Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views89 pages

Unit 1 Notes C Programming (2) For First Year

C programming notes for 1st year

Uploaded by

fakizaladafath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views89 pages

Unit 1 Notes C Programming (2) For First Year

C programming notes for 1st year

Uploaded by

fakizaladafath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

UNIT 1

Module I Problem Solving and Introduction to C


Problem definition – Logical Reasoning– Pseudo Code – Flow Chart– Algorithm.
Introduction to C–Structure of C– Tokens–C character set– Identifiers and Keywords– Data
types–Variables – Constants – Input and Output Statements–Operators and Expressions.
1. Problem definition:
“It is an action to identify the problem, to understand the problem, and to understand any
Constraints that may be the limits of the solution.” This is the first step to develop the program.
In this we understand the problem for which the program has to be developed. That is, the problem
is identified and understood in this.
In this step, the problem is formally defined.
In this all the factors like – input/output, memory requirement, processing requirement, error
handling etc. are discussed.
Processes (problem solving steps):
1.Understanding the Problem:
Here we try to understand to solve the problem completely. Before taking the next step, you mustbe
absolutely sure of the motives of a problem.
2.Problem Analysis:
Once we fully understand how to solve the problem, we look for different ways to solve the
problem and evaluate each of these methods. The idea here is to find the right solution to the
problem in question.
3. Developing Solutions:
Here an overview of the sequence of operations resulting from the analysis phase is extended to a
step by step solution to the problem in question.
4. Coding and Implementation:
The final step in problem solving is to translate the detailed sequence of operations into a language
that the computer can understand. Here each step is converted into its equivalent instruction or
instruction in the computer language which has been selected for implementation.
2. Logical Reasoning
Logical reasoning is the process of applying rules to problem solving. Algorithms are designed
as a set of steps to follow to solve a problem. At the same time, a set of rules is determined. For
example, Selection is based on rules:
1. if a condition is met, do this
2. if not, do that
Why use logical reasoning?
Algorithms are step-by-step instructions to solve a problem, created along with rules that decide
which path to take when a decision is faced.
When trying to solve a problem, it may be that more than one solution is found. A different
algorithm can be built from each solution. Logical reasoning determines if algorithms will work by
predicting what happens when the algorithm’s steps - and the rules they consist of - are followed.
Predictions from each algorithm can be used to compare solutions and decide on the bestone.
3. Pseudo Code:
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not
useany programming language in its representation instead it uses the simple English language text
as it is intended for human understanding rather than machine reading. Pseudocode is the
intermediate state between an idea and its implementation(code) in a high-level language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem.
Pseudocode is an intermediate state between algorithm and program that plays supports the
transition of the algorithm into the program.
Definition:
 Pseudo” means initiation or false.
 “Code” means the set of statements or instructions written in a programming language.
 Pseudocode is also called as “Program Design Language [PDL]”
 Pseudocode is a Programming Analysis Tool, which is commonly used for planning he
program logic.
 Pseudocode is written in normal English and cannot be understood by the computer.
 Set of instructions that mimic programming language instructions
 An informal high-level description of the operating principle of a computer program. It uses
the structural conventions of a programming language, but is intended for human reading
rather than machine reading.
Rules for writing Pseudocode:
1. Write one statement per line
2. Capitalize initial keywords (READ, WRITE, IF, WHILE, UNTIL).
3. Indent to show hierarchy.
4. End multiline structure.
5. Keep statements language.
Advantages
• It can be done easily in any word processor.
• It can be easily modified as compared to flowchart.
• Its implementation is very useful in structured design elements.
• It can be written easily.
• It can be read and understood easily.
• Converting a pseudocode to programming language is very easy compared with converting a
flowchart to programming language.
Disadvantage
• It is not visual.
• We do not get a picture of the design.
• There is no standardized style or format.
• For a beginner, it is more difficult to follow the logic or write pseudocode as compared to
flowchart.
Examples Pseudocode:
Problem 1: Calculate area of circleBEGIN
READ radius, r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
PRINT Area
END
Problem 2: Find the greater number between two numbers.BEGIN
Read A, B
IF A is less than BBIG = B
SMALL = A
ELSE
BIG = A
SMALL = B
WRITE / DISPLAY BIG, SMALL
END
Problem 3: The Average Of Two Numbers
BEGIN
WRITE “Please enter two numbers to add”
READ num1
READ num2
READ num3
Sum = num1+num2+num3
Avg = Sum/3
WRITE Sum, Avg
END
Problem 3: To check whether number is odd or even
START.
DISPLAY "Enter the Number - "
READ number.
IF number MOD 2 = 0 THEN.
DISPLAY "Number is Even"
ELSE.
DISPLAY "Number is Odd"
END IF.
4. Flowchart:
What is a Flowchart?
Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-
planning tool to solve a problem. It makes use of symbols which are connected among them to
indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs:
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A
pause/halt is generally used in a program logic under some error conditions. Terminal is the first
and last symbols in the flowchart.

2. Input/Output: A parallelogram denotes any function of input/output type. Program


instructions that take input from input devices and display output on output devices are indicated
with parallelogram in a flowchart.
3. Processing: A box represents arithmetic instructions. All arithmetic processes such as adding,
subtracting, multiplication and division are indicated by action or process symbol.

4. Decision: Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.

5. Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it
is useful to use connectors to avoid any confusions. It is represented by a circle.

6. Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of flowchart.
Rules For Creating Flowchart :
A flowchart is a graphical representation of an algorithm.it should follow some rules while
creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.
Advantages of Flowchart:

 Flowcharts are a better way of communicating the logic of the system.


 Flowcharts act as a guide for blueprint during program designed.

 Flowcharts help in debugging process.


 With the help of flowcharts programs can be easily analyzed.
 It provides better documentation.
 Flowcharts serve as a good proper documentation.
 Easy to trace errors in the software.
 Easy to understand.
 The flowchart can be reused for inconvenience in the future.
 It helps to provide correct logic.
Disadvantages of Flowchart:

 It is difficult to draw flowcharts for large and complex programs. There is no standard to
determine the amount of detail.

 Difficult to reproduce the flowcharts.

 It is very difficult to modify the Flowchart.Making a flowchart is costly.

 Some developer thinks that it is waste of time.It makes software processes low.

 If changes are done in software, then the flowchart must be redrawn


Example : Draw a flowchart to input two numbers from the user and display the largest of
two numbers .

2: Draw a flowchart to Calculate The Average Of Two Numbers


3: Draw a flowchart to Input Number And Check If They Are Odd Or Even

5. ALGORITHM:
An algorithm is a step-by-step procedure to solve a given problem. In the context of computer
science, particularly with the C programming language, an algorithm is used to create a solution
that computers can understand and execute.
It is essential to have a strong understanding of algorithms in C to create efficient programs and
solve complex problems. Dive deeper into the basic concepts, types, and design techniques of
algorithms in C in the following sections.
Basic concepts of algorithm in C:

An algorithm in C is defined as a set of instructions that, when followed, lead to a specific


