0% found this document useful (0 votes)
27 views41 pages

PPS Notes Unit-II

Uploaded by

drafreenbari
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)
27 views41 pages

PPS Notes Unit-II

Uploaded by

drafreenbari
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/ 41

Unit-II:

ATHEMATIC EXPRESSIONS
Expressions: An expression is a sequence of operands and operators that reduces to a single value.
Operator: An operator is a syntactical token that requires an action to be taken.
Operand: An operand is an object on which the operation is performed. Simply operand is an object
which receives operation from operator.
Expressions can be of two types: simple expressions and complex expressions.
Simple Expression: A simple expression contains only one operator. Ex: 2+7
Complex Expression: A compound expression contains more than one operator. Ex: 2+7*6

OPERATORS IN C-LANGUAGE:
 Operators are the foundation for any programming language. The functionality of C programming
language is incomplete without the use of operators.
 The operator can be defined as symbols that performs a specific mathematical or logical computations on
operands. In other words operator operates on the operands.
 In C, Operators are broadly categorized into 3 – types: i) Unary Operators ii) Binary Operator and
iii)Ternary Operator
 This broad categorization is done based on the number of operands the operator will use in exhibiting its
functionality.
i) Unary Operators: Operators of this type, operates or works with a single operand. Hence the
name unary operators. For example: (++, --).
ii) Binary Operators: Operators of this type, operates or works with a two operands. Hence the name
binary operators. For example: (+, -, *./).
iii) Ternary Operators: Operators of this type, operates or works with a three operands. Hence the
name ternary operators. For example: (?:).
 Based on the above criterion in mind, Operators are categorized into the following categories:
a) Arithmetic Operators:
b) Relational Operators:
c) Logical Operators
d) Bitwise Operators
e) Assignment Operators
f) Increment and Decrement Operators
g) Conditional Operator
h) Other Operators
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
a) Arithmetic Operators:
Arithmetic operators are used to perform arithmetic/mathematical operations on operands.

Arithmetic Operator Operator function Binary Form


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a / b (b≠0)
% Modulus a % b (b≠0)
Note:
1. While performing division the second operand must be not equal to zero.
2. While performing modulo division both the operands must be integers, and second operand
must be non-zero.

b) Relational Operators:
Relational operators are used for comparison of two operand values. All of the relational operators are
binary operators. They need two operands to perform their functionality. They are as follows:

‘==’ (equal operator):


o It checks whether the two given operands are equal or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5==5 will return true.

‘!=’ (not equal operator):


o It checks whether the two given operands are equal or not.
o If not, it returns true. Otherwise it returns false.
o It is the exact boolean complement of the ‘==’ (equal operator).
o For example: 5!=5 will return false.

‘>’ (Greater than operator):


o It checks whether the first operand is greater than the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 6>5 will return true.

‘<‘ (Less than operator):


o It checks whether the first operand is lesser than the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 6<5 will return false.

‘>=’ (Less than or equal operator):


o It checks whether the first operand is greater than or equal to the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5>=5 will return true.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
‘<=’ (Greater than or equal operator):
o It checks whether the first operand is lesser than or equal to the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5<=5 will also return true.
Relational Operator Operator function Binary Form
== Equal a == b
!= Not Equal a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal a >= b
<= Less than or equal a <= b
Note: The following set of operators are complement to each other.
< is complement to >=
> is complement to <=
== is complement to !=

C program to demonstrate working of relational operators


// C program to demonstrate working of relational operators
#include <stdio.h>

int main()
{
int a=10, b=4;

if (a > b)
printf("a is greater than b\n");
else printf("a is less than or equal to b\n");

if (a >= b)
printf("a is greater than or equal to b\n");
else printf("a is lesser than b\n");

if (a < b)
printf("a is less than b\n");
else printf("a is greater than or equal to b\n");

if (a <= b)
printf("a is lesser than or equal to b\n");
else printf("a is greater than b\n");

if (a == b)
printf("a is equal to b\n");
else printf("a and b are not equal\n");
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
if (a != b)
printf("a is not equal to b\n");
else printf("a is equal b\n");

return 0;
}
Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

c) Logical Operators:
Logical operators are used to perform logical operations such as Logical AND, Logical OR and Logical
NOT. They are used to combine two or more conditions/constraints or to complement the evaluation of
the original condition in consideration. They are as follows:

Logical AND (&& Operator):


o The ‘&&’ operator returns true when both the conditions in consideration are satisfied.
Otherwise it returns false. It is a binary operator.
o For example: a && b returns true when both a and b are true (i.e. non-zero).

Logical OR (|| Operator):


o The ‘||’ operator returns true when one (or both) of the conditions in consideration is
satisfied. Otherwise it returns false. It is a binary operator.
o For example: a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns
true when both a and b are true.

Logical NOT (! Operator):


o The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it
returns false. It is a unary operator.
o For example: !a returns true if a is false, i.e. when a=0.

Logical Operator Operator function Binary Form


&& Logical AND a && b
|| Logical OR a || b
Logical Operator Operator function Unary Form
! Logical NOT !a

C program to demonstrate working of logical operators


// C program to demonstrate working of logical operators
#include <stdio.h>

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
int main()
{
int a=10, b=4, c = 10, d = 20;

if (a>b && c==d)


printf("a is greater than b AND c is equal to d\n");
else printf("AND condition not satisfied\n");

if (a>b || c==d)
printf("a is greater than b OR c is equal to d\n");
else printf("Neither a is greater than b nor c is equal to d\n");

if (!a)
printf("a is zero\n");
else printf("a is not zero");

return 0;
}
Output:
AND condition not satisfied
a is greater than b OR c is equal to d
a is not zero

