Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Module 2

Syllabus
Fundamentals of C programming:

Branching and Looping- IF statement, IF..else statement, Nesting of if..Else


statement, Else if ladder, Switch Statement, The? : Operator, Go To statement,
While, Do while, For, break and continue statements.

Arrays - One, Two & multidimensional arrays.

Strings – Introduction to strings.

Advanced features-Type casting, type conversion.

Formatted and unformatted Input/Output- scanf(), printf(), gets(), puts(), getch()


and putch().
INTRODUCTION
So far, the statements in our programs have been executed in their physical
order. The first statement is executed, then the second statement, and so on until all of
the statements have been executed. But what if we want the computer to execute the
statements in some other order? Suppose we want to check the validity of input data and
then perform a calculation or print an error message, not both. To do so, we must be able
to ask a question and then, based on the answer, choose one or another course of
action.
The order in which statements are executed in a program is called the flow of
control. In a sense, the computer is under the control of one statement at a time. When
a statement has been executed, control is turned over to the next statement (like a
baton being passed in a relay race).

Flow of control is normally sequential. That is, when one statement is finished
executing, control passes to the next statement in the program. When we want the flow
of control to be nonsequential, we use control statements, special statements that
transfer control to a statement other than the one that physically comes next.
Structured high-level languages, such as C contain statements that can also alter
the flow of a sequence of instructions. These statements are called as control
statements. C provides two types of control statements.

1. Selection
2. Iteration

i. Selection : Using selection, statements can be executed conditionally. That is, if


a certain condition is true, then one sequence of statements will be executed.
These types of statements help us to jump from one part of the program to
another. This transfer of control may be based on certain conditions or may be
unconditional.

ii. Iteration : Using iteration, a set of statements to be performed repeatedly until


a certain condition is fulfilled. The iteration statements are also called loops or
looping statements.

SELECTION STATEMENTS

The selection statements allow to choose the set-of-instructions for execution


depending upon an expression's truth value. C provides two types of selection
statements : if and switch. In addition, in certain circumstances ? operator can be
used as an alternative to if statement. The selection statements are also called
conditional statements or decision statements.

if statement

The if statement is the simplest form of selection statement. It is very frequently


used in decision making and altering the flow of program execution. The if structure has
four different forms ( Simple if, if-else, Nested if-else and else if ladder). The simpler
form of an if statement is

Format I : if ( expression ) statement;

Where expression is any valid C expression (Arithmetic, Relational or Logical). The


expression must be enclosed in parentheses. If the expression evaluates to true i.e. a
nonzero value, the statement is executed, otherwise ignored. Where a statement may
consists of simple statement or a compound statement.

Figure: Action of if statement

The command says “if this condition is true” then perform the following
instructions. If the condition is false, the computer skips the instruction that is
part of the if command, and moves on to the next instruction in the program. The
statement part of the structure will be executed if and only if the expression is true. If
the expression is false, then the statement part of the structure will be ignored.

Example: Consider the following if statement :

if (a >b ) a=a + 2;
b=a+2;

This if statement specifies that when the expression a > b is true, then execute
the statement a=a+2 and the statement b =a+2, otherwise, the control of program
should goto the statement immediately following it, that is b=a+2;

Example: if (weight > 1000)


printf("Allowable weight exceeded");

This statement causes the message to be printed only when the variable weight
has a value greater than 1000. C does allow you to take advantage of the fact that the
expression is evaluated as a number. If the expression evaluates to 0, it is false, and if
non-zero, the expression is evaluated as true.

Example: The expression that follows is a common statement in C but is not usually
found in other languages.

if((ch = getchar()) =='\n')


printf("End of line");

First, the expression calls the function getchar(), then the result is assigned to ch.
Finally, the value of ch is examined to see if it is equal to a newline character. The
parentheses are required because == has a higher precedence than = and you want the
assignment operator to take effect before the relational operator.

Example: Consider the following if statement

if (( average >= 60 ) || (grade =='A') )


printf ("FIRST CLASS");