outcome. Algorithms consist of various components and concepts to ensure clarity, efficiency,
and functionality.
Some essential components and concepts of an algorithm in C include:
Input: The data provided to the algorithm to solve a problem.
Output: The result obtained after executing the algorithm.
Step-by-step procedure: A sequence of operations performed on the input data based on the
algorithm's design.
Control structure: Logical constructs used to manipulate the flow of execution in the algorithm,
such as conditional statements, loops, and branching statements.
Data structures: Structures used to store and organize data, such as arrays, linked lists, stacks,
and queues.
Advantages of Algorithms:
It is easy to understand.
An algorithm is a step-wise representation of a solution to a given problem.
In an Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
Disadvantages of Algorithms:
Writing an algorithm takes a long time so it is time-consuming.
Understanding complex logic through algorithms can be very difficult.
Branching and Looping statements are difficult to show in Algorithms(imp).
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-requisite:
The problem that is to be solved by this algorithm i.e. clear problem definition.
The constraints of the problem must be considered while solving the problem.
The input to be taken to solve the problem.
The output is to be expected when the problem is solved.
The solution to this problem is within the given constraints.
Then the algorithm is written with the help of the above parameters such that it solves the
problem.
1. Algorithm to add 3 numbers and print their sum:
STEP 1: Start the program.
STEP 2: Read the values of ‘a’&’b’.
STEP 3: Compute the sum of the entered numbers ‘a’,’b’,c=a+b.
STEP 4: Print the value of ‘c’.
STEP 5: Stop the program.
2. finding the area, circumference of circle
Step 1 : Start the program
Step 2 : Define constant pi= 3.14
Step 3 : Read the value of radius
Step 4 : Calculate area using formulae pi*radius2
Step 5 : Calculate circumference using formulae 2*pi*radius
Step 6 : Print area and circumference
Step 7 : Stop the program
3. Leap Year Or Not:
Step1: Start the program
Step2: Declare year as int data type
Step3: Read the year
Step4: Check if (ye%4==0)
STEP4.1: Print “It is a leap year”
Step5: Else Step: Print “It is not a leap year”
Step6: stop the program.
4. ODD OR EVEN
Step-1: Start the program.
Step-2: Read num
Step-3: If the number is divided by 2 , print the given number is even .
Step-4: If the number is not divided by 2, print the given number is odd.
Step-5: Stop the program.
6. INTRODUCTION TO C:
What is C?:
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories
in 1972.
It is a very popular language, despite being old. The main reason for its popularity is because it is
a fundamental language in the field of computer science.
C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Why Learn C?
It is one of the most popular programming language in the world
If you know C, you will have no problem learning other popular programming languages such as
Java, Python, C++, C#, etc, as the syntax is similar
C is very fast, compared to other programming languages, like Java and Python
C is very versatile; it can be used in both applications and technologies
Let's create our first C file.
Open Codeblocks and go to File > New > Empty File.
Write the following C code and save the file as myfirstprogram.c (File > Save File as)

#include <stdio.h>

int main() {
printf("Hello World!");
return 0;
}

o/p:Hello World
Simple program:
#include <stdio.h>
int main() {
int a = 10;
printf("%d", a);
return 0;
}
o/p:10
STRUCTURE OF C PROGRAM

The structure of a C program means the specific structure to start the programming in the
C language.

It gives us a basic idea of the order of the sections in a program. We get to know when
and where to use a particular statement, variable, function, curly braces, parentheses, etc.

There are 6 basic sections responsible for the proper execution of a program. Sections
are mentioned below

1. Documentation
2. Preprocessor Section
3. Definition
4. Declaration
5. Main() Function
{
Declaration part;
Executable part;
}
6. Sub Programs
Function 1
Function 2
…………..
…………..
Function n
1. Documentation

This section consists of the description of the program, the name of the program, and
the creation date and time of the program. It is specified at the start of the program in the form
of comments.

A comment makes the program easier to read and understand. These are the statements
that are not executed by the compiler or an interpreter.

There are two types of comments in C language:

 Single-line comment: A single-line comment starts with ( // ) double


forward slash. It extends till the end of the line and we don’t need to
specify its end.
Syntax
// This is a single line comment

 Multi-line comment: The Multi-line comment in C starts with a


forward slash and asterisk ( /* ) and ends with an asterisk and
forward slash ( */ ). Any text between /* and */ is treated as a
comment and is ignored by the compiler.

Syntax

/*Comment starts

continues

continues

Comment ends*/
2. Preprocessor Section

The preprocessor section contains all the header files used in a program. It informs the
system to link the header files to the system libraries, Preprocessors are programs that process
our source code before compilation. Preprocessor directives start with the ‘#’ symbol.
There is no semi-colon (;) at the end

#include<stdio.h>
#include<conio.h>

The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled. The #include<stdio.h> consists of the contents of the standard input output files,
which contains the definition of stdin, stdout, and stderr. There are various header files available
for different purpose

3. Definition

The #define preprocessor is used to create a constant throughout the program.


#define a = 2

4. Declaration

The variables declared in this section can be used anywhere in the program.

They’re accessible to all the function of the program

EX:

Float num=2.54;

Int a=5;

Char ch=’z’;
There are two types of declaration

Local variable: A variable that is declared and using inside the function declared and using
inside the function or block is called local variable

Ex:

Public int add()

int a=4;

int b= 5;

return a+b;

Global variable: A variable that is declared outside the function or block is called a global
variable

Ex:

int a=4;

int b=5;

Public int add()

return a+b;

}
5. Main() Function

Every C program must have a main function. Operations like declaration and execution
are performed inside the curly braces of the main program. The return type of the main()
function can be int as well as void too. void() main tells the compiler that the program will not
return any value. The int main() tells the compiler that the program will return an integer value.

int main()

Or

void main()

6. Sub Programs

The user defined functions specified the functions specified as per the requirements of the
user. For example, color(), sum(), division(), etc.

The control of the program is shifted to the called function whenever they are called
from the main or outside the main() function

Ex:

int sum(int x, int y)

return x+y;

}
Example Program

/**

* file: sum.c

* author: you

* description: program to find sum.

*/

// Link

#include <stdio.h>

// Definition

#define X 20

// Global Declaration

int sum(int y);

// Main() Function

int main(void)

int y = 55;
printf("Sum: %d", sum(y));

return 0;

// Subprogram

int sum(int y)

return y + X;

Output
Sum: 75
TOKENS IN C:
A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying to
assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using C
preprocessor directives. C language supports 32 keywords which are given below:
const float short unsigned continue for signed void
default goto sizeof volatile do if static while

auto double int struct break else long switch


case enum register typedef char extern return union

C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later program statements to
refer to the associated value. A special identifier called a statement label can be used in goto
statements.
Rules for Naming Identifiers
 Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.

For example,
main: method name.

a: variable name.
C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;

C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas,
a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

C Token – Special Symbols


The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references. These indicate
single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating parameters in
functioncalls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
whyeach individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.

Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.

Period (.): Used to access members of a structure or union.

Tilde(~): Used as a destructor to free some space from memory.

C Token – Operators

Operators are symbols that trigger an action when applied to C variables and other objects. The
data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are known
as unaryoperators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called
binaryoperators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the ternary
operator. Conditional Operator(?) is also called the ternary operator
CHARACTER SET IN C
In the C programming language, the character set refers to a set of all the valid characters that
we can use in the source program for forming words, expressions, and numbers.
The source character set contains all the characters that we want to use for the source program
text.
On the other hand, the execution character set consists of the set of those characters that we
might use during the execution of any program. Thus, it is not a prerequisite that the execution
character set and the source character set will be the same, or they will match altogether

Use of Character Set in C


In any language for communication, the C programming language also consists of a set of
various different types of characters. These are known as the characters in C. They include
digits, alphabets, special symbols, etc. The C language provides support for about 256
characters.
Every program that we draft for the C program consists of various statements. We use words for
constructing these statements. Meanwhile, we use characters for constructing these statements.
These characters must be from the C language character set. Let us look at the set of characters
offered by the C language.
Types of Characters in C
The C programming language provides support for the following types of characters. In
other words, these are the valid characters that we can use in the C language:
Digits
Alphabets
Main Characters
All of these serve a different set of purposes, and we use them in different contexts in the C
language
Alphabets
The C programming language provides support for all the alphabets that we use in the English
language. Thus, in simpler words, a C program would easily support a total of 52 different
characters- 26 uppercase and 26 lowercase.
Lowercase Alphabets a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
Uppercase Alphabets A to Z A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U,
V, W, X,Y, Z