d) Bitwise Operator:
Bitwise operators work at bit level of the given operands. There are 6-different types of bitwise operators:
& (bitwise AND operator):
o This operator takes two numbers as operands and does AND on every bit of two numbers.
o The result of AND is 1 only if both bits are 1.

| (bitwise OR operator):
o This operator takes two numbers as operands and does OR on every bit of two numbers.
o The result of OR is 1 if any of the two bits is 1.

^ (bitwise XOR operator):


o This operator takes two numbers as operands and does XOR on every bit of two numbers.
o The result of XOR is 1 if the two bits are different.
o This operator is used to check whether the given number is even or odd.

<< (bitwise left shift operator):


o This operator takes two numbers, left shifts the bits of the first operand, and the second
operand decides the number of places to shift.

>> (bitwise right shift operator):


o This operator takes two numbers, right shifts the bits of the first operand, and the second
operand decides the number of places to shift.

~ (bitwise NOT operator):


MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
o This operator takes one number and inverts all bits of it. (0’s become 1’s and 1’s become
0’s)
o This operator is used to find the one’s complement of a given number.

Bitwise Operator Operator function Binary Form


& Bitwise AND a&b
| Bitwise OR a|b
^ Bitwise XOR a^b
<< Bitwise Left Shift a << 2
>> Bitwise Right Shift a >> 2
Logical Operator Operator function Unary Form
~ Bitwise Not ~a

Examples:
a b a&b a|b a^b ~a
0 0 0 0 1 1
0 1 0 1 0 1
1 0 0 1 0 0
1 1 1 1 1 0
a = 5(00000101), b = 9(00001001)
a&b = 00000001
a|b = 00001101
a^b = 00001100
~a = 11111010
b<<1 = 00010010
b>>1 = 00000100

C Program to demonstrate use of bitwise operators


/* C Program to demonstrate use of bitwise operators */
#include<stdio.h>
int main()
{
char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}
Output:
a = 5, b = 9
a&b = 1
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
a|b = 13
a^b = 12
~a = -6
b<<1 = 18
b>>1 = 4

Instructions when using bitwise operators:


1. The left shift and right shift operators should not be used for negative numbers:
i. If any of the operands is a negative number, the result is undefined behavior.
For example: results of both -1 << 1 and 1 << -1 is undefined.
ii. If the number is shifted more than the size of integer, the behavior is undefined.
For example: 1 << 33 is undefined.

2. The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively.
For example: if x=18 then x<<1 = 36, x>>1 = 9
#include<stdio.h>
int main()
{
int x = 18;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1);
return 0;
}
Output:
36 9

3. The & operator can be used to quickly check if a number is odd or even.
For example: The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value
would be zero.
#include<stdio.h>
int main()
{
int x = 19;
(x & 1)? printf("Odd"): printf("Even");
return 0;
}

Output:
Odd

e) Assignment Operators:
 The assignment operator (=) evaluates the operand on the right side of the operator (=) and places the
value in the variable on the left.
 The value on the right side must be of the same data-type of variable on the left side otherwise the
compiler will raise an error.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The right-side value cannot be a constant, doing so is an error.
Syntax:
variable = expression (or) constant;

Types of Assignment:
There are three different types of assignments possible using the same operator (=).
1. Simple assignment: This type of statement will have only one assignment operator in it. The right
side value or the result will be assigned to the left-side variable.
Example: a=10; //Here variable a will hold 10 after assignment.

2. Multiple assignment: This type of statement will have multiple assignment statements in it.
Example: a=b=c=10; // Here value 10 will be assigned to a, b, c variables

3. Compound assignment: It is a shorthand notation for a simple assignment. It requires the left
operator to be repeated as a part of the right expression. There are five compound assignment
operators listed in the following table.
Operator Example Equivalent Statement
+= c += 7 c=c+7
-= c -= 8 c=c–8
*= c *= 10 c = c * 10
/= c /= 5 c=c/5
%= c %= 5 c=c%5

f) Increment and decrement Operators:


 These category of operators are unary operators.
 They are used to add 1, increment (++) or subtract one (--) from the given variable.
 As they are unary operators they can be used in two different ways: Postfix and Prefix.
 Postfix: In this form, the operator is place before the variable, and the variable’s value will be
incremented by 1 after the expression evaluation. Hence the name postfix.
Syntax: a=b++; /*here first the ‘a’ value will be initialized with ‘b’ value and the b gets
incremented*/
#include<stdio.h>
int main(void)
{
int a,b=7;
clrscr();
a=b++; //postfix increment
printf("\n%d %d", a, b);
a=b--; //postfix decrement
printf("\n%d %d", a, b);
getch();
return 0;
}
Output:
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
78
87

 Prefix: In this form, the operator is place before the variable, and the variable’s value will be
incremented by 1 before the expression evaluation. Hence the name prefix.
Syntax: a=++b; /*here first the ‘a’ value will be incremented by 1 and then will be
initialized to ‘b’ */
#include<stdio.h>
int main(void)
{
int a,b=7;
system("cls");
a=++b; //postfix increment
printf("\n%d %d", a, b);
a=--b; //postfix decrement
printf("\n%d %d", a, b);
return 0;
}
Output:
88
77

Operator Example Meaning Equivalent Statements


++ i++ postfix i=i+1; i+=1;
++ ++i prefix i=i+1; i+=1;
-- i-- postfix i=i-1; i -=1;
-- --i prefix i=i-1; i-=1;

g) Conditional Operator:
 Conditional operator also known as ternary operator.
 It is the only operator in C, which takes three operands in its operation.
 The (?:) token is used to form this operator.

Syntax: conditional_expression? Expression1 : Expression2;