The message “FIRST CLASS” is written out if average greater than or equal to 60
or if the grade represents the character ‘A’ ( or if both conditions are true).
Program: Write a program to find the largest of two numbers.
#include<stdio.h>
main()
{
int a,b,big;
printf("Enter two numbers");
scanf("%d%d",&a,&b);
big=a;
if(big<b)
big=b;
printf("Largest of %d and %d is %d",a,b,big);
}
Program: In a readymade showroom 20 % discount will be given if the clothes worth Rs.
5000 is purchased, otherwise no discount is given. Write a C program to calculate the
net-amount and discount.
#include <stdio.h>
main()
{
float amount,discount,netamount;
printf("Enter sales amount");
scanf("%f",&amount);
discount=0; /* Initialize discount valueto zero */
if (amount >= 5000) discount=0.2;
discount = amount * discount;
netamount=amount - discount;
printf("\nAmount =%.2f",amount);
printf("\nDiscount= %.2f",discount);
printf("\nNet amount=%.2f",netamount);
}
Program: Write a C program to input principal amount and time. If time is more than 10
years, calculate the simple interest at the rate of 8%, otherwise calculate it at the rate of
12% per annum.
#include <stdio.h>
main()
{
int principal,time,rate;
float simple_interest;
printf("Enter the principal");
scanf("%d",&principal);
printf("Enter the time ");
scanf("%d",&time);
rate=12;
if(time>10) rate=8;
simple_interest =(long) principal * time*rate/100.0;
printf("SIfor%dyears=%.2f",time,simple_interest);
}

if-else statement
All the examples of if we have seen so far allow you to execute a set of
statements if a condition or expression evaluates to true. What if there is another course
of action to be followed if the expression evaluates to false. There is another form of if
that allows for this kind of either or condition by providing an else clause.
The general form of the if-else is

if (expression )
Format II Statement-1;
else
Statement-2;
If the expression is evaluated as true, i.e., a nonzero value, then Statement-1 is executed,
otherwise Statement-2 is executed. Notice that one statement or the other is always
executed, not both. Both the statements Statement- 1 and Statement-2 can be simple or
compound.

Example: Suppose you want to find the largest of two numbers use the following if
statement.
if (a>b)
printf("Largest number is %d",a);
else
printf("Largest number is %d",b);
Program: A program to check whether a number is even or odd.
#include<stdio.h>
main()
{
int num;
printf(“ Enter a number“);
scanf("%d",&num);
if(num % 2 == 0)
printf("Number is even");
else
printf("Number is odd");
}
Program: Write a C program to input choice(1 or 2). If choice is 1, print the area of a circle
otherwise print the circumference of circle. Accept the radius of circle from user.
#include <stdio.h>
#define PI 3.14157

main()
{
int choice;
float r,area,circumference;
printf("Circle problem Menu\n");
printf("1. Area of the circle\n");
printf("2. Circumference of the circle\n");
printf("Enter your choice ");
scanf("%d",&choice);
printf("Enter the radius of the circle ");
scanf("%f",&r);
if(choice==1)
{
area = PI * r *r;
printf("\nArea of the circle = %.2f",area);
}
else
{
circumference=2 * PI * r;
printf("Circumference of circle =%.2f",circumference);
}
}
Nested if statement
A if statement may itself contain another if statement inside it, then it is known
as nested if statement. One of the nested if statement is given below:

If the expression 1 is false, the Statement 3 will be executed; otherwise it