Digits

The C programming language provides the support for all the digits that help in constructing/
supporting the numeric values or expressions in a program. These range from 0 to 9, and also
help in defining an identifier. Thus, the C language supports a total of 10 digits for
constructing the numeric values or expressions in any program.

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Characters

We use some special characters in the C language for some special purposes, such as logical
operations, mathematical operations, checking of conditions, backspaces, white spaces, etc.

We can also use these characters for defining the identifiers in a much better way. For instance,
we use underscores for constructing a longer name for a variable, etc.

The C programming language provides support for the following types of special characters:

Special Characters `~@!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

White Spaces

The white spaces in the C programming language contain the following:

Blank Spaces

Carriage Return

Tab

New Line
Summary of Special Characters in C
Here is a table that represents all the types of character sets that we can use in the C language:
DATA TYPE IN C

Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.

Each data type has a size defined in bits/bytes and has a range for the values that these
data types can hold.

PRIMITIVE DATA TYPE

The Primitive or primary data type in the C programming language are the basic data
types. All the Primitive data types are already defined in the system. There are four primitive
data types
Integer Data type

 The integer data type in C is used to store the whole numbers without decimal values.
 Integer data type is represented by the ‘int’ keyword, and it can be both signed and
unsigned.
 By default, the value assigned to an integer variable is considered positive if it is
unsigned.
 The integer data type is further divided into short, int, and long data types.
 What is a signed data type: Using signed data type both positive and negative values we
can store.
 What is the unsigned data type: Using unsigned data types; we can store only positive
values.
 What is a short and long data type:
If you need to use a large number, you can use a type specifier long

If you need to use a small integer number, you can use a type specifier short

 Syntax
int variable_name;
Data type Meaning Memory Range Format
size Specifier
signed short int The signed short data type is used 2 -32,768 to 32,767 %hd
to store positive and negative small
integer values.
signed int The signed data type is used to 4 -2,147,483,648 to %d
store positive and negative integer 2,147,483,647
values.
signed long int The signed long data type is used to 4 -2,147,483,648 to %ld
store positive and negative long 2,147,483,647
integer values.
unsigned short int The unsigned short data type is 2 0 to 65,535 %hu
used to store only positive small
integer values.
unsigned int The unsigned data type is used to 4 0 to 4,294,967,295 %u
store only positive integer values.
unsigned long int The unsigned long data type is used 4 0 to 4,294,967,295 %lu
to store only positive long integer
values.

Example program

// C program to print Integer data types.

#include <stdio.h>

int main()

{ // Integer value with positive data.

int a = 9;

// integer value with negative data.

int b = -9;

long int d = 99998L;

printf("Integer value with positive data: %d\n", a);

printf("Integer value with negative data: %d\n", b);


printf("Integer value with an long int data: %ld", d);

return 0;

Output

Integer value with positive data: 9

Integer value with negative data: -9

Integer value with an long int data: 99998

Character Data Type

 Character data type allows its variable to store only a single character.
 The storage size of the character is 1.
 For char data type, it is necessary to enclose our data in single quotes.
 Syntax
char variable_name = ‘value’;

 The character data type is divided into two types one is signed data type and the second
one is unsigned data type. Both Signed data type and unsigned data type occupy only one
byte of memory.
 Unsigned means it will accept only positive values and the signed means it will accept
both positive as well as negative values. Whatever the type either signed or unsigned, the
character occupies only one byte.
Data Type Memory (bytes) Range Format Specifier

Char 1 byte −128 to 127 %c

signed char 1 byte −128 to 127 %c

unsigned char 1 byte 0 to 255 %c

Example program

#include <stdio.h>

void main()

char c;

c = 'a' ;

printf("%c"c);

Output

Float Data Type

 Float data type is used to store floating-point values.


 Float in C is used to store decimal and exponential values.
 It is used to store decimal numbers (numbers with floating point values) with single
precision.
 Syntax

float varaible_name;
Data type Meaning Memory Range PRECISION Format
(byte) Specifier
float float’ used to stores real 4 byte 1.2E-38 to 6 decimal places %f
numbers in 32 bits with 3.4E+38
up to 6 decimal points
precision.
double double type also similar 8 byte 2.3E-308 to 14 decimal places %lf
to float stores in 64 bits 1.7E+308
with more accurate
precision up to 14
decimals
long double Long double further 10 byte 3.4E-4932 19 decimal places %Lf
extends the precision to
using 80 bits and 19 1.1E+4932
decimal places.

Example program

#include <stdio.h>

int main()

float a = 9.0;

double b = 12.293123;

printf(“Value of Float a = %f\n", a);

printf(“Value of Double b = %lf\n", b);

return 0;

Output:

Value of Float a= 9.0

Value of Double b = 12.293123


Void Data Type

 This means no value. This data type is mostly used when we define functions.
The void data type is used when a function does not return anything. It occupies 0
bytes of memory. We use the void keyword for void data type.
 Syntax

void function()

//your code goes here

DERIVED DATATYPE

 The data-types that are derived from the primitive or built-in datatypes are referred to
as Derived Data Types.
 Derived data types do not create new data types. Instead, they add some functionality to
the existing data types.
 Derived data types are derived from the primitive data types by adding some extra
relationships with the various elements of the primary data types. The derived data type
can be used to represent a single value or multiple values.
 Given below are the various derived data types used in C
 Array.
 Functions.
 Pointers.
Array
An array is one of the most frequently used data types (derived) in the C language. We
can form arrays by collecting various primitive data types such as int, float, char, etc. Thus,
when we create a collection of these data types and store them in the contiguous memory
location, they are known as arrays.
Syntax
data_type arr_name[size];

Example program
#include<stdio.h>
int main(){
Int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75; //traversal of array
for(int i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0; }

Output

80 60 70 85 75

Function

A function is a piece of code that performs some specific task when invoked in the
program. It can be called from anywhere and any number of times in the program. The return
value i.e., what type of value it will return depends upon the return type of the function.

In C, a function can be called by types: call by value and call by reference. When the
function is called by value, a copy of the variable is passed as the argument whereas when the
function is called by the reference, the address or reference of variable itself is passed to the
function.

Syntax

return_type function_name(parameters);

Example program

#include<stdio.h>

Void sum(int, int);

Void main()

int x, y;
Printf(“enter 2 number”);

Scanf(“%d %d,” &x, &y);

Sum(x,y);

Void sum(int x, int y)

int c;

c=x+y;

Printf(“%d”, c);

Output

Enter 2 number

21

Pointers

 A pointer can be defined as a variable that stores the address of other variables. This
address signifies where that variable is located in the memory.
 Syntax: datatype *pointer_name;
 Description of the syntax
type: This is the data type that specifies the type of value to which the pointer is
pointing.
pointer_name: This is the name of the pointer. To specify the name of a pointer,
you must follow the same rules which are applicable while declaring a usual
variable in C. Apart from these rules, a pointer must always be preceded by an
asterisk(*).

Example program
#include <stdio.h>
#include <conio.h>
int main ()
{
int count = 5; //declaring the local variables
int *ptr = &count; //pointer variable
printf("The value of count variable is %d\n", count);
printf("Address of count variable: %x\n", ptr);
getch();
return 0;
}

Output
The value of count variable is 5
Address of count variable: da5f4764

USER-DEFINED DATA TYPES


 These user-defined data types are constructed using a combination of fundamental data
types and derived data types.
 Fundamental data types are basic built-in types of C programming language. These are
integer data type (int), floating data type (float), and character data type (char). Derived
data types are derived from fundamental data types, like functions, arrays, and pointers
in the C programming language.
 Structures (struct)
 Union
 Enumerations (enum)

STRUCTURES

 Structures are used to group multiple variables of different data types. It gathers
together, different atomic information that comprises a given entity.
 Members of the structures can be accessed using the dot (.) operator.
 Syntax

Struct <name>

<data type 1> <variable name 1>,

<data type 2> <variable name 2>, ...

};
Example program

#include <stdio.h>

struct Book { // Struct Book Declaration.

char name[100];

int number_of_pages;

char author[100];

float price;

};

int main()

{ // Create a variable of type struct Book.

struct Book myBook;

// Initialize data members of the struct Book myBook.

strcpy(myBook.name, "CLRS");

strcpy(myBook.author, "C.L.R.S.");

myBook.price = 1000.0;

myBook.number_of_pages = 2000;

// Print the data members.

printf("Book Name: %s\n", myBook.name);

printf("Number of Pages: %d\n", myBook.number_of_pages);

printf("Author: %s\n", myBook.author);

printf("Price: %f\n", myBook.price);

OUTPUT

Book Name: CLRS

Number of Pages: 2000


Author: C.L.R.S.

Price: 1000.000000

UNION

 It is a collection of different data types in the C programming language that allows


users to store different data types at the same memory location in the RAM.
 Unions are like structures in the C programming language with an additional property
that all members of a union share the same memory location in the RAM.
 A Union is declared using the keyword union and members are accessed using the dot
(.) operator.
 Syntax

union <name>

<data type 1> <variable name 1>,

<data type 2> <variable name 2>, ... };

Example program

# include<stdio.h>

struct book {

// Create a struct with the same data member as the union.

char name[100];

int pages;

int prices;

};

union Book {

// Create a union Book with some data members.

char name[100];

int pages;

int price;
};

int main() {

// Compare the size of struct book and union Book.

printf("Size of union Book: %ld\n", sizeof(union Book));

printf("Size of struct Book: %ld\n", sizeof(struct book));

// Create a variable of type union Book. Making changes in one variable,

// changes the data in the memory location.

union Book myBook;

myBook.pages = 10; myBook.price = 10

printf("Pages in myBook: %d\n", myBook.pages);

printf("Price in myBook: %d\n", myBook.price);

Output

Size of union Book: 100

Size of struct Book: 108

Pages in myBook: 10

Price in myBook: 10

ENUMERATIONS (ENUM)

 Enumerations in C are a way to define constants


 These constants are usually defined globally and are used throughout the code.
 The constant values are generally integers and are given meaningful names to increase
the readability of the program and highlight the need for the constants being used.
 Syntax

enum <identifier>

value1, value2, value3, ... }


Example program

enum month {

// Create enum with default values assigned by compiler.

JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC

// JAN = 0, FEB = 1, APR = 2

};

enum monthDays {

// Values are assigned to constants.

JANUARY = 31, FEBRUARY = 28, MARCH = 31

};

enum colors {

// Starting value is assigned.

RED, GREEN, BLUE

// RED = 1, GREEN = 2, BLUE = 3

};

int main() {

printf("January Month Number: %d\n", JAN);

printf("Number of days in January: %d\n", JANUARY);

printf("Favorite Color: %d\n", BLUE);

Output

January Month Number: 0

Number of days in January: 31

Favorite Color: 3
VARIABLES IN C

 A variable is a data name that may used to store a data value.


 Different types of variables require different amounts of memory, and have some
specific set of operations which can be applied on them.
 Variables actually refer to the address of the memory where data is stored
 The name of a variable can be composed of letters, digits, and the underscore character.

Rules for defining variables

 A variable can have alphabets, digits, and underscore.


 A variable name can start with the alphabet, and underscore only. It can’t start with a
digit.
 A variable name must not be any reserved word or keyword, e.g. int, goto , etc.
Declaration of Variables

Syntax: datatype variable_name;

datatype variable1_name, variable2_name, variable3_name;

Example:

int rollno;

char gender;

char name[20];

float salary;

int rollno, year, age;

Initializing the variables


Assignment Statement
Syntax: datatype variable_name=constant;
Example: int rollno=15;
char gender=‘M’;
char name[20]=“apple”;
float salary=2500.00;
int rollno=15, year=2020, age=20;
Initializing the variables
Reading data from keyboard
Syntax:
scanf(“control string”,&variable1, &variable2….);
Example:
scanf(“%d%c”,&rollno, &gender);
Scanf(“%d%d%d%d”,&a,&b,&c,&d);

Scope of the Variable

1. Local Variable : A variable that is declared and used inside the function or block is
called local variable. It’s scope is limited to function or block. It cannot be used outside
the block.Local variables need to be initialized before use.
2. Global Variable : A variable that is declared outside the function or block is called a
global variable. It is declared at the starting of program. It is available to all the
functions.
3. Example –

What is format specifier?

If you want to read the information or if you want to display the information, formatting
is very important. In which format do you have to read information and in which format do you
have to print the information. That you have to specify to the computer using a format specifier

Example:
#include <stdio.h>
int main()
{
int a = 10;
printf("%d", a);
return 0;
}
Output: 10
C OPERATORS

 Operators are used to perform operations on variables and values.


 An operator is a symbol that specifies an operation to be performed on the operands.
 Example : a + b
a, b  operands
+ -  operator

 Operators in C Language are the special kind of symbols that performs certain operations
on the data.
 The collection of operators along with the data or operands is known as expression.
 There are following types of operators to perform different types of operations in C
language.

UNARY OPERATION
A Unary Operator in C is an operator that takes a single operand in an expression or a
statement.
Types of Unary Operators are:
 Increment operators (++): Example: (++x)
 Decrement operators (–): Example: (--x)
Increment Operators
Increment Operators is a unary operator. It takes one value at a time.

Increment operators are used to increase the value by one

It is classified into two types:

 Post Increment Operator


 Pre Increment Operator

Post Increment Operators: A post-increment operator is used to increment the value of the
variable after executing the expression completely in which post-increment is used. In the Post-
Increment, value is first used in an expression and then incremented.

Syntax: Variable++;
Example: x++;

Pre Increment Operators: A pre-increment operator is used to increment the value of a variable
before using it in an expression. In the Pre-Increment, value is first incremented and then used
inside the expression.

Syntax: ++Variable;
Example: ++x;

Example program
#include<stdio.h>
int main()
{
int a = 11, b = 90;
printf("++a = %d \n", ++a);
printf(“b++ = %d \n", b++);
return 0;
}
Output
++a = 12
b++ = 91

Decrement Operators
Decrement Operators is a unary operator. It takes one value at a time.
Decrement Operators are used to increase the value by one
It is classified into two types:
 Post Decrement Operator
 Pre Decrement Operator
Post Decrement Operators: A post-decrement operator is used to decrement the value of the
variable after executing the expression completely in which post-decrement is used. In the Post-
decrement, value is first used in an expression and then decremented.

Syntax: Variable--;
Example: x--;

Pre Decrement Operators : A pre-decrement operator is used to decrement the value of a


variable before using it in an expression. In the Pre-decrement, value is first decremented and
then used inside the expression.

Syntax: --Variable;
Example: --x;
Example Program
#include<stdio.h>
int main()
{
int a = 11, b = 90;
printf(“--a = %d \n", --a);
printf(“b--= %d \n", b--);
return 0;
}
Output
--a = 10
b-- = 89

Binary Operators

A Binary Operator in C is an operator that takes two operands in an expression or a


statement. Types of Binary Operators are:
 Arithmetic operators
 Logical operators
 Relational operators
 Bit-wise operators
 Assignment operators

Arithmetic Operator

Arithmetic Operators are the operators which are used to perform mathematical
calculations. It performs all the operations on numerical values (constants and variables).
Operator Name Description Example

+ Addition Adds together two x+y


values

- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y


remainder

Example Program
#include <stdio.h>
int main()
{
int a = 7,b = 5, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a is divided by b = %d \n",c);
return 0;}
Output
a+b = 12
a-b = 2
a*b = 35
a/b = 1
Remainder when a divided by b = 2
Logical Operator
 Logical operators are used to determine the logic between variables or values
 The logical operators are used when we want to check or test more than one condition
and make decisions.
 It returns either 0 or 1 depending upon the condition whether the expression results in
true or false.

Operator Name Description Example

&& Logical and Returns true if both x < 5 && x < 10


statements are true

|| Logical or Returns true if one x < 5 || x < 4


of the statements is
true

! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true

Example Program
#include <stdio.h>
int main()
{ int a = 15, b = 15, c = 20, results;
results = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", results);
results = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", results);
results = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", results);
results = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", results);
results = !(a != b);
printf("!(a != b) is %d \n", results);
results = !(a == b);
printf("!(a == b) is %d \n", results); return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0

Bitwise Operator
 Bitwise operator is used for the manipulation of data at the bit level.
 Bitwise operator first converts the integer into its binary representation then performs its
operation.
 Bitwise operators subsist of two digits, either 0 or 1. The truth tables for &, |, and ^ is as
follows –
P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 12 and B = 25 in binary format, they will be as follows –

12 = 00001100 (In Binary)


25 = 00011001 (In Binary) A&B
Bit Operation of 12 and 25
00001100
&
00011001

00001000 = 8 (In decimal)


Example program
#include <stdio.h>
intmain()
{
inta = 12, b = 25;
printf("Output = %d", a&b);
return0;
}

Output = 8

Operator Name Description Example

& AND Binary AND Operator. (A & B) = 16, i.e.


It copies a bit to the result if it exists 00010000
in both the operands.

| OR Binary OR Operator. (A | B) = 59, i.e.


It copies a bit if and only if it exists in 00111011
either operand.

^ XOR Binary XOR Operator. (A ^ B) = 43, i.e.


It copies the bit only if it is set in one 00101011
operand but not both.

~ One's Binary One's Complement Operator. (~A ) = ~(50), i.e,. -


Complement It is unary and has the effect of 0111101
'flipping' bits.

<< Left Shift Binary Left Shift Operator. A << 2 = 200 i.e.
The value of the left operands is 11001000
moved left by the number of bits
specified by the right operand.

>> Right Shift Binary Right Shift Operator. A >> 2 = 12 i.e.,


The value of the left operands is 00001100
moved right by the number of bits
specified by the right operand.
Bitwise AND operator (&)

 The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.

 Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
&
00011001
___________
00001000 = 8 (In decimal)
Example program
#include <stdio.h>
intmain()
{
inta = 12, b = 25;
printf("Output = %d", a&b);
return0;
}
Output = 8

Bitwise OR operator (|)

 The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1.

 Let us suppose the bitwise OR operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
||
00011001
___________
00011101 = 29 (In decimal)
Example program
#include <stdio.h>
intmain()
{
inta = 12, b = 25;
printf("Output = %d", a|b);
return0;
}
Output = 29

Shift Operators in C programming


There are two shift operators in C programming:

Right shift operator : Right shift operator shifts all bits towards right by certain number of
specified bits. It is denoted by >>.

212 = 11010100 (In binary)


212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left shift operator: Left shift operator shifts all bits towards left by certain number of specified
bits. It is denoted by <<.

212 = 11010100 (In binary)


212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

Example program
#include <stdio.h>
int main()
{
intnum=212, i;
for(i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i); printf("\n");
for(i=0; i<=2; ++i)
printf("Left shift by %d: %d\n", i, num<<i);
return0;
}
OUTPUT
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848

Assignment Operator

An assignment operator is mainly responsible for assigning a value to a variable in a


program.

The most commonly used Assignment Operator is =.

The above diagram helps us to understand that the RHS value is assigned to
the LHS variable.

The LHS and RHS are known as Operands.

So the operand on the LHS of the assignment operator must be a variable and operand
on RHS must be a constant , variable or expression.

For example, x = 4; then that means value 4 is assigned to variable x or we can say that
variable x holds value 4.
Operator Name of Operator What it does How it is used

= assignment assign value of variable b to variable a = b


a

+= plus assign a = a+b (adds values of a to b and a += b


assign this value to a)

-= minus assign a = a-b (subtracts values of b from a a -= b


and assign this value to a)

*= times assign a = a*b (Multiplies a with b and a *= b


assign the value to a)

/= div assign a = a/b (divides a by b and assigns the a /= b


value to a)

%= Mod assign a = a%b (divides a by b and assigns a %= b


the value of the remainder to a)

Example program

#include <stdio.h>

int main()

int a = 7, b;

b = a; // b is 7

printf("b = %d\n", b);

b += a; // b is 14
printf("b = %d\n", b);

b -= a; // b is 7

printf("b = %d\n", b);

b *= a; // b is 49

printf("b = %d\n", b);

b /= a; // b is 7

printf("c = %d\n", c);

b %= a; // b = 0

printf("b = %d\n", b);

return 0; }

Output

b=7

b = 14

b=7

b = 49

b=7

b=0

Ternary Operator

This is an operator that takes three arguments.

There are Two type

 Conditional operator (?:)

 Sizeof()
Conditional operator (?:)

This is an operator that takes three arguments. The first argument is a comparison
argument, the second is the result of a true comparison, and the third is the result of a false
comparison

Syntax

testCondition ? expression1 : expression 2;

The testCondition is a boolean expression that results in either true or false. If the
condition is

true - expression1 (before the colon) is executed

false - expression2 (after the colon) is executed

Example Program

#include <stdio.h>

int main() {

int age; // take input from users

printf("Enter your age: ");

scanf("%d", &age);

// ternary operator to find if a person can vote or not

(age >= 18) ? printf("You can vote") : printf("You cannot vote");

return 0;

Output

Enter your age: 12

You cannot vote


SIZEOF() OPERATOR

 Sizeof is a compile-time unary operator which can be used to compute the size of its
operand.

 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
sizeof can be applied to any data type, including primitive types such as integer and
floating-point types, pointer types, or compound datatypes such as Structure, union, etc.

 Syntax:

sizeof(Expression);

Example program

// C Program to print size of // different data type in C

#include <stdio.h>

int main()

int size_of_int=sizeof(int);

int size_of_char= sizeof(char);

int size_of_float=sizeof(float);

int size_of_double=sizeof(double);

printf("The size of int data type : %d\n",size_of_int );

printf("The size of char data type : %d\n",size_of_char);

printf("The size of float data type : %d\n",size_of_float);

printf("The size of double data type : %d",size_of_double);

return 0;

}
Output

The size of int data type : 4

The size of char data type : 1

The size of float data type : 4

The size of double data type : 8

WHEN THE OPERAND IS AN EXPRESSION

When sizeof() is used with the expression, it returns the size of the expression.

// C Program To demonstrate

// operand as expression

#include <stdio.h>

int main()

int a = 0;

double d = 10.21;

printf("%lu", sizeof(a + d));

return 0;

Expressions

An expression is a formula in which operands are linked to each other by the use of

operators to compute a value.

An operand can be a function reference, a variable, an array element or a constant.

Syntax : variable = expression;

Example : c= (a+b)*d;
There are four types of expressions exist in C:

 Arithmetic expressions

 Relational expressions

 Logical expressions

 Conditional expressions

Example:

Sum = 3 –3 + 77 * 3 -1 (ans: 230)

(3-9)/ 3+77 * (3-1) (ans= 152)

PRECEDENCE AND ASSOCIATIVITY IN C

Precedence of operators: determines which operation is performed first in an expression with


more than one operators with different precedence.

10 + 20 * 30
Associativity of operators: is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right or Right to Left. For example: ‘*’ and ‘/’
have same precedence and their associativity is Left to Right, so the expression “100 / 10 *
10” is treated as “(100 / 10) * 10”.

Example Program

#include <stdio.h>

main()

int a = 20;

int b = 10;

int c = 15;

int d = 5; int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5

printf("Value of (a + b) * c / d is : %d\n", e );

e = ((a + b) * c) / d; // (30 * 15 ) / 5

printf("Value of ((a + b) * c) / d is : %d\n" , e );

e = (a + b) * (c / d); // (30) * (15/5)

printf("Value of (a + b) * (c / d) is : %d\n", e );

e = a + (b * c) / d; // 20 + (150/5)

printf("Value of a + (b * c) / d is : %d\n" , e );

return 0; }
INPUT/OUPUT STATEMENT

 Input and Output statement are used to read and write the data
 These are embedded in stdio.h (standard Input/Output header file).
 Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
 There are mainly two of Input/Output functions are used for this purpose.

 Unformatted I/O functions

 Formatted I/O functions

UNFORMATTED I/O FUNCTIONS

 Unformatted I/O functions are used only for character data type or character array/string
and cannot be used for any other datatype.
 These functions are used to read single input from the user at the console and it allows to
display the value at the console.
 There are mainly six unformatted I/O functions discussed as follows:

 getchar()

 putchar()

 gets()

 puts()

 getch()

 getche()

getch()

This function reads a single character from the keyboard by the user but doesn’t display
that character on the console screen and immediately returned without pressing enter key. This
function is declared in conio.h(header file).

Syntax:

getch();

or

vari able-name = getch();


Example Program

#include <conio.h>

#include <stdio.h>

int main()

printf("Enter any character: ");

getch();

return 0;

Output:

Enter any character:

getche():

This function reads a single character from the keyboard by the user and displays it on the
console screen and immediately returns without pressing the enter key. This function is declared
in conio.h(header file).

Syntax:

getche();

or

variable_name = getche();

Example program

#include <conio.h>

#include <stdio.h>

int main()

printf("Enter any character: ");

getche();
return 0;

Output:

Enter any character: g

getchar()

This function is used to read only a first single character from the keyboard whether
multiple characters is typed by the user and this function reads one character at one time until
and unless the enter key is pressed. This function is declared in stdio.h(header file)

Syntax:

Variable-name = getchar();

Example program

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter the character: ");

ch = getchar();

printf("%c", ch);

return 0;

Output:

Enter the character: a

a
putchar():

This function is used to display a single character at a time by passing that character
directly to it or by passing a variable that has already stored a character. This function is
declared in stdio.h(header file)

Syntax:

putchar(variable_name);

Example program

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character: ");

ch = getchar();

putchar(ch);

return 0;

Output:

Enter any character: Z

gets():

This function reads a group of characters or strings from the keyboard by the user and
these characters get stored in a character array. This function allows us to write space-separated
texts or strings. This function is declared in stdio.h(header file).

Syntax:

char str[length of string in number]; //Declare a char type variable of any length

gets(str);
Example program

#include <conio.h>

#include <stdio.h>

int main()

char name[50];

printf("Please enter some texts: ");

gets(name);

printf("You have entered: %s",name);

return 0;

Output:

Please enter some texts: geeks for geeks

You have entered: geeks for geeks

puts()

This function is used to display a group of characters or strings which is already stored in
a character array. This function is declared in stdio.h(header file).

Syntax:

puts(identifier_name );

Example program

#include <stdio.h>

int main()

char name[50];

printf("Enter your text: ");


gets(name);

printf("Your text is: ");

puts(name);

return 0;

Output:

Enter your text: GeeksforGeeks

Your text is: GeeksforGeeks

putch():

This function is used to display a single character which is given by the user and that
character prints at the current cursor location. This function is declared in conio.h(header file)

Syntax:

putch(variable_name);

Example program

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character:\n ");

ch = getch();

printf("\nEntered character is: ");

putch(ch);

return 0;

}
Output:

Enter any character:

Entered character is: d

Formatted I/O Functions

Formatted I/O Functions are used to take various inputs from the user and display multiple
outputs to the user.

These types of I/O functions can help to display the output to the user in different formats using
the format specifiers.

There are mainly six unformatted I/O functions discussed as follows:

 printf()

 scanf()

printf()

This function is to display any value like float, integer, character, string, etc on the
console screen. It is a pre-defined function that is already declared in the stdio.h(header file).

Syntax

printf("control strings",&v1,&v2,&v3,................&vn);

or

printf("Message line or text line");

Example program

#include <stdio.h>

int main()

int a;

a = 20;

printf("%d", a);

return 0;
}

Output

20

scanf():

This function is used for reading or taking any value from the keyboard by the user, these
values can be of any data type like integer, float, character, string, and many more. This function
is declared in stdio.h(header file). In scanf() function we use &(address-of operator) which is
used to store the variable value on the memory location of that variable.

Syntax:

scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example program

#include <stdio.h>

int main()

int num1;

printf("Enter a integer number: ");

scanf("%d", &num1);

printf("You have entered %d", num1);

return 0;

Output:

Enter a integer number: 56

You have entered 56


Type Conversion in C
Type conversion in C is the process of converting one data type to another. The type
conversion is only performed to those data types where conversion is possible. Type
conversion is performed by a compiler

There are two types of Conversion:


Implicit Type Conversion
Explicit Type Conversion

Implicit Type Conversion


Implicit type conversion is also called automatic type conversion. Done by the compiler
on its own, without any external trigger from the user.
Example program
#include <stdio.h>
int main()
{
int x = 17; // integer x
char y = 'c'; // character c
// y implicitly converted to int. ASCII
// value of 'c' is 99
int sum = x + y;
printf("value of sum %d/n”, sum);
return 0;
}
Output
Value of sum: 116
Explicit Type Conversion
This process is also called type casting and it is user-defined. Here the user can typecast
the result to make it of a particular data type.

syntax : (type) expression


Example program

// C program to demonstrate explicit type casting


#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);

return 0;
}
Output
sum = 2

Constants
Constants refer to fixed values that do not change during the execution of a program. They are
also called as literals.
Syntax for declaring Constant
constdata_typevariable_name= value;
(or)
constdata_type*variable_name= value;
Example :
const int batch=2019;
const float pi=3.14;
We can also use pre-processor command “define”.
Example :
#define pi 3.14
#define batch 2019
Types of Constants :
1. Integer constants: These are of the integer data type. For example,const int value = 400;
2. Floating constants or real constant :These are of the float data type. For example,const
float pi = 3.14;
3. Characte constants: These are of the character data type. For example,const char gender
= ‘f’;
4. String constants: These are also of the character data type, but differ in the declaration.
For example,const char dept[] = ‘‘ECE’’;
5. Octal constants: The number system which consists only 8 digits, from 0 to7 is called
the octal number system. The constant octal values can be declared as,const int oct =
040;(Itis the octal equivalent of the digit “32” in the decimal number system.)
6. Hexadecimal constants: The number system which consists of 16 digits, from 0 to 9 and
alphabets ‘a’ to ‘f’ is called hexadecimal number system. The constant hexadecimal
values can be declared as,const int hex = 0x40;(It is the hexadecimal equivalent of the
digit 64 in the decimal number system.).
Case-Study Problems

1. Finding the Biggest number

Algorithm for Biggest among three number

STEP 1:- START

STEP 2:- Declare three variables X,Y,Z.

STEP 3:-If X>Y&X>Z print X is the GREATEST.

STEP 4:-Otherwise if Y>Z&Y>X print Y is the GREATEST.

STEP 5:- Otherwise print Z is GREATEST.

STEP 6:- STOP

Pseudo code for Biggest among three number


1. BEGIN
2. DECLARE three variables: num1, num2, num3
3. INPUT num1, num2, and num3 from the user
4. DECLARE a variable maxNumber and initialize it to 0 (assuming all input numbers are positive)
5. IF num1 is greater than maxNumber, set maxNumber to num1
6. IF num2 is greater than maxNumber, set maxNumber to num2
7. IF num3 is greater than maxNumber, set maxNumber to num3
8. DISPLAY maxNumber as the biggest number among the three
9. END
Flowchart for Biggest among three number

2. Sum of Natural Numbers

Algorithm for Sum of Natural Numbers

Step 1:start the program

Step 2: Input a positive integer n.

Step 3: Initialize a variable sum to 0 to store the sum of natural numbers.

Step 4: Initialize a loop counter variable i to 1.

Step 5: Start a loop that continues as long as i is less than or equal to n. a. Add the value of i to sum. b.
Increment i by 1 in each iteration.

Step 6: After the loop, sum will contain the sum of natural numbers from 1 to n.

Step 7: Output the value of sum as the result.

Step 8:Stop the program


Pseudo code for Sum of Natural Numbers:

BEGIN

NUMBER i, sum=0

FOR i=1 TO 100 STEP 1 DO


sum=sum+counter
END FOR
OUTPUT sum

END

Flowchart for Sum of Natural Numbers:

3. Factorial of a Number:

Algorithm for Factorial of a Number:

Step 1: Start
Step 2: Read a number n
Step 2: Initialize variables:
i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise go to step 7
Step 4: Calculate
fact = fact * i
Step 5: Increment the i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop

Pseudo code for Factorial of a Number:

BEGIN

FOR value = 1 to number

factorial = factorial * value

END FOR

DISPLAY factorial

END

Flowchart for Factorial of a Number:


4. Fibonacci Series

Algorithm for Fibonacci Series

Step1: START

Step 2: Take integer variable A, B, C

Step 3: Set A = 0, B = 0

Step 4: DISPLAY A, B

Step 5: C = A + B

Step 6: DISPLAY C

Step 7: Set A = B, B = C

Step 8: REPEAT from 4 - 6, for n times

Step9: STOP

Pseudo code for Fibonacci Series

BEGIN

IF fib_num less than 1


DISPLAY 0

IF fib_num equals to 1
DISPLAY 1

IF fib_num equals to 2
DISPLAY 1, 1

IF fib_num greater than 2


Pre = 1,
Post = 1,

DISPLAY Pre, Post


FOR 0 to fib_num-2
Fib = Pre + Post
DISPLAY Fib
Pre = Post
Post = Fib
END FOR
END IF
END
5. Flowchart for Fibonacci Series
PART A

1. Define Algorithm.
An algorithm is a set of instructions designed to perform a specific task. It is a step-by-
Step procedure for solving a task or a problem. The different algorithm differs in their requirements of
time and space. The programmer selects the best-suited algorithm for the given task to be solved.

2. What are the characteristics of algorithm?


Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the result of
the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.

3. What are the advantages of algorithm?


It is a step-by-step rep. of a solution to a given problem, which is very easy to understand
It has got a definite procedure.
It easy to first developer an algorithm, then convert it into a flowchart &then into computer program.
It is independent of programming language.
It is easy to debug as every step is got its own logical sequence.

4. Define flow chart.


A graphical representation of the sequence of operations in an information system or program.
Information system flowcharts show how data flows from source documents through the computer to
final distribution to users.

5. What are the basic symbols used in flowchart ?


Name Symbol
Start/End

Arrows
Input/Output

Process

Decision

6. What are the advantages of flowchart ?


 Communication
 Effective analysis
 Proper documentation
 Efficient Coding
 Proper Debugging
 Efficient Program Maintenance

7. Define Pseudo code?


Pseudo code is a compact and informal high-level description of a computer programming
algorithm that uses the structural conventions of a programming language. Pseudo code typically
omits details that are not essential for human understanding of the algorithm, such as variable
declarations, system-specific code and subroutines.

8. What are the rules of pseudo code?


 The pseudo code program should have Start instruction and End instruction.
 Each pseudo code statement should contain at least one instruction.
 Each pseudo code statement should contain a verb that represents the action Performed along
with any identifier and operators that hold program values or perform calculations.
9. What are the advantages of Pseudo code?
 Clarify algorithms in many cases.
 Impose increased discipline on the process of documenting detailed design.
 Provide additional level at which inspection can be performed.
 Help to trap defects before they become code.
 Increases product reliability.
 May decreases overall costs.
10. Write two characteristics of pseudo code.
 Composed of a sequence of statements or steps
 Statements are often numbered sequentially.
 Statements are written in simple English
 Each statement is written on a separate line
 Keywords and indentation are used to signify control structures or blocks of repetition
 There is no fixed syntax.
 Clarity of expression is essence of pseudocode.

11. Write down the steps involved in writing a program to solve a problem.
To design a program, a programmer must determine three basic steps:
a. The instruction to be performed.
b. The sequence in which those instructions are to be performed.
c. The data required to perform those instructions.

12. What is the use of main ( ) function in C program?


Every C program must have main () function. All functions in C, has to begin with (and end with)
parenthesis. It is a starting point of all C programs. The program execution starts from the opening
brace {and ends with closing brace} within which executable part of the program exists.

13. List the delimiters in


C. The delimiters in C are
a. : Colon
b. ; Semicolon
c. ( ) Parenthesis
d. [ ] Square Bracket
e. { } Curly Brace
f. # Hash
g. , Comma
14. What is the purpose of main( ) in C?
main( ) is a special function used by the C system to tell the computer where the program starts. Every
program must have exactly one main function. The empty parenthesis immediately following main
indicates that the function main has no arguments.
15. Write any four escape sequences in C.
Following are the escape sequences in C
a. \n -new line
b. \t –tab
c. \a –alert
d. \0 –null

16. Define Tokens


C tokens are the basic buildings blocks in C language which are constructed together to writea C
program. Each and every smallest individual unit in a C program is known as C tokens. C language
contains the individual units called C tokens. C tokens are of six types. They areas
Follows
a. Keywords (Ex: int, while)
b. Identifiers (Ex: main, total)
c. Constants (Ex: 10, 20)
d. Strings (Ex: “total”, “hello”)
e. Special symbols (Ex: (), {})
f. Operators (Ex: +, /,-,*)

17. What is a variable? Illustrate with an example.


A variable is an entity whose value can vary during the execution of a program. A variable can be
assigned different data items that at various places within the program. A variable is a data name used
for storing a data value. It can be assigned different values at different times during program
execution. Ex: a=3, b=5.

18. What are the different data types available in C?


Basic /Primitive Data Types Derived Data Types User Defined Void
Integer types (signed int, Arrays DataTypes
unsigned int) Pointers Structure
Floating Type (float, double) Structures, Union
Character Enumeration
types (signed char)
19. What is meant by Enumerated data type?
Enumerated data type is a user defined data type in C language. Enumerated data type variables can
only assume values which have been previously declared.
Ex. enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};

20. What are Keywords? What is the importance of keywords in C?


Keywords are pre- defined / reserved words in a C compiler. Each keyword is meant to can be used
only for a specific function in a C program. Since keywords are referred names for compiler, they
can’t be used as variable name. Ex. auto, break, const, else

21. Define Constants in C. Mention the types.


The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals. Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string constant. Ex. const int LENGTH = 10

22. Is ‘main’ a keyword in C language? Justify your answer.


The name main is not a keyword in C. From the compiler's perspective, main() is a function. Just like
any other function that you may define in your program, such asfactorial(),sort(). The simplest way to
prove is that you can create a variable "main" in the program and that will work.
#include <stdio.h>int
main()
{
int main = 10;
printf("The value of main is: %d \n", main);
}
Output
The value of main is: 10

23. List out the rules to be followed in forming in identifier.


a. First letter should be alphabets.
b. Both numeric and alphabets are permitted.
c. Both lower case and upper case are allowed.
d. No special symbols are permitted except underscore ( _ ).
e. Keywords are not permitted, blank space is not allowed.
24. What is identifier? Give any two examples for an identifier.
Identifiers are the names given to variable program elements such as variables, functions and arrays.
Ex. STDNAME, sub, TOT_MARKS, sub123

25. What are Operators? What are various types of C? operators? (Jan 2014)
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides following type of operators
a) Arithmetic Operators
b) Bitwise Operators
c) Relational Operators
d) Assignment Operators
e) Logical Operators
f) Misc Operators

26. What is the difference between ++a and a++?


++a means do the increment before the operation (pre increment) a++ means do the increment after the
operation (post increment).

27. What is type casting?


Type casting is a way to convert a variable from one data type to another data type. For example, if
you want to store a long value into a simple integer then you can typecast long to int. You can convert
values from one type to another explicitly using the cast operator.
int x,y; c = (float) x/y; where x and y are defined as integers. Then the result of x/y is converted into
float.

28. What do you meant by conditional or ternary operator? Give an example for Ternary
operator.
Conditional or ternary operator‟s returns one value if condition is true and returns another value is
condition is false. Using ?: reduce the number of line codes and improve the performance of
application.
Syntax: (Condition? true_value: false_value);
Ex: a<b ? printf("a is less") : printf("a is greater");
29. What is the use of sizeof() Operators in C?
sizeof() is used with the data types such as int, float, char... it simply return amount of 5 memory is
allocated to that data types.
sizeof(char); //1
sizeof(int); //4
sizeof(float);//4
sizeof(double); //8 sizeof() is used with the expression, it returns size of the expression.int
a = 0;
double d = 10.21;
printf("%d", sizeof(a+d)); //8

30.What are the types of I/O statements in C?


There are two types of I/O statements available in C
a. Formatted I/O Statements
b. Unformatted I/O Statements.

31. Write the limitations of using getchar() and scanf() functions for reading strings.
getchar(): It is written in standard I/O library. It reads a single character only from a standard input
device. This function is not use for reading strings.
Scanf: It is use for reading single string at a time. When there is a blank was typed, the scanf()
assumes that it is an end.

32. Define Macro in C. What is the use of #define preprocessor?


A macro can be defined as the facility provided by the C preprocessor by which a token can be placed
by the user defined sequence of characters. Macros are defined with the help of define directive. Its
format is: #define identifier replacement. #define TABLE_SIZE 100

33. What is the difference between ‘=’ and ‘==’ operator?


Where = is an assignment operator and == is a relational operator.
Example: while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only
when i=5.
34. What is the difference between ++a and a++?
++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)
Example: a=5;
x=a++; /* assign x=5*/
y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7*/

35. Why we don’t use the symbol ‘&’ symbol, while reading a String through scanf()?
The ‘&’ is not used in scanf() while reading string, because the character variable itself specifies as a
base address.
Example: name, &name[0] both the declarations are same.

36.Define logical and data errors


Logical errors: These are the errors, in which the conditional and control statements cannot end their
match after some sequential execution.
Data errors: These are the errors, in which input data given, is not in syntax as specified in the input
statement.

37.What is the difference between Logical AND and Bitwise AND?


Logical AND (&&): Only used in conjunction with two expressions, to test more than one condition.
If both the conditions are true the returns 1. If false then return 0. AND (&): Only used in Bitwise
manipulation. It is a unary operator.

38. What is an unary operator? Give example.


The operators that act upon a single operand to produce a new value is known as unary operator.
Eg: minus operator(-) ,
Increment operator (++)

39. What is character set?


The C Character set consists of upper and lower case alphabets, digits, special character and white
spaces. The alphabet and digits are together called the alphanumeric characters.
Alphabets:
A,B,C,D,E...........................X,Y,Z
a,b,c,d,e.............................x,y,z
Digits:
0,1,2,3,4,5,6,7,8,9
Special Character
+ *& ^ % $ # @ ! ~ ` -- = > < .\ , : ;