The result of the above operation is based on the conditional_expression, if this expression is true
(nonzero) then expression1 gets evaluated, if the conditional_expression is false (zero) then expression2
will be evaluated.

 The conditional operator is equivalent to the if-else statement.


Conditional Operator if-else statement
#include<stdio.h> #include<stdio.h>
int main(void) int main(void)
{ {
int a=6,b=7; int a=6,b=7;
system("cls"); system("cls");
a>b?printf("%d is big", a):printf("%d is big",b); if(a>b)
return 0; printf("%d is big", a);
} else
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("%d is big",b);
return 0;
}
Output Output
7 is big 7 is big

h) Other Operators:
C supports the following set of special operators:
& (Address Operator)  The address operator is used get the address of an operand.
 It is a unary operator, it requires only on operand.
 When used with the operand, it returns the address of that operand’s
memory location.
* (Indirection Operator)  To access the value from the given address, the * operator is used.
 Generally it deal with pointer, where to get the value from a pointer
this operator is used.
 It is also a unary operator, requires only one operand to perform its
functionality.
, (Comma Operator)  This operator does not show any operations on the operands, rather it
is used to separate the expressions which are appearing in the same
line.
 Like regular use, the comma operator is used like a separator.
 Example: int a,b,c;
j=(i=12,i+20);
sizeof() Operator  This operator is used to know the memory size of the operand
supplied.
 As it is a unary operator, it operates on single operand.
 Syntax: sizeof(datatype/variable);
 Example: sizeof(a);
sizeof(int);
. and  (Member access The . (dot) and  operators are used to access the members of a
Operators: structure (directly or indirectly).

PRECEDENCE AND ASSOCIATIVITY:


 Expression evaluation is easy if it is a simple expression to be evaluated, but problem arises when we have
a complex expression to evaluate.
 Without the knowledge of precedence, it is difficult to determine the order in which the operators in a
complex expression are evaluated.
 Precedence: Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
 Associativity: Associativity is used to determine the order in which operators with same precedence are
evaluated in a complex expression.
 Always the precedence is applied before the associativity, knowing that there are more operators with
same precedence level, the associativity is applied.
 If there are no operator with same precedence, no need to apply the associativity.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Every operator in C is having a precedence, the higher the precedence the earlier the operator gets
evaluated.

Example: 2+3*4 = ?
In precedence table operator * is having higher precedence than operator +, hence the * will be
evaluated first and then +, so the value is 14 (see the following precedence table).

Associativity:
 Associativity can be left-to-right or right-to-left.
 Left-to-right associativity evaluates the expression by starting on the left and moving to the right.
 Right-to-left associativity evaluates the expression by starting on the right and moving to the left.
 Remember, associativity is used only when there are operators with same precedence level in occur in a
complex expression.

Associativity Rule

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
OPERATOR PRECEDENCE TABLE

Example:
1. 3*8/4 is 6
2. 2+3%2*4 is 6
3. 3*8/4%4*5 is 10

CONDITIONAL BRANCHING (DECISION MAKING)


 Decision is nothing but selecting the right choice between multiple alternatives.
 In computers always the decision will be made based on conditions, for a condition there are two
possibilities, either true or false.
 Always for every possibility of the decision, there will be action or set of actions defined. Based on the
condition result the possible path way will be selected.
 If the specified condition becomes true, a set of actions suitable to that will be selected for execution,
failing which the false operations will be selected.
 In C – The following possible conditional branching statements are there:
I. Simple if – statement
II. If – else statement

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
III. Nested if – else statement
IV. Else – if ladder
V. Switch statement

I. Simple if – Statement:
 In C, the simplest form of decision making is the if – statement.
 If statement will have a condition helpful in making the decision.
 If the condition is true then the statement-block will be executed.
 If the condition is false it does not do anything (or the statements block is skipped). Simply the
simple form of if statement will not have anything to do in case of the false condition.
 The condition is given in parentheses and must be evaluated as true (nonzero value) or false
(zero value).
 If a compound statement need to be provided, it must be enclosed in opening and closing
braces.
Syntax: Simple if statement
if (condition)
{
statement-block;
}
Flow Chart: Example:
Example:
main()
{
int a=10,b=20;
if(a>b)
{
printf(“%d”,a);
}
printf(“%d”,b);
}

Output:
10
20
Whenever the specified condition becomes true, statement-block gets executed. If condition
becomes false it has nothing to do.

II. If – else statement (Two – Way selection statement)


 Another form of decision making statement is two – way selection statement.
 In this not only the actions for true condition state, but also the actions for false condition state
are specified.
 The expression or condition which is followed by if statement must be enclosed in
parenthesis. No semicolon is needed for an if…else statement.
 As like simple – if, if the condition is true, the if part statements will be executed. And if
condition is false, the else part statement will be executed.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Whenever expression value is true (non – zero), statement1 will be executed. If the expression
value is false (zero), statement2 will be executed.
Compound statement:

One and only one statement is allowed in each part of if and else, use statement block
(compound statement) if more than one statement need to be specified.
Example: program for finding the biggest number in two.
#include<stdio.h>
int main(void)
{
int a,b;
clrscr();
printf(“Enter the two Numbers:”);
scanf(“%d %d”, &a,&b);
if(a>b)
printf(“%d is big”, a);
else
printf(“%d is big”, b);
getch();
return 0;
}
Output:
Enter the two Numbers:
10 20
20 is big

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
III. Nested if – else:
 Nested if…else means within the if…else you can include another if…else either in if block or in
else block.
 It is a way towards forming multi-way selection statements in C.
 By nesting the if – else within another if – else, the programmers will have the possibility of
including multiple conditions in the programs.
 With multiple conditions, there exist multiple possible paths.
Syntax: Flowchart:

Using Nested if – else, two expressions are included. With two expressions it is possible to include three
statements that is three different paths for execution.
Example: Program to find the biggest number in three numbers.
#include<stdio.h>
int main(void)
{
int a,b,c;
clrscr();
printf("Enter a,b,c values:");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is big",a);
else
printf("%d is big",c);
}
else
{
if(b>c)
printf("%d is big",b);
else
printf("%d is big",c);
}
getch();
return 0;
}
Output:
Enter a,b,c values:2 7 29
29 is big
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
The Dangling else Problem:
 The nested if – else statement has to be used with extra care, otherwise it may lead to dangling else