continues to perform the expression 2. If the expression 2 is true, the Statement-1 will
be executed; otherwise the Statement-2 is evaluated.
The if statement may be nested as deeply as you need to nest it. One block of
code will only be executed if two conditions are true. Expression 1 is tested first and then
expression 2 is tested.
Example:
if (a >b)
if(a>c)
big=a;
The second if statement is nested in the first. The second if condition is tested
only when the first condition is true, so the variable big is assigned only when both
conditions are true.
Program: A program to find the largest of three numbers using nested if.
#include<stdio.h>
main()
{
int a,b,c,big;
printf("Enter three numbers ");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
if(a>c)
big=a;

big=c;

else
else
if (b>c)
big=b;
else
big=c;
printf("Largest of %d,%d and %d = %d",a,b,c,big);
}
Program: Program to find the largest, second largest and smallest of three numbers.
#include<stdio.h> main()
{
int a,b,c,lar,small,seclar;
printf("Enter three numbers ");
scanf("%d %d %d",&a,&b,&c);
if (a > b)
{
lar=a;
small=b;
}
else
{
lar=b;
small=a;
}
if ( lar < c)
lar= c;
else
if (small > c) small=c;
printf("\n Largest number = %d’,lar);
printf("\n Smallest number =%d’,small);
seclar=(a+b+c) - (lar+small);
printf("\nSecond largest =%d",seclar);

}
else-if ladder
This construct is an extension of if-else structure. A general else-if ladder
selection construct is of the form:

If expression-1 is true only Statement-1 is executed. The control is transferred to


the statement following Statement-n+1. If expression-1 is false then one of the
statements, Statement-2, Statement-3,..,Statement-n+1, is executed depending upon
which expression is true. If expression-2 is true, then Statement-2 is executed, If
expression-3 is true, then Statement-3 is executed and so on ... . If none of the condition
is true, then Statement-n+1 is executed. In each case after statement execution, control
is transferred to the statement following the Statement-n+1. The flow of control in else-
if ladder is shown in Figure.
Program: Write a program to find the largest of three numbers using ladder if.
#include <stdio.h>
main()
{
int a,b,c;
printf("Enter three numbers \n");
scanf("%d%d%d",&a,&b,&c);
if(a>b &&a>c)
largest = a; else
if(b>c)
largest=b;
else
largest=c;
printf("\nLargestof%d,%dand%d=%d",a,b,c,largest);
}
Program: A program to grade the students according to the following rules.

70 to 100 Distinction First


60 to 69 class Second
50 to 59 class Pass class
40 to 49 Fails
0 to 39

#include<stdio.h>
main()
{
int marks;
printf("\nEnter marks");
scanf("%d",&marks);
if((marks<=100) && (marks>=70))printf("\nDistinction"); else
if(marks>=60) printf("\nFirstclass");
else if(marks>=50) printf("\nSecond class");
else if(marks >=40) printf("Pass class");
else printf("Fails");
}

Character type functions


C supports many character type functions which are given in below table.
These functions are contained in the file ctype.h and therefore the statement

#include <ctype.h>

must be included in the program.


Function name Remarks

isalnum( char ) Is char an alphanumeric character?


isalpha( char ) Is char an alphabetic character?
isdigit( char Is char is a digit?
islower( char ) Is char is a lower case letter?
Is char is a white space character?
isspace( char )
Is char an upper case letter?
isupper( char )

Table: Character type functions


Program: Check if a character that is input is a letter or a digit or a special character
using built in functions.
#include <stdio.h>
#include <ctype.h>
main()
{
char ch;
printf("Input a character ");
ch=getchar(); printf("%c",ch);
if(isalpha(ch))printf(" isaletter");
else if(isdigit(ch))printf("isadigit");
else printf("isaspecialcharacter");
}

The above program receives a character typed from the keyboard and tests
whether it is a letter or digit and prints out accordingly. These tests are done with the
help of character type functions.

MULTIWAY DECISIONS - switch statement


Unlike the if, which allows a selection of two alternatives, the switch statement
allows a program to select one statement for execution out of a set of alternatives.
During the execution of the switch statement, only one of the possible statements will
be executed; the remaining statements will be skipped. The format of this statement is
:

When the switch statement is executed, the control expression (integer


expression or a character variable) is evaluated first, and the value is compared with the
case label (constant) values in the given order. If a label matches with the value of the
control expression, then the control is transferred directly to the group of statements
following that label. If none of the label values with the value of the control expression,
the statement against default is executed. The default is optional in a switch
statement. When it is not present, and the value of the control expression does not
match with the value of any of the case labels, then no action will take place, in this case
control is transferred to the statement that follows the switch construct.

The break statement at the end of each block signals the end of a particular case
and causes an exit from the switch statement, transferring the control to the statement
that follows the switch construct. The action of the switch can be represented
schematically as shown in below figure.

Example: Consider the following switch statement :


switch ( j )
{
case 1: printf("ONE");
break;
case 2:
printf("TWO");
break;
case 3: printf("THREE");
}
Statements labelled 1 is executed when j = 1 and statement 2 is executed for j =
2. When j = 3 statement labelled 3 is executed.
Example: Consider the following program segment : a=2;
switch( a )
{
case 1 : printf("Value is one\n ");
break;
case 2 : printf("Value is two\n");
case 3 : printf("Value is three\n");
}
In this example the output is
Value is two
Value is three
because there is no break after case label 2. Consequently, control flows on to the next
printf, regardless of the match. Once a match has been found, each executable
statement in the switch construct is executed in order until either a break statement is
encountered or the end of the switch is reached. The break statement transfers
control to the first executable statement after the switch construct.
Program: Design a program that accept day number of the week and display the
corresponding week day.
#include <stdio.h>
main()
{
int dayno;
printf("Enterdaynumberoftheweek");
scanf("%d",&dayno);
switch (dayno)
{
case1 : printf("Sunday");
break;
case2 : printf("Monday");
break;
case3 : printf("Tuesday");
break;
case4 : printf("Wednesday");
break;
case5 : printf("Thursday");
break;
case6 : printf("Friday");
break;
case7 : printf("Saturday");
break;
default : printf("Invaliddaynumber\n");
}
}
Example: In the following program segment, the message is displayed when num is
an even number less than 10.
switch(num)
{
case 2 :
case 4 :
case 6 :
case 8 : printf("Number is even less than 10");
break;
}
Example: The switch can be used as a keyboard-character filter.
ch=getchar();
switch(ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ : printf("Vowel");
break;
default : printf("Error - not a vowel ");
}

Example: Consider the above program where a student's grade is based on the value
of a test score using nested if statements. The preceding code could be rewritten using
a switch as :
int n;
n=marks/10; /* divide marks by 10 */
switch(n)
{
case 10 :
case 9 :
case 8 :
case 7 : printf("Distinction");
break;

case 6 : printf("First Class");


break;
case 5 : printf("Second Class");
break;
case 4 : printf("Pass Class");
break;
default : printf("Fails");
}

THE TERNARY OPERATOR ?


C has an operator that can be used as an alternative to if statement. This operator
can be used to replace if-else statement. The general form of if statement

if ( expression-1 )
Statements-1;
else
Statements-2;

The above form of if can be alternatively written using ?: as follows:

expression-1 ? Statements-1 : Statements-2 ;

First, expression-1 is evaluated, if it is true, Statements-1 gets executed,


otherwise Statements-2 gets executed.
Example: Consider the following statement
if( number % 2==0)
even=1; /* TRUE */
else
even=0; /* FALSE */

1 is assigned to even if number is divisible by 2, and 0 otherwise. This can also be written
using ternary operator ( ? ) in any one of the following form

1. even=(number % 2==0) ? 1 : 0;

2. even=(number%2) ? 0 : 1 /* non-zero is true */

in case ( 2 ) if number is not divisible by 2, then the expression immediately following


the question mark is used. If number is divisible by 2, then the ex- pression following the
colon is used.
Program: A program to find the largest of three numbers using ternary operator.
#include <stdio.h>
main()
{
int a,b,c,big;
printf(“Enterthreenumbers “);
scanf(“%d%d%d”,&a,&b,&c);
big=a>b? (a>c?a:c):(b>c?b:c);
printf(“Largestof%d,%dand%d=%d”,a,b,c,big);
}

THE goto STATEMENT


Structured programming advocates avoiding the arbitrary transfer of control
provided by the goto statement. The goto statement is a simple statement, used to
transfer control from one point in a program to any other point in that program. This
action is called branching. If misused, the goto can make a program impossible to
understand. Its form is

Syntax : goto label;


......
......
label : statement;

Where label is a user defined identifier and can appear either before or after goto. This
statement provides an unconditional jump to the statement indicated by the label. No
declaration is required for the label. The syntax of the label requires a colon (:) after the
label.

Example: LOOP : printf("Mangalore ");


...............
goto LOOP;

Here LOOP is the label of statement printf("Mangalore"). During running of a


program, the flow of control will jump to the statement immediately following the label
LOOP :. This happens unconditionally.
The goto statement is discouraged in C, because it alters the sequential flow of
logic that is the characteristic of the language.
Program: A program to generate N natural numbers using goto statement.
#include <stdio.h>
main()
{
int n,i=1; printf("Entera
number"); scanf("%d",&n);
LOOP : printf("%d\t",i++);
if(i<=n) goto LOOP;
}

To avoid the use of goto, more sophisticated, tightly controlled looping


commands have been introduced : while, while-do and for. These commands makes
programs that are more easily understood, and goto is generally avoided.

LOOPS
One of the methods with which it is possible for us to achieve high
performance using a computer is by repeating the execution of identical tasks on
different data. For example we may write a program to add two numbers. The program
would be more useful if it was able to perform the operation more than once. For
performing an operation just once it would be better to use a calculator or even pencil
and paper. However when we will have to perform the operation again and again many
times, the effort of using a calculator or pencil and paper would be tedious. A program
would save us many tedious calculations.
A loop is a program construct that causes a statement to be executed again and
again. The process of repeating the execution of a certain set of statements again and
again is termed as looping. C has several such statements that can be used to form loops
they are

i. while statement
ii. do-while statement
iii. for statement

The first two types of loops i.e., the while and do-while loops, are used in
situations when the programmer does not know exactly the number of executions. Thus,
the execution will be repeated until some condition is satisfied. for loop is normally used
when the number of repetitions is known in advance.

while statement
This structure is also called as the “pre-tested” looping statement. For this
statement two different things must be specified, the statements to be repeated and
the condition. In this structure the checking of a condition is done at the beginning. The
condition must be satisfied before the execution of the statements i.e., the set of
statements in the structure(block) is executed again and again until the test condition is
true. If the test condition becomes false control is transferred out of the
structure(block).
The general form of the while statement in C programming language is as follows
:

while (test condition)

Syntax : Statement 1;
Statement 2;
……..

Statement n+1;

The execution of this statement structure works as follows:


1. The test condition is first evaluated.
2. If the value of the test condition is false then the while statement is
terminated and the control goes out of the structure.
3. If the value of the test condition is true then the statements in the structure is
executed and the control returns to the test condition.

The flowchart below shows the usage of the while structure.

Example: count = 1;
while (count <= 5 )
{
printf ("%d\t", count);
count ++;
}
In this example count is initialsed to 1, the while loop is executed as long as
count is less than or equal to 5. The output is the value of count at the beginning of each
execution of the while loop : 1,2,3,4 and 5. The loop is executed five times.
Example: sum = 0;
count = 1;
while (count <= 10)
{
sum = sum + count;
count ++;
}
printf ("Total sum = %d ", sum);

The program first initializes the value of the variable sum to zero and the value
of the variable count to one. The statements inside the structure find the sum of all
numbers from 1 to 10. The calculated sum is stored in a variable, which is finally
displayed.

Program: Program to calculate sum of first hundred natural numbers.


#include <stdio.h>
main()
{
int sum,num;
sum=0;
num=1; /* Firstnumber */
while(num<= 100)
{
sum = sum + num;
num=num+1; /* Nextnumber */
}
printf("Sum =%d \n ", sum);
}
Program: Program to display the digits of a number.
#include <stdio.h>
main()
{
int num,digit;
printf(“\nEnteranumber“);
scanf("%d",&num);
while(num >0)
{
digit=num%10;
num=num/10;
printf("\n Digit=%d", digit);
}
}
In the above program, the number is inputted to the variable num. Dividing the
number by 10 and extracting the remainder always generates the last digit(LSD) of the
number. Then find the quotient and store it in the variable num itself, so that the next
digit can be generated. The extracted digit is then displayed. The process is repeated till
the quotient is greater than 0.

Program: Program to reverse a number.

#include <stdio.h>
main()
{
long rev,n,num;
int digit;
printf("\nEnteranumber");
scanf("%ld",&num);
rev=0;
n=num;
while ( num != 0)
{
digit=num%10;
num=num/10;
rev = rev * 10 + digit;
}
printf("\nThe number is%ld",n);
printf("\nThe reverse is %ld",rev);
}
Program : Program to find the sum of the squares of following ten terms.
2, 5, 10, 17, 26, 37, 50, 65, 82, 101

#include <stdio.h>
main()
{
int sum,num,term;
sum =0;
num=1; /* Firstnumber */
while(num<= 10)
{
term=num*num+1;
sum=sum+term*term;
num=num+1; /* Nextnumber */
}
printf("Sum =%d \n ", sum);
}
OUTPUT
Sum = 26113
Program: Program to input the age of 100 employees and tell how many belong to the
age groups of :
a. 25 – 35
b. 36 – 50
c. > 50
#include <stdio.h>
main()
{
int count,age, fc=0, sc=0, tc=0; count=1;
while( count <=100)
{
printf("\nEnter the age of employee %d", count);
scanf(“%d”,&age);
if((age >=25) && (age <=35))
++fc; /* Incrementfirst category */
elseif((age>=36)&&(age<=50))
++sc; /* Increment second category */
else
++tc; /* Incrementthirdcategory */
++count; /* Nextemployee */
}
printf("\nNumberofemployeesbetween25–35is=%d",fc);
printf("\nNumberofemployeesbetween36–50is=%d",sc);
printf("\nNumberofemployeesgreaterthan50yearsis=%d",tc);

do-while statement

This structure is also called as the “post-tested” looping statement. For this
statement two different things must be specified, the statements to be repeated and
the condition. In this structure the checking of a condition is done at the end. The
condition must be satisfied for the execution of the statements after the first instance
i.e., the set of statements in the structure is executed again and again until the test
condition is true. If the test condition becomes false control is transferred out of the
structure.
The general form of the do-while statement in C programming language is as
follows:
do

Statements 1;
Statements 2;
……..
} while (test condition);
Statements n+1;

The execution of this statement structure works as follows:


1. The set of statements in the structure (block) is first executed once.
2. The test condition is then evaluated.
3. If the value of the test condition is false then the do-while statement is
terminated and the control goes out of the structure.
4. If the value of the test condition is true then control goes back to the beginning of
the structure and the statements in the structure is executed again.
The flowchart below shows the usage of the structure.

Execution of a do-while loop

Example: prod = 1;
count = 1;
do
{
prod = prod * count;
count ++;
} while (count < = 100)
printf ("Total product = %d \n", prod);
The program first initializes the value of the variable prod to one and the value
of the variable count to one. The statements inside the structure find the product of all
numbers from 1 to 100. The calculated product is stored in a variable, which is finally
displayed.

Program: Program to generate the multiplication table for a number in a proper format.

#include <stdio.h>
main()
{
int result, num, count;
printf("\nEnter a number");
scanf("%d",&num);
printf(" \nThe table is");
count = 1;
do
{
result = num * count;
printf("\n%d *%d =%d",num,count,result);
++count ;
}while(count <= 10);
}
The number for which the table is generated is inputted. The count is set to
1. The result of the multiplication of the number and the count is then found. The output
is then displayed in a proper format. The process is then repeated ten times for
incremented values of count.

Program: Program to calculate the compound interest using the expression.


CI = p * ( 1 + r / 100 ) t
#include <stdio.h>
main()
{
float prin,amt,rate,CI; int
time,year;
printf(" \nEnter principal amount,rate of interest and time ");
scanf("%f%f%d",&prin,&rate,&time);
amt=prin;
year = 1;

do
{
amt = amt * (1 + rate / 100);
++ year;
}while(year <=time);
CI=amt–prin;
printf("\n Interest earned =%.2f ",CI);
}
The principal amount, rate of interest and the time period is inputted to the
variables prin, rate and time. The year is set to 1 and the principal amount is copied to
the variable amt. The Interest for the first year is then calculated and added to the
amount. The process is then repeated for the given time period. Finally the compound
interest is calculated by subtracting the principal amount (prin) from the total amount
(amt) and the output is displayed.

Program: Program to find whether a given number is an Armstrong number. (153 = 13 +


53 + 33 ) i.e., the sum of the cubes of all the digits is equal to the original number.
main()
{
int sum,n,num,digit;
printf("\nEnter a number");
scanf("%d",&num);
sum = 0;
n = num;
do
{
digit=num%10;
num=num/10;
sum =sum + digit * digit *digit ;
}while(num>0);
if(sum==n)
printf("\n%d is an Armstrong number",n);
else
printf("\n%d is not an Armstrong number",n);
}
For statement
for statement is also called as the “fixed execution” looping structure. This
structure is normally used when we know exactly how many times a particular set of
statements is to be repeated again and again. The for statement is a looping control
structure which will execute a set of statements a specified number of times and
automatically keep track of the number of ‘passes’ through the set of statements.

for statement can be either used as the increment looping statement or the
decrement looping statement. The general form of the for statement in a programming
language is as follows:
for ( Expression 1; Expression 2; Expression 3 )
{
Statements 1;
Statements 2;
……..
}
statements n+1;

Where
1. Expression 1 represents the initialization expression.
2. Expression 2 represents the expression for the final condition.
3. Expression 3 represents the increment or decrement expression.

The execution of this statement structure works as follows :

1. Expression 1 is first evaluated i.e., the counter variable of the expression is


assigned the initial value.
2. Expression 2 is then executed i.e., the value of the counter variable is
checked to see whether it has exceeded the final value, if not the
statements in the structure(block) are executed once.
3. Control is sent back to the beginning of the structure and Expression 3 is
evaluated i.e., the value of the counter variable is either increased or
decreased depending on the statement used.
4. Step 2 is repeated again and again until the counter variable exceeds the
final value.
Figure: Execution of a for loop

Example: The statement uses a for loop to print the numbers 1 through 10 down the
screen.

for(repeat=1; repeat<=10; repeat++)


printf(“%d\n”,repeat);

When the program first encounters the loop, it sets the value of repeatto 1. It
then checks the condition to see if the value of repeat is less than or equal to 10. Since
the condition is true, it will perform the instruction that is associated with the loop,
displaying the value of the variable.

After performing the instruction, it increments the value of repeat by 1, and


again checks the condition. Since the condition is still true, it performs the instruction a
second time, displaying the current value of the variable. The process is repeated until
the value of repeat is incremented to 11. The condition repeat <= 10 is then false,
so the instruction is not performed and the loop stops.

Example: You can use a for loop without any instructions to place a timed pause in a
program:

for( delay=1; delay<=1000; delay++);

Even though there is no instruction, the loop is repeated 1000 times, as the
variable named delay is incremented and then checked against the condition. This
repetition pauses the program before executing the next instruction.

Example: You can use for loop without any start value.
s=0;
for( ; s<=10 ; s++)
printf(“%d\n”,s);

s variable set to 0 before the looping statement, there’s no need to initialize it.

Program: Program to generate N natural numbers using for loop.

#include <stdio.h>
main()
{
int i,n;
printf("Enter the upper limit");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d\t",i);
}
Program: Program to calculate and print the sums of even and odd integers of
the first N natural numbers.
#include <stdio.h>
main()
{
int i,n, sum_even, sum_odd;
printf("Enter the upper limit");
scanf("%d",&n);
sum_even=0;
sum_odd =0;
for(i=1;i<=n;i++)
if( i % 2==0)
sum_even=sum_even + i;
else
sum_odd =sum_odd +i;
printf("\nThe sum of even integers=%d",sum_even);
printf("\nThe sumof odd integers=%d",sum_odd);
}

For loop variations


i. Nested loops : If one looping statement is enclosed in another looping statement
then such a sequence of statements is called as nested loops. If one for
statement is performed within another, the sequence is called as nested-for.
Whenever nested loops are used the inner loop should be completely enclosed
by the outer loop i.e., overlapping of loops is not possible. Also the inside loop is
completely repeated for each repetition of the outside loop.

Example: for(row = 1; row <=10; row++) /* outer loop */


for(col = 1; col <=row; col++) /* inner loop */
printf(“%d”,i);

Program: Program to generate the following output.

*
**
***
****
#include <stdio.h>
main()
{
int row,col;
for(row=1;row<=4;row++) /* outerloop */
{
for(col=1;col<=row;col++) /* innerloop */
printf(“*”);
printf(“\n”);
}
}
ii Infinite loops : If we do not use any expressions in a for statement then the loop
will run for an infinite amount of time. Such loops, which do not terminate are called as
infinite loops.

Example: for( ; ;)
printf(“ C programming”);

The loop will print the statement “ C programming “ forever (infinite loop).

Program: Program to generate the following output.

1
2 3
4 5 6
7 8 9 10
#include <stdio.h>
main()
{
int row,col, k=1;
for(row =1;row<=4;row++) /* outerloop */

{
for(col=1;col<=row;col++) /* innerloop */
printf(“%d\t”,k++);
printf(“\n”);
}
}
Program: Program to generate the following output.

1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
#include <stdio.h>
main()
{
int row,col;
long num=12345;
for(row = 1; row <=5 ; row++)
{
printf("%ld",num);
num=(num%10)*10000+ (num/10);
printf(“\n”);
}
}
Comma operator
By using the comma operator in an expression of a loop, we will be able to
combine two statements that are in the body of the loop into a single expression, which
then becomes the action of the loop. This leaves the body of the loop empty, allowing
us to use null statement as its body.

COMPARISON OF THE THREE LOOPING STATEMENTS


C has three types of looping structures(while, do-while and for). These loops can
be used in almost all situations. There are some situations where one loop fits better
than the other.
The for loop is appropriate when you know in advance how many times the loop
will be executed. The other two loops while and do-while loops are more suitable in the
situations where it is not known before-hand when the loop will terminate. The while
should be preferred when you may not want to execute the loop body even once, and
the do-while loop should be preferred when you are sure to execute the loop body at
least once.

while statement do-while statement for statement


i = 1; i = 1;
for (i = 1; i < = 10; i++)
while ( i < = 10 ) do
printf (“%d \n “, i);
{ {
printf (“%d \n “, i); printf (“%d \n “, i);
i++; i++;
} } while ( i < = 10 );
JUMP STATEMENTS
The jump statements unconditionally transfer program control within a
function . C has four statements that perform an unconditional branching : goto, return,
break, and continue. We can use goto and return statements any where in the program
whereas break and continue are used inside the loops. In addition to the above four, C
provides a standard library function exit( ) that helps you break out of a program.

break statement
The break statement is used to terminate loops. It can be used within a while,
do-while or for statement. When break is encountered inside any loop, control
automatically passes to the first statement after the loop. This provides a convenient
way to terminate the loop if an error or other irregular condition is encountered. The
break statement is simply written as :

break;

Program: To test whether a number is prime or not.


In the above program the moment num % i turns out to be zero the message
“Number is not a Prime” is printed and the control breaks out of the while loop.

continue statement
In some programming situations we want to take the control back to the
beginning of the loop, bypassing the statements inside the loop, which have not yet been
executed. When the keyword continue is encountered inside any loop, control
automatically passes to the beginning of the loop. The continue statement is simply
written as:

continue;

Program: Program to display all numbers from 1 to n, which are not divisible by 5.

exit() function
exit() is a standard library function that comes ready-made with the C compiler.
Its purpose is to terminate the execution of the program. break statement terminates
the execution of loop in which it is written, where as exit() terminates the execution of
the program itself. Let us consider the following program:
The above program accepts a number and tests whether it is prime or not. If the number is
divisible by any number from 2 to half of the number, the program displays a message that
the "number is not a prime" and exits from the program by exit() function. The exit() has
been defined under the header file stdlib.h which must be included in a program that uses
exit() function.

You might also like