40. What is different between local variable and global variable


Local Variable Global Variable
a) Variables are declared inside a function. a) Variables are declared outside any
b) They are accessed only by the statements, function.
inside a function in which they are b) They are accessed by any statement in
declared. the entire program.
c) Local variables are stored on the stack, c) Stored on a fixed location decided by a
unless specified. compiler.
d) Created when the function block is entered d) Remain in existence for the entire time
and destroyed upon exit. your program is executing.
e) They are unknown too there functions and e) They are implemented by associating
to the main program. memory locations with variable names.
f) They are recreated each time an function is f) They do not get recreated if the
executed or called. function is recalled

41. Whatisdifferentbetween aconstantandvariable?


Variable Constant
a) A variable is as pace reserved in the a) A constant is value stored in the
machine memory for storing values in application code itself and is not stored
runtime. in the memory
b) The stored value can be changed anytime. b) The value of a constant cannot be
c) Variables are comparatively slow when changed.
compared to constants c) Constants are slightly faster than
variables because constants are stored in
The code not running the memory.

42. Give two examples for logical and relational expression.

RelationalExpressi Logical Expression


on
(a>b) if((a>b)&&(a>c))
(a==b) if((a>b)||(a>c))

43. What are the Bitwise Operators available in C?(Jan2011)