problem.
 This problem arises when there is no matching else for every if in the statement.
 In C, always an else part is paired with the most recent unpaired if.
 Doing so may result that some of the if statements may left unpaired.

Syntax: Flowchart:

Consider the above example syntax, from the syntax it is clear that the programmer intended the else
statement to be paired with the first if, but the compiler pair it with the second if. This is known as
dangling else problem.

 The solution to the dangling else problem can be obtained by simply taking a compound statement (a set
of curly braces to separate the true part for the first if statement) into consideration.
Syntax: Flowchart:

Consider the above figure; from this it is clear that when compound statement (curly braces) is used the
true part for the first if statement is separated, now the else will be paired with the first if and the
second if remains unpaired.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The else-if ladder:
 Nested if – else can be used in such a way, so that the programmers can put more number of
conditions into it, to have multiple paths.
 It is way of having multiple paths flows (multiway – selection) in a program known as else – if ladder.
 In else – if ladder, the first if is coded with its associated statements, the else part for this if will have
another if statement with its associated statements, this series will continue until the programmers need
is satisfied. This structure will form a ladder of if – else – if – else – if …. Hence the name else – if
ladder.
Syntax: Flowchart:

The conditions are evaluated from the top to down. As soon as a true condition is found the
statement associated with it is executed and the control is transferred to the statementx by skipping
the rest of the ladder. When all n conditions become false, final else containing default statement
that will be executed
Example:
#include<stdio.h>
int main(void)
{
float m1,m2,m3,m4;
float avg;
system("cls"); //clrscr();
printf("Enter marks for (m1,m2,m3,m4):\n");
scanf("%f %f %f %f",&m1,&m2,&m3,&m4);
avg=(m1+m2+m3+m4)/4;
if(avg>=75)
printf("\nDistinction");
else if(avg<75 && avg>=60)
printf("\nFirst Class");
else if(avg<60 && avg>=50)
printf("\nSecond Class");
else if(avg<50 && avg>=40)
printf("\nThird Class");
else
printf("\nFail");

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
getch();
return 0;
}
Output:
Enter marks for (m1,m2,m3,m4):
65 75 69 78
First Class

 Switch Statement:
 The switch statement is a way to implement a multiway selection statement in C.
 The switch statement is used only when the selection condition reduces to an integral expression.
 If the selection condition is not an integral value, the else – if ladder is used.
 Switch is selection statement in which decision for selection is made between many alternatives.
 A switch statement allows a single variable to be compared with several possible case labels, which
are represented by constant values.
 If the variable matches with one of the constants, then an execution jump is made to that point.
 A case label cannot appear more than once.
 When none of the case labels are matching with the conditional expression then a default case will be
evaluated.

Syntax: Flowchart:

To break every case, so as to avoid multiple case execution when matching case is found,
the break statement is used. Practically speaking every case should have a break
statement as the last statement to avoid the execution of multiple statements.
 Break causes the program to jump out of the switch statement, that is go to the
closing braces (}) and continues the remaining code of the program.

Example:
#include<stdio.h>
int main(void)
{
char ch;
system("cls"); //clrscr();
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("Enter your choice(R,B,G):\n");
scanf("%c",&ch);
switch(ch)
{
case 'R':printf("RED");
break;
case 'B':printf("BLUE");
break;
case 'G':printf("GREEN");
break;
default: printf("Invalid Option...!");
}
getch();
return 0;
}
Output:
Enter your choice(R,B,G):
B
BLUE

LOOPS IN C (REPETITION)
 Loops are nothing but an approach to repeat set of statements for a specific number of times.
 Every repetition is known as an iteration in the programming terminology.
 The real power of computers is in their ability to repeat an operation or a series of operations many times.
 This repetition, called looping, is one of the basic structured programming concepts.
 Each loop must have an expression that determines the termination point for the loop. If there is no
termination point specified the loop will iterate for infinite number of times.
 The basic loop concept is shown in the following figure, as there is no termination condition specified the
loop will iterate infinitely.

 Loops in C are broadly categorized as pretest loops and posttest loops.


 Pretest Loops: In pretest loops, in every iteration the condition (which is used to terminate the loop) will
be tested before the body of the loop gets executed. If the condition is true, the body of the loop gets
executed, and if the condition is false the loop exits.
 Posttest Loops: In posttest loops, in every iteration the condition (which is used to terminate the loop)
will be tested after the body of the loop gets executed. If the condition is true, the body of the loop gets
executed, and if the condition is false the loop exits.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The major difference between a pretest and a posttest loop is, in a pretest the body of the loop executes
zero or more times, but in a posttest loop the body of the loop executes one or more times.
 That is if the termination condition fails in the first iteration, in a pretest loop the body of the loop never
executes, but in a posttest loop body of the loop executes at least once, after that only the condition will be
checked.
Initialization and Updating:
 The main entity which controls the complete loop functioning is the termination conditions, which
specifies when the loop will terminate, failing which the loop will enter into an infinite number of
iteration.
 Hence there is a need to do some change in the condition, so as to meet the termination point.
 Initialization must be done before the loop body, generally the initialization part initialized the operands
