Module 1-1
Module 1-1
1 Algorithm
An algorithm is a finite set of step-by-step instructions to solve a problem. The
essential properties of an algorithm are:
1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each and every instruction should be precise and unambiguous i.e.
each and every instruction should be clear and should have only one meaning.
3. Effectiveness: Each instruction should be performed in finite amount of time.
4. Input and Output: An algorithm must take zero or more inputs, and produce
one or more outputs.
5. Generality: An algorithm applies to different sets of same input type.
Advantages:
1. It is step-by-step solution to a given problem which is very easy to understand.
2. It has got a definite procedure.
3. It is easy to first develop an algorithm, then convert into a flowchart and then
into a computer program.
4. It is easy to debug as every step has got its own logical sequence.
5. It is independent of programming languages.
Disadvantages:
1. It is time consuming and cumbersome as an algorithm is developed first which is
converted into flowchart and then into a computer program
2. Algorithm lacks visual representation hence understanding the logic becomes
difficult.
Examples:
Write an algorithm to add two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum
Step 3: Read num1 and num2
Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
Step 5: Display sum
Step 6: Stop
Advantages
1. It clarifies the program logic.
2. Before coding begins the flowchart assists the programmer in determining the
type of logic control to be used in a program
3. The flowchart gives pictorial representation
4. Serves as documentation
5. Serves as a guide for program writing.
6. Ensure that all possible conditions are accounted for.
7. Help to detect deficiencies in the problem statement.
Disadvantages:
1. When the program logic is complex the flowchart quickly becomes complex and
clumsy and lacks the clarity of decision table.
2. It alterations and modifications are required, the flowchart may require re-
drawing completely.
3. As the flowchart symbols cannot be typed reproduction of flowcharts often a
problem.
4. It is sometimes difficult for a business person or user to understand the logic
depicted in a flowchart.
Symbols used to draw flowcharts:
Comparison between flow chart and algorithm
S. No. Algorithm Flow chart
An algorithm is a finite set of step- Flowchart is a pictorial or symbolic
1 by-step instructions that solve a representation of an algorithm.
problem
Algorithm gives verbal which is Gives pictorial representation.
2
almost similar to English language.
Suitable for large and modular Suitable for small programs.
3
programs
Easier to understand To understand flowcharts one has to
4
familiar with symbols.
5 Drawing tools are not required. Required.
Algorithm can be typed so Flowcharts cannot be typed. So
6
reproduction is easy. reproduction is a problem.
It is independent of programming We have to use predefined standard
7 languages. symbols only.
The example of a pseudo code to add two numbers and display the result as shown below:
Advantages
Developing program code using Pseudo codeis easier.
The program code instructions are easier to modify in comparison to a flowchart.
It is well suited for large program design.
Disadvantages
It is difficult to understand the program logic since it does not use pictorial
representation.
There is no standard format for developing a Pseudocode
Basic concept’s of C Program
C language was developed by Dennis Ritchie in 1972 at AT&T Bell Laboratories
(USA). C language was derived from B language which was developed by Ken Thomson in
1970. This B language was adopted from a language BCPL (Basic Combined Programming
Language), which was developed by Martin Richards at Cambridge University. The language
B named as so by borrowing the first initial from BCPL language. Dennis Ritchie modified
and improved B language and named it as C language, using second initial from BCPL.
Importance of C
It is a robust language whose rich set of built in functions and operators can be used to
write any complex program. The C compiler combines the capabilities of an assembly
language with the features of a higher level language and therefore it is well suited for both
system software and business packages.
Features
C is a general purpose language
C can be used for system programming as well as application programming.
C is middle level language
C is portable language
An application program written on C language will work on many different
computers with little or no modifications.
C Block structured language. In C , a block is marked by two curly braces({ })
C programs are compact, fast and efficient
C is case sensitive language
C is function oriented language
C language includes advanced data types like pointers, structures, unions,
enumerated types etc.
C language supports recursion and dynamic storage allocation
C can manipulate with bits, bytes and addresses
Parameter passing can be done using call-by-value and call-by-reference
Comments
Comments are used by programmers to add remarks and explanations within the
program.
Compilerignores all the comments and they do not have any effect on the executable
program.
Comments are of two types; single line comments and multi-line comments.
Single line comments start with two slashes ( // ) and all the text until the end of
the line is considered a comment.
// this is a single line comment
Multi-line comments start with characters /* and end with characters */. Any text
between those characters is considered a multi-line comment.
/* this is a multi-line comment and it
spawned over
multiple lines */
C provides a standard minimal set of data types. Sometimes these are also called as
‘Primitivetypes’. They are:
‘char’ is used to store any single character.
‘int’ is used to store integer value.
‘float’ is used to store floating point value and
‘double’ is used for storing long range of floating point number.
Type Qualifiers
In addition, C has four type qualifiers, also known as type modifiers which precede the basic
data type. A type modifier alters the meaning of basic data type to yield a new data type.
They are as follows:
short
long ( to increase the size of an int or double type)
signed
unsigned
The qualifiers can be classified into two types:
1. Size qualifier (e.g., short and long)
2. Sign qualifier (e.g., signed and unsigned)
Size qualifiers: alters the size of basic data type. The keywords long and short are two size
qualifiers. For example:
long int i;
The size of int is 2 bytes but, when long keyword is used, that variable will be either 4 bytes
or 8 bytes.
Sign qualifiers: Whether a variable can hold only positive value or both values is specified
by sign qualifiers. Keywords signed and unsigned are used for sign qualifiers.
Example
Suppose a variable can be assigned only an integer value. Such variable can be declared as
int a;
This declaration reserves two bytes of memory for storing the number. Such a variable can
store a number in range -32768 to 32767. In order to increase the range you can add a
qualifier to the declaration.
long int a;
The following table shows the basic data types with qualifiers and their ranges.
Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can
be either positive or negative.
Examples for integer constants
1 9 234 999
Floating point Constant
A floating point constant is decimal number that contains either a decimal point or an
exponent. In the other words, they can be written in 2 forms: fractional and exponential.
When expressed in fractional form, note the following points.
1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Examples for fractional form
12.33 -19.56 +123.89 -0.7
When expressed in exponential form, a floating point constant will have 2 parts. One is
before e and after it. The part which appears before e is known as mantissa and the one which
follows is known as exponent. When expressed in this format, note the following
points.mantissa and exponential should be separated by letter E.
1. mantissa can have a positive and negative sign.
2. default is positive.
Character Constant
These are single character enclosed in single quotes. A character can be single
alphabet, single digit, single special symbol enclosed with in single quotes. Not more than a
single character is allowed.
Example
‘a’ ‘Z’ ‘5’ ‘$’
String Constant
A String constant is sequence of characters enclosed in double quotes. So “a” is not
same as ‘a’. The characters comprising the string constant are stored in successive memory
locations.
Example
“hello” “Programming” “cse”
Variables/Identifiers
Variable is named memory location that can be used to store values. These variables
can take different values but one value at a time. These values can be changed during
execution of a program.
Identifiers are basically names given to program elements such as variables, arrays and
functions.
Key words
These are also called as reserved words.
All Keywords have fixed meanings and these meanings cannot be changed.
There are 32 keywords in C programming.
Keywords serve as basic building blocks for a program statement.
All keywords must be written in lowercase only.
ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Delimiters
Delimiters are used for syntactic meaning in C. These are given below:
2.4 Variables
A variable is named memory location that stores a value. When using a variable, we
actually refer to address of the memory where the data is stored. C language supports two
basic kinds of variables:
1. Numeric variables
2. Character variables
Numeric variables
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole number without a fraction part or decimal point. A floating
point value can have a decimal point.
Numeric values may be associated with modifiers like short, long, signed, and
unsigned.
Character variables
Character variables can include any letter from the alphabet or from ASCII chart and
numbers 0-9 that are given within single quotes.
Variable declaration
To declare a variable, specify the data type of the variable followed by its name. The
data type indicates the kind of data that the variable will store. Variable names should always
be meaningful and must reflect the purpose of their usage in the program. In C, variable
declaration always ends with a semicolon, for example:
char grade;
int emp_no;
float salary;
double bal_amount
unsigned short int acc_no;
C allows multiple variable of same type to be declared in one statement, so the following
statement is absolutely legal in C
float temp_in_deg, temp_in_farh;
Initializing variables
Assigning value to variable is called variable initialization. For example:
char grade= ‘A’;
int emp_no=1007;
float salary=8750.25;
double bal_amount=100000000
When variables are declared but not initialized they usually contain garbage values.
Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and assign
it a value. For example,
const float pi=3.1415;
This const keyword specifies that the value of cannot change.
Link section
The link section provides instructions to the compiler to link functions from the
system library.
#include directive
The #include directive instructs the compiler to include the contents of the file
"stdio.h" (standard input output header file) enclosed within angular brackets.
Definition section
The definition section defines all symbolic constants. #define PI 3.1413
Every C program must have one main function section. This section contains two
parts:
1. Declaration part and
2. Executable part
Declaration part: It declares all the variables used in the executable part.
Subprogram section
The subprogram section contains all the user-defined functions that are called in the
main () function. User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.
For Example a ‘C’ program that prints welcome message:
#include<stdio.h>
int main( )
{
printf(“Welcome to C Programming\n”);
}
Output :
Welcome to C Programming
2.5 Operators in C
An operator is defined as a symbol that operates on operands and does something. The
something may be mathematical, relational or logical operation. C language supports a lot of
operators to be used in expressions. These operators can be categorized into the following
groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment/Decrement operators
5. Bitwise operators
6. Conditional operators
7. Assignment operators
8. Special operators
Arithmetic operators
These are used to perform mathematical operations.
These are binary operators since they operate on two operands at a time.
They can be applied to any integers, floating-point number or characters.
C supports 5 arithmetic operators. They are +, -, *, /, %.
The modulo (%) operator can only be applied to integer operands and cannot be used
on float or double values.
Consider three variables declared as,
int a=9,b=3,result;
We will use these variables to explain arithmetic operators. The table shows the arithmetic
operators, their syntax, and usage in C language.
#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d+%d=%d\n",a,b,a+b);
printf("%d-%d=%d\n",a,b,a-b);
printf("%d*%d=%d\n",a,b,a*b);
printf("%d/%d=%d\n",a,b,a/b);
printf("%d%%%d=%d\n",a,b,a%b);
return 0;
}
Output
9+3=12
9-3=6
9*3=27
9/3=3
9%3=0
Relational operators
A relational operator, also known as a comparison operator, is an operator that
compares two operands. The operands can be variables, constants or expressions. Relational
operators always return either true or false depending on whether the conditional relationship
between the two operands holds or not.
C has six relational operators. The following table shows these operators along with their
meanings
#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d>%d=%d\n",a,b,a>b);
printf("%d>=%d=%d\n",a,b,a>=b);
printf("%d<%d=%d\n",a,b,a<b);
printf("%d<=%d=%d\n",a,b,a<=b);
printf("%d==%d=%d\n",a,b,a==b);
printf("%d!=%d=%d\n",a,b,a!=b);
return 0;
}
Output
9>3=1
9 >= 3 = 1
9<3=0
9 <= 3 = 0
9= =3 = 0
9 != 3 = 1
Logical operators
Operators which are used to combine two or more relational expressions are known as
logical operators. C language supports three logical operators – logical AND(&&), logical
OR(||), logical NOT( !).
Logical&& and logical || are binary operators whereas logical!is an unary operator.
All of these operators when applied to expressions yield either integer value 0 (false)
or an integer value 1(true).
Logical AND
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If expressions on the both sides (left and right side) of logical operators is true then
the whole expression is true otherwise false. The truth table of logical AND operator is given
below:
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If one or both the expressions on the left side and right side of logical operators is
true then the whole expression is true otherwise false. The truth table of logical OR operator
is given below:
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
Logical NOT
It takes single expression and negates the value of expression. The truth table of logical NOT
operator is given below
A !A
0 1
1 0
For example: x and y are two variables. The following equations explain the use of logical
operators.
z1 = x&&y …1
z2 = x||y …2
z3 =!x …3
Equation1 indicates that z1 is true if both x and y is true. Equation2 indicates z2 is true when
x or y or both true. Equation3 indicates z3 is true when x is not true.
Unary minus
The unary minus operator returns the operand multiplied by –1, effectively changing
its sign. When an operand is preceded by a minus sign, the unary minus operator negates its
value.
For example,
int a, b=10;
a=-(b);
the result of this expression is a=-10.
Bitwise operators
As the name suggests, the bitwise operators operate on bits. These operations include:
1. bitwise AND(&)
2. bitwise OR(|)
3. bitwise X-OR(^)
4. bitwise NOT(~)
5. shift left(<<)
6. shift right(>>)
Bitwise OR (|)
When we use the bitwise OR operator, the bit in the first operand is ORed with the
corresponding bit in the second operand. If one or both bits are 1, the corresponding bit in the
result is 1 and 0 otherwise. For example:
In a C program, the | operator is used as follows.
int a=4,b=2,c;
c=a|b;
printf(“%d”,c); //prints 6
For example:
In a C program, the | operator is used as follows.
int a=4,b=2,c;
c=a^b;
printf(“%d”,c); //prints 6
Shift operators
C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>).
These operations are simple and are responsible for shifting bits either to left or to the right.
The syntax for shift operation can be given as:
23 22 21 20
8 4 2 1
x=4 0 1 0 0
0 1 0
x>>1 = 0 0 1 0 the result of x>>1 is 2
}
Output:
4|2=6
4&2=0 int a=4,b=2;
4^2=6 printf("%d | %d = %d\n",a,b,a|b);
~4 = -5 printf("%d & %d = %d\n",a,b,a&b);
4 << 1 = 8 printf("%d ^ %d = %d\n",a,b,a^b);
4 >> 1 = 2 printf("~%d = %d\n",a,~a);
printf("%d<<1 = %d\n",a,a<<1);
printf("%d>>1 = %d\n",a,a>>1);
return 0;
Assignment operators
Assignment operator (=)
In C, the assignment operator (=) is responsible for assigning values to variables.
When equal sign is encountered in in an expression, the compiler processes the statement on
the right side of the sign and assigns the result to variable on the left side.
For example,
int x;
x=10;
Assigns the value 10 to variable x. if we have,
int x=2,y=3,sum=0;
sum = x + y;
then sum=5.
The assignment has right-to-left associativity, so the expression
int a=b=c=10;
is evaluated as
(a=(b=(c=10)))
#include <stdio.h>
int main() Output
{ Operator is = and c = 21
int a = 21,c; Operator is += and c = 42
c = a; Operator is −= and c = 21
printf("Operator is = and c = %d\n", c ); Operator is *= and c = 441
c += a; Operator is /= and c = 21
printf("Operator is += and c=%d\n",c); Operator is %= and c = 11
c −= a; Operator is <<= and c = 44
printf("Operator is −= and c=%d\n",c); Operator is >>= and c = 11
c *= a; Operator is &= and c = 2
printf("Operator is *= and c=%d\n",c); Operator is ^= and c = 0
c /= a; Operator is |= and c = 2
printf("Operator is /= and c=%d\n", c);
c = 200;
c %= a;
printf("Operator is %= and c=%d\n",c);
c <<= 2;
printf("Operator is <<= and c=%d\n",c);
c >>= 2;
printf("Operator is >>= and c=%d\n",c);
c &= 2;
printf("Operator is &= and c = %d\n", c );
c ^= 2;
printf("Operator is ^= and c = %d\n", c );
c |= 2;
printf("Operator is |= and c = %d\n", c );
return 0;
}
Advantages:
1. Short hand expressions are easier to write.
2. The statement involving short hand operators are easier to read as they are more
concise.
3. The statement involving short hand operators are more efficient and easy to
understand.
Conditional operator (? : )
It is also called ternary operator because it takes three operands. It has the general form:
variable = expression1 ? expression2 : expression3;
If the expression1 is evaluated totrue then it evaluates expression2 and its value is
assigned to variable, otherwise it evaluates expression3 and its value is assigned to variable.
For example
#include<stdio.h>
int main()
{
int a=5,b=6,big;
big = a>b ? a : b;
printf("%d is big\n", big);
return 0;
}
Output
6 is big
Special operators: Comma operator (,)
This operator allows the evaluation of multiple expressions, separated by the comma,
from left to right in the order and the evaluated value of the rightmost expression is accepted
as the final result. The general form of an expression using a comma operator is
expressionM= ( expression1, expression2, expressionN);
For example
#include<stdio.h> i=5 j=9
int main() #include<stdio.h>
{ int main()
int k=5; {
i=k++, j=(k++,k++,++k); int k=5;
printf(i=%d\t j=%d”, i,j); i=k++, j =k++, k++, ++k;
return 0; printf(i=%d \t j=%d”, i,j);
} return 0;
Output }
17
Output i=5 j=6
sizeof Operator
The operator sizeof is a unary operator used calculates the size of data types and
variables. The operator returns the size of the variable, data type in bytes. i.e. the sizeof
operator is used to determine the amount of memory space that the variable/data type will
take. The outcome is totally machine-dependent.
For example:
#include<stdio.h>
int main()
{
printf("char occupies %d bytes\n",sizeof(char));
printf("int occupies %d bytes\n",sizeof(int));
printf("float occupies %d bytes\n",sizeof(float));
printf("double occupies %d bytes\n",sizeof(double));
printf("long double occupies %d bytes\n",sizeof(long double));
return 0;
}
Output
char occupies 1 bytes
int occupies 2 bytes
float occupies 4 bytes
double occupies 8 bytes
long double occupies 10 bytes
2.6 Expressions
In C programming, an expression is any legal combination of operators and operands
that evaluated to produce a value.Every expression consists of at least one operand and can
have one or more operators. Operands are either variables or values, whereas operators are
symbols that represent particular actions.
In the expression x + 5; x and 5 are operands, and + is an operator.
In C programming, there are mainly two types of expressions are available. They are as
follows:
1. Simple expression
2. Complex expression
Simple expression: In which contains one operator and two operands or constants.
Example: x+y; 3+5; a*b; x-y etc.
Complex expression: In which contains two or more operators and operands or constants.
Example: x+y-z; a+b-c*d; 2+5-3*4; x=6-4+5*2 etc.
Operator Precedence
It definesthe order in which operators in an expression are evaluated depends on their
relative precedence. Example: Let us see x=2+2*2
1st pass- 2+2*2
nd
2 pass- 2+4
3rd pass- 6 that is x=6.
Associativity defines the order in which operators with the same order of precedenceare
evaluated. Let us see x=2/2*2
1st pass-- 2/2*2
2nd pass-- 1*2
3rd pass-- 2that is x=2
Output:
The value of a is 16
The value of a is 14
The value of a is 6
Format specifiers
Format
Data Type Display
specifier
%c char Single character
%c unsigned char
%s Sequence of characters (String)
int Signed integer (both +ve and –ve
%d
values)
%u unsigned int Unsigned integer (only +ve values)
%hd short int Signed short integer
%ld long int Long integer
unsigned long Unsigned long integer (only +ve
%lu int values)
%o int Octal values
%x int Hexa decimal values
%f float Floating-point value
long Double precision floating-point
%lf float/double value
long double Double precision floating-point
%Lf
value
%p pointer Address stored in pointer
%% none Prints %
Flag Meaning
− Left justify the display
+ Display the positive or negative sign of value
0 Pad with leading zeros
space Display space if there is no sign
The simplest printf statement is
printf(“Welcome to the world of C language”);
When executed, it prints the string enclosed in double quotes on screen.
Examples:
printf(“Result:%d%c%f\n”,12,’a’,2.3);
Result:12a2.3
printf(“Result:%d%c%f\n”,12,’a’,2.3);
Result:12a2.3
printf(“Result:%d\t%c\t%f\n”,12,’a’,2.3);
Result:12 a 2.3
printf(“%6d\n”,1234);
1 2 3 4
printf(“%06d\n”,1234);
0 0 1 2 3 4
printf(“%-6d\n”,1234);
1 2 3 4
printf(“%-06d\n”,1234);
- 0 1 2 3 4
printf(“%2d\n”,1234);
1 2 3 4
printf(“%9.2f\n”,123.456);
0 0 1 2 3 4 . 4 5
char ch=’A’;
printf(“%c\n%2c\n%3c\n”,ch,ch,ch);
A
A
A
printf(“%X\n”,255);
FF
Syntax
scanf(“control string”,variable1,variable2,…,variable n);
This function should have at least two parameters. First parameter is control string which is
conversion specification character. It should be within double quotes. This may be one or
more, it depends on the number of variables. The other parameter is variable names.
Each variable must preceded by ampersand (&) sign. This gives starting address of
the variable name in memory. scanf ( ) uses all the format specifiers used in printf( ) function.
Note: comments are not allowed in scanf()
For example, consider the following simple programs.
#include <stdio.h>
int main()
{
int x;
printf(“Enter number:”);
scanf(“%d”, &x);
printf(“The value of x is %d\n”, x);
return 0;
}
Output
Enter a number: 45
The value of x is 45
For accessing multiple values from keyboard using scanf() function
#include <stdio.h>
int main()
{
int x,y;
printf(“Enter two numbere:”);
scanf(“%d%d”, &x,&y);
printf(“The value of x is %d\n”, x);
printf(“The value of y is %d\n”, y);
return 0;
}
Output
Enter two numbers: 29 47
The value of x is 29
The value of x is 47
A Sample ‘C’ program that illustares the use implicit type conversion
#include<stdio.h>
int main()
{
int sum, num=17;
char ch='A';
sum=num+ch;
printf("The value of sum=%d\n", sum);
return 0;
}
Output:
The value of sum= 82 i.e. sum=num+ch=>17+65 (ASCII value of ‘A’
Syntax
(data_type) expression;
Where, data_type is any valid C data type, and expression may be constant, variable or
expression.
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Let us look at some examples of type casting.
2. 9 Mathematical Functions in C
The mathematical functions such as sin, cos, sqrt, log etc., are frequently used in
analysis of real-life problems. Most of the C compilers support these basic math functions.
The following Table lists some standard math functions
Function Meaning
Trigonometric
asin(x) Arc sin of x.
acos(x) Arc cosine of x
atan(x) Arc tangent of x
atan2(y,x) Arc tangent of y/x
sin(x) sine of x
cos(x) cosine of x
tan(x) tangent of x
Hyperbolic
sinh(x) hyperbolic sine of x
cosh(x) hyperbolic cosine of x
tanh(x) hyperbolic tangent of x
Other functions
exp(x) e to the power of x (ex)
ceil(x) x rounded up to the nearest integer.
floor(x) x rounded down to the nearest integer
fabs(x) absolute value |x|
log(x) Natural logarithm of x, x>0.
log10(x) Base 10 logarithm x, x>0.
fmod(x,y) Remainder of x/y
sqrt(x) square root of x, x>=0.
pow(x,y) x to the power y.
Note:
1. x and y should be declared as double.
2. In trigonometric and hyperbolic functions, x and y are radians.
3. All the functions return a double.
We should include the line:
#include<math.h>
in the beginning of the program
Output
sin 90 = 1
cos 0= 1
sqrt(9) = 3
floor(9.56) = 9.00
ceil(9.56) = 10.00
abs(-9) = 9.00
power(2,3) = 8
Remainder of 9/3 = 0
Control Statements in C
Statements
The statements of a C program control the flow of program execution.
A statement is a command given to the computer that instructs the computer to take a
specific action, such as display to the screen, or collect input.
A computer program consists of a number of statements that are usually executed in
sequence. Statements in a program are normally executed one after another.
Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to make
decisions, to perform tasks repeatedly or to jump from one section of code to another.
Syntax: Flowchart
if(test expression )
{
statement-block;
}
statement - x;
If the test expression is true then the statement-block will be executed; otherwise the
statement block will be skipped and the execution will jump to the statement-x. Remember,
when the condition is true both the statement-block and the statement-x are executed in
sequence.
Ex 1: Write a program „C‟ to check whether the given number is +ve or –ve using
simple if statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)
if(test expression )
{
statement block - 1;
}
else
{
statement block - 2;
}
statement-x;
If the test expression is true, then statement block – 1 is executed and statement block-2 is
skipped. Otherwise, the statement-2 is executed. In both the cases, the control is transferred
subsequently to the statement-x.
Ex 2: Write a program „C‟ to check whether the given number is even or odd using if..else
statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
if(num%2==0)
printf("%d is even number\n",num);
else
printf("%d is odd number\n",num);
return 0;
}
Output:
Enter a number: 8
8 is even number.
Ex 3: Write a „C‟ program to check whether the given year is leap or not using if..else
statement.
.#include<stdio.h>
int main()
{
int year;
printf("Enter any year:");
scanf("%d",&year);
if(year%4==0)
printf("%d is leap year\n", year);
else
printf("%d is non leap year\n", year);
return 0;
}
Output:
Enter any year: 1996
1996 is leap year.
Syntax: Flowchart:
if (test expression 1)
{
if (test expression 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
If the test expression1 is false, the statement-3 will be executed; otherwise it continues
to perform the second test. If the test expression-2 is true, the statement-1 will be executed.
Otherwise the statement-2 will be executed and then the control is transferred to the
statement-x.
Ex 4: Write a C program to find the biggest among three numbers using nested-if statement.
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter a,b,c values:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is the big\n",a);
else
printf("%d is the big\n",c);
}
else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
return 0;
}
Output:
Enter a, b, c values: 9 5 17
17 is the big
All the conditions are evaluated one by one starting from top to bottom, if any one of
the condition evaluating to true then statement group associated with it are executed and skip
other conditions. If none of expression is evaluated to true, then the statement or group of
statement associated with the final else is executed.
Flowchart
The following program demonstrates a legal if-else if statement: In this program we
assign grades to students according to the marks they obtained, using else-if ladder statement.
Output
Enter marks of 5 subjects: 90 90 88 86 84
Total marks = 438
Aggregate = 87
Grade: Excellent
The switch statement
A switch statement is also a multi-way decision making statement that is a simplified
version of if..else..if block that evaluates a single variable. The syntax of switch statement is:
switch(variable)
{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
case constant N:
statements;
break;
default:
default statement;
}
Output
Simple Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice(1..4): 2
Enter a,b values: 12 7
12 – 7 = 5
The body of the loop will be executed repeatedly till the value of test expression
becomes false (0). The initialization of a loop control variable is generally done before the
loop separately.
syntax:
Flowchart
Output: 1 2 3 4 5 6 7 8 9 10
Output
Enter a number to be reversed: 1234
The reverse number is: 4321
Output
Enter a number: 153
153 is Armstrong
do..while Statement
do-while loop is similar to while loop, however there is one basic difference between
them. do-while runs at least once even if the test condition is false at first time. Syntax of do
while loop is:
Syntax Flowchart
do
{
body of the loop;
}
while (expression);
statement -x;
Output: 1 2 3 4 5
Flowchart
The loop header contains three parts:
o an initialization,
o a test condition, and
o incrementation(++) / decrementation(˗ ˗) /update.
Initialization: This part is executed only once when we are entering into the loop first time.
This part allows us to declare and initialize any loop control variables.
Condition: if it is true, the body of the loop is executed otherwise program control goes
outside the for loop.
Increment or Decrement: After completion of initialization and condition steps loop body
code is executed and then increment or decrements steps is execute. This statement allows to
us to update any loop control variables.
Then, the test expression is evaluated. If the test expression is false, for loop is
terminated. But if the test expression is true, codes inside the body of for loop is
executed and the update expression is executed. This process repeats until the test
expression becomes false.
Note: In for loop everything is optional but mandatory to place two semicolons (; ;)
Ex 11: Write a C program to check whether the given number is prime or not.
#include<stdio.h>
int main( )
{
int n,i,fact=0;
printf("Enter a number:");
scanf("%d",&n);
for (i=2;i<n/2;i++)
{
if(n%i == 0)
fact++;
}
if(fact == 0)
printf("%d is Prime\n",n);
else
printf("%d is not a Prime\n",n);
return 0;
}
Output
Enter a number: 13
13 is Prime.
Ex 12: Write a C program to print the factorial of a given number.
#include<stdio.h>
int main( )
{
int n,i;
long int fact=1;
printf("Enter a number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
fact = fact*i;
}
printf("Factorial of %d is %ld\n", n, fact);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is 120
Comparison between for and do, while loops
S.No For loop Do-while loop
1 Generally deterministic in nature Non-deterministic in nature
Loop index can be initialized and altered Index will be initialized outside the loop
2
with in loop
Very flexible in nature Not so flexible when compared with for
3
loop
Condition is checked at beginning of the Same in case of while loop. In do loop,
4 loop condition is checked after end of the
loop
Minimum iterations are zero Minimum iterations are zero (while)
5
Minimum iterations are one (do-while)
Pre-test loop: The condition can be tested- At the beginning is called as pre-test or entry-
controlled loop. Example: while and for loops.
Post-test loop: The condition can be tested - At the end is called as post-test or exit-
controlled loop. Example: do-while loop.
Nested loops
Insertion of one loop statement inside another loop statement is called nested loop.
Generally for loops are nested. In C loops can be nested to any desired level. General syntax
for nested for loops are:
Output:
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *
Output
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Output
Enter number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Output
1 2
Output
Enter a number (999 for exit): 1
Enter a number (999 for exit): 3
Enter a number (999 for exit): -1
Enter a number (999 for exit): 7
Enter a number (999 for exit): 999
Sum of the numbers entered by the user is 11
Array
An array is collection of homogeneous elements that are represented under a single variable
name.
(Or)
An array is collection of same data type elements in a single entity.
It allocates sequential memory locations.
Individual values are called as elements.
Types of Arrays
We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
1. One – dimensional arrays(1-D)
2. Two – dimensional arrays (2-D)
3. Multidimensional arrays (n-D)
The data type specifies the type of element that will be contained in the array, such as int,
float, or char or any valid data type.
The array name specifies the name of the array.
The size indicates the maximum number of elements that can be stored inside the array.
The size of array should be a constant value.
For example
int marks[10]; //integer array
C array indices start from 0. So for an array with N elements, the index that last element is N-1
Valid Statements
a = marks[0] + 10;
marks[4] = marks[0] + marks[2];
marks[2] = x[5] + y[10];
value[6] = marks[i] * 3;
Example 1: A C program that prints bytes reserved for various types of data and space required
for storing them in memory using array.
#include<stdio.h>
int main()
{
char c[10];
int i[10];
float f[10];
double d[10];
printf("\nThe type char requires %d byte",sizeof(char));
printf("\nThe type int requires %d bytes",sizeof(int));
printf("\nThe type float requires %d bytes",sizeof(float));
printf("\nThe type double requires %d bytes",sizeof(double));
printf("\n%d memory locations are reserved for 10 character elements", sizeof(c));
printf("\n%d memory locations are reserved for 10 integer elements", sizeof(i));
printf("\n%d memory locations are reserved for 10 float elements", sizeof(f));
printf("\n%d memory locations are reserved for 10 double elements", sizeof(d));
return 0;
}
Output
The type char requires 1 byte
The type int requires 2 bytes
The type float requires 4 bytes
The type double requires 8 bytes
10 memory locations are reserved for 10 character elements
20 memory locations are reserved for 10 integer elements
40 memory locations are reserved for 10 float elements
80 memory locations are reserved for 10 double elements
For example
int i ,marks[10];
for (i=0; i<10; i++)
printf(“%d”,marks[i]);
For example
int marks[5]={90,87,76,69,82};
While initializing the array at the time of declaration, the programmer may omit the size of the
array. For example,
int marks[]= {98, 97, 90};
int i ,marks[10];
for (i=0; i<10; i++)
scanf(“%d”,&marks[i]);
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5
Example 3: Write a C Program to print the maximum and minimum element in the array.
#include <stdio.h>
int main()
{
int i, n, a[20], max, min;
printf("Enter the number of elements in the array : ");
scanf("%d", &n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%d",&a[i]);
}
max = min = a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("\n The smallest element is : %d\n", min);
printf("\n The largest element is : %d\n", max);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The smallest element is : 1
The largest element is : 5
Linear Search
Linear search, also called as sequential search, is a very simple method used for searching
an array for a particular value. It works by comparing the value to be searched with every
element of the array one by one in a sequence until a match is found. It is mostly used to search
an unordered list of elements. For example, if an array a[] is declared and initialized as,
int a[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is
present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3
(index starting from 0).
Example 4: Write a C Program to search an element in an array using the linear search
technique.
#include <stdio.h>
int main()
{
int a[100],n,i,key,flag=0;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter an element to be searched:");
scanf("%d", &key);
/* linear search starts here */
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("%d is found at position %d\n", key, i);
flag=1;
break;
}
}
if(flag==0)
printf("%d is not found\n",key);
return 0;
}
Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Enter an element to be searched: 9
9 is found at position 3
Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list.
5.2 Sorting
Sorting means arranging the elements of an array in specific order may be either ascending or
descending. There are different types of sorting techniques are available:
1. Bubble sort
2. Selection sort
3. Insert sort
4. Merge sort
5. Quick sort etc.
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair of adjacent items and swaps them if they
are in the wrong order.
Selection sort is a simple sorting algorithm. This sorting algorithm is in-place comparison based
algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at
right end. Initially sorted part is empty and unsorted part is entire list.
In the above table V23 refers to the value “80”. C allows us to define such tables of items by using
two-dimensional arrays.
Definition
A list of items can be represented with one variable name using two subscripts and such
a variable is called a two – subscripted variable or a two – dimensional (2D) array.
If the values are missing in an initializer, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, \\ 1 1 0
{2} \\ 2 0 0
};
When all the elements are to be initialized to zero, the following short-cut method may be
used.
int m[3][5] = { {0}, {0}, {0}};
The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.
return 0;
}
Output
Enter number of rows and columns (between 1 and 10): 3 3
Enter elements of first matrix: 1 2 3 4 5 6 7 8 9
Enter elements of second matrix: 1 2 3 4 5 6 7 8 9
The matrix A
1 2 3
4 5 6
7 8 9
The matrix B
1 2 3
4 5 6
7 8 9
The resultant matrix is
2 4 6
8 10 12
14 16 18
printf("\n");
}
}
else
printf("Multiplication is not possible\n");
return 0;
}
Output
Enter number of rows and columns of first matrix (between 1 and 10):2 3
Enter number of rows and columns of second matrix (between 1 and 10):3 2
Enter elements of first matrix: 1 2 3 4 5 6
Enter elements of second matrix: 1 2 3 4 5 6
The Matrix A
1 2 3
4 5 6
The Matrix B
1 2
3 4
5 6
The resultant matrix is
22 28
49 64
Initializing 3D Array
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
This initializes the elements of first two dimensional (matrix) first row to zero’s and the second
row to one’s and second matrix elements are first row to six’s and the second row to seven’s.
This initialization is done row by row.
The above statement can be equivalently written as
int a[2][3] = {{{0,0,0},{1,1,1}},{{0,0,0},{1,1,1}}}
we can also initialize a two – dimensional array in the form of a matrix as shown.
int a[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
};
5.5 Strings
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character '\0'. Since string is an array, the declaration of a string is
the same as declaring a char array.
char string1[30];
char str2[7] = “String”;
The following declaration creates string named “str2” and initialized with value “String”. To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word.
Note: The C compiler automatically places the '\0' at the end of the string when it initializes the
array.
The terminating null (‘\0’) is important, because it is the only way the functions that work with a
string can know where the string ends.
Function Use
strlen() Finds length of a string
strlwr() Converts a string to lowercase
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strcpy() Copies a string into another
strcmp() Compares two strings
strchr() Finds first occurrence of a given character in a string
strstr() Finds first occurrence of a given string in another string
strrev() Reverses the given string
strlen() function
This function counts the number of characters present in a string. Syntax for strlen() function is
given below:
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose length is to be found, and
returns the length of the string passed.
strcpy( ) function
This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
char * strcpy ( char * destination, const char * source );
Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.
Output
Source string = Sayonara
Destinnation string = Sayonara
strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.
For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.
strcmp( ) function
It compares two strings to find out whether they are same or different. The two strings
are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first.
If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it
returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax for strcmp( ) function is given below.
Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example 15: C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ; Output
int i, j, k ; 0 4 -32
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.
The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: New horizon
Hello! New horizon