It is used to manipulate the data at bit level. It operates only integers.

Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise XOR
<< ShiftLeft
>> Shift Right
~ One‟scomple
ment

44. Write the following conditions using ternary operator.

4x+100forx<40 
Salary=300forx=40
Salary=x<40?4*x+100:x>40?4.5*x+150:300;

45. Differentiate between formatted and unformatted functions.

Formatted I/O functions Unformatted I/O functions


a) Formatted data requires more space than a) Unformatted input/output is usually
unformatted to represent the same the most compact way to store data.
information. b) Unformatted input/output is the least
b) Formatted input/output is very portable. portable form of input/output.
c) It is a simple process to move formatted c) Unformatted data files can only be
data files to various computers, even moved easily to and from computers
computers running different operating that share The same internal data
systems, as long as they all use the ASCII representation.
character set.

46. List the various input and output statements in C.

The various input and output statements in C are


Input Statements Output Statements
gets() puts()
getch() putch()
getchar() putchar()
scanf() printf()
getche()

47. What is C language?


 C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972.

 The C programming language is a standardized programming language developed in the early


1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system.
 It has since spread to many other operating systems, and is one of the most widely used
programming languages.
48. Define the problem
 A clear and concise problem statement is provided
 The problem definition should specify the input and output
 Full knowledge about the problem is needed.
 Example: find the average of two number

49. Define logical reasoning

Logical reasoning is the process of applying rules to problem solving.

PART B

1. Explain different data types in C with examples.


2. Explain about the variable in C with examples and its types?
3. What are the various operators available in C? Discuss each one of them with suitable illustrations.
4. Discuss about Structure of C program with an example?
5. Explain in detail about the formatted and unformatted I/O functions in C.
6. Describe about types of Expressions available in C with an example?
7. How type conversions are implemented in C with an example?
8. What are constants? Explain the various types of constants in C.
9. Explain the following:
i) Keyword ii) identifiers
ii) C character set
iv) Constants and volatile variables
10. Develop a C program for the following:
a) To check whether a given year is leap or not.
b) To find the root of a quadratic equation.
c) To convert the temperature given in Fahrenheit to Celsius.
d) To find the area and circumference of a circle with radius r.
e) To find the sum of first 100 integers
11. Explain with diagram symbols used in flowchart and the basic design structures in flowchart.
12. Write an algorithm, draw flowchart and pseudo code for Sum of Digits of number.
13. Briefly explain the algorithm
14. Briefly explain the peseudocode

You might also like