involved in termination condition expression.
 The update process helps in making changes to the termination condition, if there is no change in the
condition the loop will enter into infinite. Update process updates the operands involved in the
termination condition. The update process will be done inside body of the loop, as it has to be updated in
every iteration of the loop.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Comparison between Pre-test and Post-test Loops:

LOOPS IN C (while, do – while and for Loops)


 In C, there are three different types of loops: while loop, do – while loop and for loop.
 While and do – while loops can be used as event controlled loops, and the for loop is used as
counter controlled loop.
 All three loops continue as long as the termination condition becomes true. Once the termination
condition fails they will terminate.
 For every loop the initialization part and update part has to done as per the requirement.

while loop:
 The while loop is a pretest loop.
 It uses an expression (termination condition) to control the loop.
 As it is a pretest loop it tests the expression before every iteration of the loop.
Syntax: Flowchart:

 No semicolon is required at the end of the while statement.


 But to the within the while statements semicolon is needed.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Example: To print 1 to 10 natural numbers


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
i=1;
while (i<=10)
{
printf("%d ",i);
i++;
}
getch();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

do – while loop:
 The do – while loop is a post-test loop.
 Like while loop, do – while also uses an expression to control the loop.
 It tests the condition after the execution of the body.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Unlike other looping statement a semicolon is required at the end of the do – while statement, and
also to the statements within the body.
Example: To print 1 to 10 natural numbers
#include<stdio.h>
int main()
{
int i;
system("cls"); //clrscr();
i=1;
do
{
printf("%d ",i);
i++;
}while(i<=10);
getch();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

 In while loop if the condition becomes false in the first iteration, the body of the loop never gets executed.
But in do – while the body of the loop gets executed at least once, even if the condition fails in the first
iteration.

for loop:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The for loop statement is a pretest loop statement. It tests the condition in each iteration before the body
gets executed.
 Generally the for contains three expressions, the first expression is an initialization expression, the second
expression is a limit test expression (termination condition) and the third expression is a updating
expression.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.
 The expression1 in the syntax will be executed only once when the loop starts, expression2 will be tested
in every iteration before the execution of the body (hence the name pretest) and expression3 after
executing the body of the loop.
Syntax: Flowchart:

Note that the semicolon is not required at the end of the for loop statement, but the statement
within the loop body do require semicolons at the end.
The following figure compares the while loop and for loop

Example: To print 1 to 10 natural numbers


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
for(i=1;i<=10;i++)
{
printf("%d ",i);
}
getch();
return 0;
}
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Output:
1 2 3 4 5 6 7 8 9 10

Nested for Loop:


 Generally all forms of loops supports nesting concepts, but it can be more comfortable to use nested for
loops whenever necessary.
 Nested for loop is nothing but having a for loop as a part of another loop.
Example: printing number in matrix format
#include<stdio.h>
int main(void)
{
int i,j;
system("cls"); //clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=4;j++)
printf("%d ",j);
printf("\n");
}
getch();
return 0;
}
Output:
1234
1234
1234

The different forms of using a for loop:


 The for loop can be used in the following forms
Option 1:
for (k= 1; k< = 10 ;)
{
printf(“%d”, k);
k = k + 1;
}
 Here the increment is done within the body of the for loop and not in the for statement.
Note that the semicolon after the condition is necessary.

Option 2:
int k = 1;
for (; k< = 10; k++);
{
printf(“%d”, k);
}
 Here the initialization is done in the declaration statement itself, but still the semicolon
before the condition is necessary.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Option 3: The infinite loop
 One of the most interesting uses of the for loop is the creation of the infinite loop.
 Since none of the three expressions that form the for loop are required, it is possible to
make an endless loop by leaving the conditional expression empty.
 For example: for (; ;)
printf(“The loop will run forever\n”);

Other looping statements (break and continue)


Break statement:
 If used in a loop, the break statement causes the loop to terminate.
 It is same like as of the termination condition is becoming false.
 In a series of nested loops the break statement terminates only the loop where it got invoked.
 When using a break statement, it needs a semicolon at the end.
 The break statement can be used in any of the loops while, do – while and for, and even in selection
statements.
Syntax:

Example: Demonstrate the use of break


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
i=1;
while(i<=10)
{
if(i==8)
break;
printf("%d ",i);
i++;
}
printf("\nOther statements");
getch();
return 0;
}
Output:
1234567
Other statements

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Continue Statement:
 Unlike the break statement the continue statement does not terminate the loop, but simply transfers the
control to the testing condition in while and do – while, and in for loop it transfers the control to the
update statement.
 The continue statement when encountered in the body of the loop, simply skips the remaining part in the
current iteration and continues with the next iteration.
Syntax:

Example: Demonstrate the use of continue


#include<stdio.h>
int main()
{
int i;
system("cls"); //clrscr();
for(i=1;i<=10;i++)
{
if(i == 3)
continue;
printf("%d ",i);
}
getch();
return 0;
}
Output:
1 2 4 5 6 7 8 9 10

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
ARRAYS IN C:

 If we have to read, process and print 10 integers, then we need 10 integers in memory for the duration of
the program.
 We can declare and define 10 variables with a different name.
 To read these 10 variables from the keyboard we need 10 read statements, and also to print these 10 variables
onto the output screen we need 10 output (printf) statements. This is something redundancy in programming
code.
 The approach may look simpler and acceptable to some extend for 10 variables, but if the variable count
increases rapidly, nowhere the above concept is acceptable.
 To process large amount of data, C uses a powerful data structure called array.
 An array is a collection of elements of the same data type.
 Array elements can be initialized, accessed and manipulated using the indexing.
Example: score[10] Here score will contain 10-elements
 Array index always start at ‘0’ and end at total-number of elements minus one.
 In our example the index for score will start at 0 and end at 9.

Using Arrays in C
C provides two different types of arrays
 One-Dimensional arrays: In One-dimensional arrays the data are organized linearly in only one direction.
 Two-Dimensional arrays: In Two-Dimensional arrays the data are organized in rows and columns, like a
matrix.

ONE-DIMENSIONAL ARRAYS:
Array declaration and definition
 Like every other object in C, an array must be declared, defined and initialized before it can be used in the
program.
 Array declaration tells the compiler the name of the array.
 Array definition specifies the size or number of elements in the array. In a fixed length array, the size of
the array is a constant and must have a value at the compile time.
Example: type arrayname[array_size];
 The declaration and definition format for a variable length is same as like a fixed length array except the
size is a variable. The array size will be determined when the program is executed. Once the size is
determined it cannot be changed.

Accessing elements in arrays:


 To access the individual elements in an array the array index can be used. The index must be an integral
value or can be an expression that evaluates to an integral value.
 To process all the elements in the array a loop can be used. Consider the following code segment:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
for(i=0;i<10;i++)
printf(“ %d”, scores[i]);
 The arrays name is the symbolic reference for the address to the first byte of the array. The index
represents an offset from the beginning of the array to the element being referenced.

Storing values in Arrays:


 Declaration and definition only reserves space for the elements in the array.
 To store values in the array they must be initialized.
 To initialize values in the array elements they can be read from the keyboard or they can be assigned with
individual values.

Initialization:
 Array elements in a fixed-length array can be initialized when they are declared. For variable-length
arrays they cannot be initialized when they are defined.
 To initialize the array elements with a set of values, they must be enclosed in braces and separated by
commas.
 It is a compile error to specify more values than elements in the array.
 The initialization can be done in the following ways:
(a) Basic initialization: int scores[5]={3,7,12,24,45};
(b) Initialization without size: int scores[]={3,7,12,24,45};
(c) Partial initialization: int scores[5]={3,7,0,0,0};
(d) Initialization to all zeros: int scores[5]={0};

The first example array the score array will have 5-elements and they contain specific set of values.
In the second example, when the array is completely initializing then the size attribute can be omitted.
In the third example, if the array is initialized with partial values rest of the elements will be
initialized to zero.
In the fourth example can be used to initialize all the elements to zeros.

Inputting values:
 An array can be initialized from the keyboard. The values can be read from the keyboard and initialized to
array.
 The most appropriate loop to use with arrays is the for loop.
for(i=0;i<9;i++)
scanf(“%d”,&scores[i]);
Assigning values:
 Array elements can be assigned individually by using a set of values, with the help of assignment operator.
Example: scores[4]=10;
 Assigning one array to another array is not possible even if they match fully in type and size. To do so we
have to copy all the elements individually from one array to another.
for(i=0;i<10;i++)
scores[i]=temp[i];
Printing values:
 To print the contents of the array, a normal for loop can be used.
Example: for(i=0;i<10;i++)
printf(“%d “,scores[i]);

Index Range checking:


 The C-language does not check the boundary of an array.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 As a programmer it is our job to ensure all references to indexed elements are valid and within the range.
 If an array is used with an invalid index, the results will be unpredictable.
Example: for(i=1;i<=10;i++) // indexing going out of range
printf(“%d “,scores[i]);

//Program to calculate sum of all the array elements.


#include <stdio.h>
int main(void)
{
int a[10];
int i, size, sum=0;
printf("Enter the size of the array[<10]:");
scanf("%d", &size);
printf("\nEnter the elements of an array:");
for (i=0;i<size;i++)
scanf("%d",&a[i]);
for (i=0;i<size;i++)
sum+=a[i];
printf("Sum of all array elements: %d",sum);
getch();
return 0;
}
Output:
Enter the size of the array[<10]:4

Enter the elements of an array:1 2 3 4


Sum of all array elements: 10

TWO-DIMENSIONAL ARRAYS
 In One-dimensional arrays the data are organized linearly in only one direction.
 Many applications require data to be stored in more than one dimension.
 Matrices require an array that consists of rows and columns as shown in the following figure, which is
generally called as two-dimensional array.

 In C-language a two dimensional array will be considered as an array of arrays. That is a two dimensional
array is an array of one-dimensional arrays.

Declaration and Definition:


 Two-dimensional arrays like One-dimensional arrays must be declared and defined before being used.
 Declaration tells the compiler the name of the array; definition specifies the type and size of each
dimension.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
 The size of a two array must be a constant and must have a value at compile time.
Example: int scores[5][4];

Initialization:
 The definition of a Two-Dimensional array only reserves the memory for the elements in the array.
 No values will be stored in the locations. The locations will generally contain unpredictable values or
garbage values without initialization.
 Initialization of array can be done when the array is defined.
 The values for the array must be enclosed in braces.
Example: int scores[3][2]={2,3,5,4,6,9};
 Nested braces must be used to show the exact number of rows and columns.
Example: int scores[3][2]={{2,3,5},{4,6,9}};
 In a Two-Dimensional array, if the array is completely initialized with values, only the first dimension can
be omitted. The second dimension must need to be specified.
Example: int scores[][2]={{2,3,5},{4,6,9}};
 The whole array can be initialized to zeros.
Example: int scores[5][4]={0};

Inputting Values:
 Another way to initialize the values is, we can read them from the keyboard.
 In Two-Dimensional array, it usually requires nested for loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
Example: for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”,&scores[i][j]);
Outputting values:
 The values inside a Two-Dimensional array can be printed using two nested loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
 To print the matrix in a table format, a newline is printed at the end of each row.
Example: for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“ %d”,scores[i][j]);
printf(“\n”);
}
Accessing values:
 Individual elements can be initialized using the assignment operator.
scores[2][0]=23;
scores[2][2]=scores[1][1]+12;

/* Write a C program to perform Addition of two matrices */

#include <stdio.h>
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
int main(void)
{
int a[2][2], b[2][2], c[2][2], i, j;
system("cls"); //clrscr();
printf("\nEnter values for matrix A(2X2):\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d", &a[i][j]);

printf("\nEnter values for matrix B(2x2):\n");


for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);

for(i=0; i<2; i++)


for(j=0; j<2; j++)
c[i][j] = a[i][j]+b[i][j];

printf("\nThe resultant matrix C(2x2):\n");


for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
printf("%d ", c[i][j]);
printf("\n");
}
getch();
return 0;
}
Output:
Enter values for matrix A(2X2):
2468

Enter values for matrix B(2x2):


8642

The resultant matrix C(2x2):


10 10
10 10

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
STRINGS
 A string is a series of characters treated as a single unit.
 String is a variable length piece of data. Strings are divided into two major categories.
o Fixed length strings.
o Variable length strings.

Fixed length strings:


 In implementation of a fixed-length string, the important thing is to make decide the size of the variable. If
we make it too small, it sometimes can’t store all of the data. If we make it too big, we waste the memory.
 Another problem is how to differentiate between data and non-data. A solution is to use special characters
like spaces to indicate non data. In this case the space can’t be used as a character in the string.

Variable-Length strings:
 A much preferred solution is to create a structure that can expand and contract according to the size of the
value we want to store.
 Example: To store a person name with only three characters the structure should contract and provide
three characters and to store a person name with 30-characters the structure should expand and provide
30-characers.
 Here also there is a problem: as we are using a variable length structure in computers memory, there must
be a way to indicate the end of the string.
 Two common techniques are used to indicate the end of the string.
o Length-Controlled Strings
o Delimited Strings

Length-Controlled Strings:
 In this type of strings a count is used as the first character in the string that specifies the number of
characters in the string.
 This count then be used by string manipulation functions to determine the length of the string.

Delimited Strings:
 In this type of strings the end is specified by a special character known as delimiter, hence the name
delimited strings.
 This concept is similar to using a full stop (.) at the end of a sentence in English. Where each sentence is
of variable length and a special symbol full stop is used to indicate the end of the sentence.
 The disadvantage of using a delimiter is that it eliminates one character from being used for data in the
string.
 The most common delimiter is a null character (\0).
 All C strings are of variable length and delimited once.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
C-Strings
 A C string is a variable length array of characters that is delimited by the null character.
 A string is stored in an array of characters and delimited by a null character (\0).

 As a string is stored in an array, the name of the string is a pointer to the beginning of the string.
 There is a big difference between how a character is stored in memory and a one-character string is stored.
The character requires only one memory location, but the one-character string requires two memory
locations one for actual character and one for delimiter.
 To store an empty string in memory also requires one memory location to store the delimiter.

String Constants:
 A string literal or a string constant is a sequence of characters enclosed in double quotes.
 When string constants are used in a program, C automatically creates an array of characters, initializes to a
null delimited string, and stores it.
Example: “C is a programming language”
“Hello World”
 A string literal is stored in memory like any other object. It has an address, and can be referred by using a
pointer. Here the string literal as it is a sequence of characters, itself a pointer constant to the first element.
 The string itself can be used to refer the individual characters by using index.
Example: “hello”[1]  e

Declaring and defining Strings:


 C has no string type. To use strings in C programming they must be declared and defined as character
arrays.
 When defining the array to a store a string, we must provide enough space for both actual data and
delimiter.
Example: char str[9];
 In this example it is possible to store a string of eight characters long as the last character must be a
delimiter.
 A character pointer can also be used to hold strings of variable length in a program, because the name of
the string or the string itself is a reference to the starting memory location.
Example: char* pStr;
Initializing Strings:
 Initialization of strings is much like initialization any other object in C. We use assignment operator to
initialize the string when they are defined.
Example: char str[9]=”Good day”;
 As declaration, definition and initialization all are happening at a same point of time, the size attribute can
be ignored.
Example: char str[]=”Good day”;

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Strings can be initialized by using a set of characters where the last character is going to be the delimiter.
This method is not used, because it is very tedious to code.
Example: char str[9]={‘G’,’o’,’o’,’d’,’ ‘,’D’,’a’,’y’,’\0’};
 The most common way for defining and initializing a string in programming is using a pointer. This
method first creates a string literal into the memory and assigns its address to the character pointer. Later
that pointer can be used to refer the string.
Example: char* pStr=”Good Day”;
String Input/Output functions
Functions gets() and puts() are two string functions to take string input from the user and display it respectively.

#include<stdio.h>

int main(void)
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Strings and the Assignment Operator


 The string is an array and the name of the string is a pointer constant.
 As a pointer constant is should always be used as an rvalue but not as lvalue.
Example: char str1[6]=”Hello”;
char str2[6];
str1=str2; //compile error
String Manipulation Functions:
 The C Library provides a rich set of string handling functions that are placed under the header file
<string.h> and <ctype.h>.

 Some of the string handling functions are (string.h):


o strlen() strcat() strcpy()
o strcmp() strstr() strrev()

 Some of the string conversion functions are (ctype.h):


o toupper() tolower()

 C provides different predefined set of string functions which are helpful in manipulating the strings.

String Length
strlen () function:
 This function counts and returns the number of characters in a string. It takes the form
Syntax: int n=strlen(str);

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Where n is an integer variable, which receives the value of the length of the string. The counting ends at
the first null character.
 The string length function (strlen) returns the length of a string that is the number of characters in the
string excluding the null character.
 If the string is empty then the string length function returns zero.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
int len;
char str[]="hello";
len=strlen(str);
printf("%d",len);
getch();
return 0;
}
Output:
5

String Copy
 The String copy functions strcpy(); copies the contents from one string including the null character to
another string.
 There are two string copy functions:
I. Basic string copy strcpy();
II. String copy length controlled strncpy();

I. Basic string copy strcpy();


 The basic string copy function strcpy(); copies the contents of the from one string fromstr
including the null character to another string tostr.
Syntax: strcpy(tostr,fromstr);
 If fromstr is longer than the tostr then, the data in memory after tostr is destroyed.
 The destination string should be large enough to hold the source string.
 If fromstr is longer than tostr, the data in memory after tostr is destroyed.
 The function returns the address of tostr.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char fromstr[]="hello",tostr[10];
strcpy(tostr,fromstr);
puts(tostr);
puts(fromstr);
getch();
return 0;
}

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Output:
hello
hello

II. String copy length controlled strncpy();


 String copy length controlled strncpy(); function copies the content of one sting to another, but it
sets a maximum number of characters that are to be copied.
 This function contains a parameter that specifies the maximum number of characters that can be
copied at a time.
Syntax: strncpy(tostr,fromstr,size);
 If the actual size of the fromstr is equal or greater than size parameter, then size number of
characters are copied.
 If the fromstr size is smaller than the size parameter, the entire string is copied and then null
characters are inserted into the tostr until the size parameter is satisfied.
 If the fromstr is longer than the size the copy stops after size bytes have been copied. In this case
the destination variable tostr may not be a valid string; that is it may not have a delimiter.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char fromstr[]="hello",tostr[10];
strncpy(tostr,fromstr,2);
puts(tostr);
puts(fromstr);
getch();
return 0;
}
Output:
he
hello

Sring Compare
C has two string compare functions:
I. Basic string compare strcmp();
II. String compare length controlled strncmp();

I. Basic string compare strcmp();


 The strcmp(); function compares the two string until an unequal character is found or until the end of
the string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: strcmp(str1,str2);
 If both strings are equal the function returns zero. If length of str1 < str2, it returns < 0 value. If length
of str1 > str2, it returns > 0 value.

II. String comparison length controlled strncmp();

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The strncmp(); function compares the two strings until unequal character is found in a specified number of
characters have been tested, or until the end of the string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: int strncmp(str1, str2, size);
 If both strings are equal the function returns zero. If length of str1 < str2, it returns < 0 value. If length of
str1 > str2, it returns > 0 value.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "Hydarabad" ;
int i, j, k;
i = strncmp ( str1, str2, 3) ;
j = strncmp ( str1, str2, 4) ;
k = strncmp ( str1, str2, 10) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Output
0 4 4

String Concatenation
 The string concatenation function appends one string to the end of another string.
 The size of the destination string should be large enough to hold the resulting string. If it is not the data at
the end of the destination string will be destroyed.
 C has two string concatenation functions:
I. Basic string concatenation strcat();
II. String concatenation length controlled strncat();

I. Basic string concatenation strcat();


 The function copies str2 to the end of str1, beginning at the delimiter. That is the delimiter is
replaced with the first character of the str2. The delimiter from str2 is copied to the resulting string.
Syntax: strcat(str1, str2);
 The resulting string length is the sum of the length of str1 plus the length of str2.
 The function returns the address pointers to the resulting string.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strcat ( str1, str2);
printf ( "%s", str1);
getch();
return 0;
}
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Output
HyderabadISL

II. String concatenation length controlled strncat();


 The strncat(); function copies only the specified number of characters from source string str1 to
destination string str2. A null character is appended at the end.
Syntax: strncat(str1, str2, size);
 If the length of str2 is less than size, then the function will work in same as basic string copy.
 If the length of str2 is greater than size, then only the number of characters specified by size are
copied, and a null character is appended at the end.
 If the value of size is zero or less than zero, then no characters are copied.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strncat ( str1, str2, 2) ;
printf ( "%s", str1 ) ;
getch();
return 0;
}
Output
HyderabadIS

Search for a substring


 Searching for a sub-string in a string can be done only from the beginning of the string.
 The function strstr(); is used to locate a substring in a string from the beginning of the string.
Syntax: strstr(string, sub_string);
 If sub_string exists in string then a pointer pointing to the first character of the sub_string is returned.
 If sub_string does not exist in string then a null pointer is returned.

String reverse
strrev() function:

 The function strrev is used to reverse the contents of the given string.
 The function strrev(); takes the string and reverses it, and places the reversed string in the given string
only.
Syntax: strrev(string);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
char s[]="hello";
strrev(s);
puts(s);
getch();
return 0;
}
Output:
olleh

Changing the case of characters toupper() and tolower() functions:


toupper() function:

 toupper() function takes the character value as parameter, and converts it into the uppercase character.
 If the converted character is already in upper case, it remains as it is.
Syntax: tolower(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'i';
printf("%c",toupper(ch));
getch();
return 0;
}
Output:
I

tolower() function:

 tolower() function takes the character value as parameter, and converts it into the lowercase character.
 If the converted character is already in lower case, it remains as it is.
Sybtax: tolower(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'I';
printf("%c",tolower(ch));
getch();
return 0;
}
Output:
i

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
toascii() function:

 toascii() function takes the character value as parameter, and converts it into the equivalent ASCII value.
Syntax: toascii(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'A';
printf("%d",toascii(ch));
getch();
return 0;
}
Output:
65

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com

You might also like