0% found this document useful (0 votes)
2 views

Module 2 C programming

This document provides an introduction to decision control and looping statements in C programming, covering branching (if, if-else, nested if-else, switch) and looping constructs (for, while, do-while). It explains the syntax and usage of these statements with examples, detailing how to implement conditional logic and control flow in programs. Additionally, it discusses unconditional branch statements like break, continue, and goto.

Uploaded by

cojogan898
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)
2 views

Module 2 C programming

This document provides an introduction to decision control and looping statements in C programming, covering branching (if, if-else, nested if-else, switch) and looping constructs (for, while, do-while). It explains the syntax and usage of these statements with examples, detailing how to implement conditional logic and control flow in programs. Additionally, it discusses unconditional branch statements like break, continue, and goto.

Uploaded by

cojogan898
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/ 34

Introduction to C Programming DSCE

Module 2
Decision control and Looping statements
BRANCHING AND LOOPING: Two way selection (if, if-else, nested if-else, cascaded if-else),
switch statement, ternary operator? Go to, Loops (For, do-while, while) in C, break and continue,
programming examples and exercises

BRANCHING AND LOOPING:

What is branching and looping?


In programming we have to perform (Execute) some statements when condition met or may need to
skip some statements. These statements are called as Branch statements.
Branching is deciding what actions to take and looping is deciding how many times to take a certain
action.

C provides two styles of flow control:


 Branching
 Looping

Branch statements are classified into two ways,

1. Conditional Branch statements.


2. Unconditional Branch statements.

1. Conditional Branch statements.

 Simple if (single selection)


 if-else (two way selection)
 nested if
 else-if ladder
 switch

The if, if...else and nested if...else statement are used to make one-time decisions in C Programming,
that is, to execute some codes and ignore some codes depending upon the test expression.

1. simple if

Dr. Shobha N, Assistant Prof., CSD 1


Introduction to C Programming DSCE

This is the simplest form of the conditional branching statements. Here condition is evaluated, if
it evaluate true a statement or group of statement is executed.

Syntax:
if (expression)
{
Statement to be executed if expression is true ;
}
- If the expression is evaluated and found to be true, statements inside the body of if is executed
but if expression is false, statements inside body of if is ignored.
- Usage of braces is optional, when only one statement is there.
- Multiple statements should be written in pair of braces { }.
- No semicolon is required after if.

‘C’ programming using simple if statement:

1. ‘C’ program to check given number is even or not.


#include<stdio.h>
void main()

Dr. Shobha N, Assistant Prof., CSD 2


Introduction to C Programming DSCE

{
int n;
printf (“Enter the value of n”);
scanf (“% d”,&n);
if(n% 2==0) / / checking w hether number even or not

printf(“number is =% d”,n);

2. Write a C program to print the number entered by user is negative.

#include<stdio.h>
void main()
{
int n;

P rintf(“Enter the number to check”);


Scanf(“%d”,&n);
if (n<0) / / checking w hether number is less t han 0 or not
{
printf(“the number is=% d”,n);
}

P rintf(“This will execute always”);


}

Output 1:- When user enters -2 then, the test expression (num<0) becomes true.
Hence, Number = -2 is displayed in the screen.
Output 2 :- When user enters 5 then, the test expression (num<0) becomes false and
Print This will execute always.
Note: Above program is same as to check whether given no is positive or not.

Dr. Shobha N, Assistant Prof., CSD 3


Introduction to C Programming DSCE

2. if-else

The if...else statement is used if the programmer wants to execute some statements when the test
expression is true and execute some other statement/s if the test expression is false.
It is two way selection statements
If multiple statements have to be executed, it has to be written into pair of braces. If only one statement
has to be executed then use of pair of braces is optional.

Syntax:

if (test expression)
{
Statements will execute if test expression is true;
}
else
{
Statements will execute if test expression is false;
}

‘C’ programming using simple if-else statement:

1. WAC program to check whether user is eligible for voting or not

# include <stdio.h>

Dr. Shobha N, Assistant Prof., CSD 4


Introduction to C Programming DSCE

void main()
{
int age;
printf("Enter the person age");
scanf("%d",&age);

if(age>=18)
{

printf("person is eligible to vote");

else
printf("person is not eligible to vote");

2. Write a C program to check whether a number entered by user is even or odd

#include<stdio.h>
void main()
{
int n;
printf(“Enter the value of n”);
scanf(“%d”,&n);

if(n% 2==0) / / checking w hether number even or not


{
printf(“given number is even number);
}
else
{
printf(“given number is odd number);

}
}
3. Program to accept a number and check the given number is Armstrong or not.
# include <stdio.h>
void main( )
{
int n, a, b, c, d;
printf ("Enter a Three Digit Number: ");

Dr. Shobha N, Assistant Prof., CSD 5


Introduction to C Programming DSCE

scanf ("%d", &n);


a=n/100; 1 153 = 13+53+33 =1+125+27= 153 153/100
123 =1+8+27=36

b=((n/10)%10); 5

c=n%10; 3

d=a*a*a+b*b*b+c*c*c;

if (n==d)
printf ("The Given Number is Armstrong number");

else
printf ("The Given Number is Not Armstrong number");

4. WAC program to find out biggest of two numbers.


5. Write above program with simple if.
3. Nested if

- Nested if means one if statement contains another if statements.


- Nested if statement also called as multi-way decision.
- The control of program moves into inner if statement when the outer if statement evaluated true.
Syntax:-

if (Expression 1)
{
if (expression 2)
{
Block- A;
else
Block –B;
}
}
else
{
Block-c;
}

Dr. Shobha N, Assistant Prof., CSD 6


Introduction to C Programming DSCE

Flowchart for nested-if :-


True

Exp1 False
Exp2

False True

Block-B
Block-A

Block-C

Program to find greatest of three numbers using if else

#include <stdio.h>

int main()
{

int a, b, c, ;

printf("\n enter the value of a b c");


scanf("%d%d%d", &a, &b, &c);
if(a>b)
{
if(a>c)

printf("\n a is greater");
else
printf("\n c is geater");

else
{

Dr. Shobha N, Assistant Prof., CSD 7


Introduction to C Programming DSCE

if(c>b)
printf("\n c is greater");
else
printf("\n b is greater");

}
return 0;
}

‘C’ programming using nested- if statement:


1. WAC program to find greatest number among 3 numbers.

4. Else- if ladder
The nested if...else statement is used when program requires more than one test expression.

Syntax :-
if (test expression1)
{
Statements will execute if test expression1 is true;
}
else if(test expression2)
{
Statements will execute if test expression1 is false and expression2 is true;
}

else if (test expression3)


{
Statements to be executed if test expression1 and expression2 are false and test expression 3 is true;
}
….
….
else

Dr. Shobha N, Assistant Prof., CSD 8


Introduction to C Programming DSCE

{
Statements to be executed if all conditions are false;
}

How ne sted if...else works?

Nested if()...else statements take more execution time compared to an if()...else ladder because the
nested if()...else statements check all the inner conditional statements once the outer
conditional if() statement is satisfied,
whereas the if()..else ladder will stop condition testing once any of the if() or the else if() conditional
statements are true.

‘C’ programming using else- if ladder statement:

1. WAC program to check grade.

#include<stdio.h>
void main( )
{
int marks;

printf(“Enter the marks ”);


scanf(“%d”, &marks);

if(marks<=34)
printf(“Grade Fail”);
else if(marks<=59)
printf(“Grade Second”);
else if(marks<=69)
printf(“Grade First”);
else if(marks<=79)
printf(“Grade Distinction”);
else
printf(“Grade out standing”);

Dr. Shobha N, Assistant Prof., CSD 9


Introduction to C Programming DSCE

int main()
{

int marks;

printf("\n enter the marks");


scanf("%d", &marks);

if(marks<=34)
printf("Grade Fail");
else if(marks<=59)
printf("Grade Second");
else if(marks<=69)
printf("Grade First");
else if(marks<=79)
printf("Grade Distinction");
else
printf("Outstanding");

return 0;
}

2. WAC program to display the output stop, ready, or go based on traffic signal input given
by user.

#include<stdio.h>
void main( )
{
char s;
printf ("enter the light colour");
scanf("%c",&s);

if (s=='r')
printf("Red-stop at signal");
else if (s=='g')
printf("Green-go");
else if(s=='y')
printf("Yellow- ready to move");
}

Dr. Shobha N, Assistant Prof., CSD 10


Introduction to C Programming DSCE

3. Write a C program to relate two integers entered by user using = or > or < sign.

#include<stdio.h>
Void main()
{
int n1 ,n2 ;
printf(“enter two numbers to check”);
scanf(%d%d”, n1,n2)
if (n1== n2)
printf(“entered number are equal”);
else
if (n1>n2)
printf(“n1 is greater number”);
else
printf(“n2 is greater number”);
}

5. Switch

A switch statement is a conditional statement, which tests a value between many different
values. (When decision has to made between many alternatives)

It should begin with switch keyword followed by value expression in parenthesis.

Value expression can be integer value or character.

Syntax:-

switch( expression )
{
case value1: statements1;
break;
case value 2: statements2;
break;
case value 3: statements3;
break;
……
……
[default : statements4;]
}

Dr. Shobha N, Assistant Prof., CSD 11


Introduction to C Programming DSCE

‘C’ programming using switch statement:

1. WCP to display the output stop, ready, go.


#include<stdio.h>
void main( )
{
char s;
printf (“enter the colour”);
Scanf(“%c”,&s);

switch (s)
{
case ‘r’ : printf(“stop at signal”);
break;
case ‘y’ : printf(“ready to go”);
break;
case ‘g’ : printf(“go”);
break;
default : printf(“error in giving input”);
break;
}

Dr. Shobha N, Assistant Prof., CSD 12


Introduction to C Programming DSCE

2. Program to accept any single digit number and print it in words .


# include <stdio.h>
Void main( )
{

int n;
clrscr( );
printf(“enter a number :”);
scanf(“%d “,&n);
switch(n)
{
case 0: printf(“ZERO”);
break;
case 1: printf(“ONE”);
break;
case 2: printf(“TWO”);
break;
case 3: printf(“THREE”);
break;
case 4: printf(“FOUR”);
break;
case 5: printf(“FIVE”);
break;
case 6: printf(“SIX”);
break;
case 7: printf(“SEVEN”);
break;
case 8: printf(“EIGHT”);
break;
case 9: printf(“NINE”);
break;

default:
printf(“please enter the number between 0 and 9”);
}
}

# include <stdio.h>
void main( )
{

int n;

Dr. Shobha N, Assistant Prof., CSD 13


Introduction to C Programming DSCE

printf("enter a number :");


scanf("%d",&n);
switch(n)
{
case 0: printf("Sunday");
break;
case 1: printf("Monday");
break;
case 2: printf("Wednesday");
break;
case 3: printf("Thursday");
break;
case 4: printf("Friday");
break;
case 5: printf("Saturday");
break;
default:
printf("please enter the number between 0 and 5");
}
}

#include<stdio.h>
void main()
{
char operator;
float num1,num2,result,div;
printf("Simulation of a Simple Calculator\n");
printf("*********************************\n");
printf("Enter two numbers and operator[+,-,*,/] \n");
scanf("%f %f %c",&num1,&num2,&operator);
switch(operator)
{
case '+': result = num1 + num2;
printf("\n %f %c %f = %f\n", num1, operator, num2, result);
break;
case '-': result = num1 - num2;
printf("\n %f %c %f = %f\n", num1, operator, num2, result);
break;
case '*': result = num1 * num2;
printf("\n %f %c %f = %f\n", num1, operator, num2, result);
break;
case '/': if(num2!=0)
{
result = num1 / num2;

Dr. Shobha N, Assistant Prof., CSD 14


Introduction to C Programming DSCE

printf("\n %f %c %f = %f\n", num1, operator, num2, result);


}
else
{
printf("Divide by Zero Error\n");
}
break;
default : printf("Error in operation\n");
}
}
3. WAC program to get the number through keyboard and print whether it is divisible by
3 and 5 both. Hint: ( if (n%3==0 &&n%5==0)

Unconditional branch statements


An unconditional branch statement is a construct which alter the sequential control flow without
checking any condition.
1. break
2. continue
3. goto

1. break
1. used to break any type of loop as well as switch statements
2. breaking loop means terminating loops
3. break statements will be the last statement.
4. In break, control comes out of loop and statement following loop will be executed
5. If break appears in the inner loop of nested loop, control comes out of inner loop only, not
from outer loop

Example:
#include<stdio.h>
void main()
{
int i=1;

Dr. Shobha N, Assistant Prof., CSD 15


Introduction to C Programming DSCE

while(i<=8)
{
printf("%d\t", i);
if(i==7)
break;
i++;
}
}
2. Continue

Continue statement break the current iteration.

int main()
{
int i;

for(i=1;i<=5;i++)
{
if(i==2) continue;
printf("%d\t",i);
}
return 0;
}

3. goto

it transfer the control to the specified statement in a program.


Syntax:
goto label_name
_____
_____

label_name: statements;

disadvantage
Using goto and writing program is an unstructured programming.

Dr. Shobha N, Assistant Prof., CSD 16


Introduction to C Programming DSCE

It is difficult to debug the program.

int main()
{
int i=0, n, sum=0;

printf("enter the number of terms");


scanf("%d", &n);

top: sum=sum+i;
i=i+1;
if(i<=n)goto top;

printf("sum of series=%d", sum);

return 0;
}

1. Looping (Repetition)

Looping means Execution of same set of instruction for given number of times OR until a specified
result obtained.
Q What is pre-test loop?
- If the condition is checked before each iteration of loop, such loops called as pre-test loop.
- Conditional expression is evaluated true or false at the beginning of loop.
Since in pre-test loop, condition is checked at the top of loop so called as top-testing or entry
controlled loop.
Ex: for, while loop.

Body of loop

Q What is post-test loop?


- If the condition is checked after each iteration of loop, such loops called as post-test loop.

Dr. Shobha N, Assistant Prof., CSD 17


Introduction to C Programming DSCE

- First body of loop is executed then expression evaluated true or false.


Since condition is checked at the bottom of loop it is also called as bottom-testing or Exit controlled
loop. Ex. Do-while loop
- In post test, body of test condition is executed at least once.(one OR more times)

Body of loop

Loops in ‘c ‘ Language:-
1. While loop :-
The while loop checks whether the test expression is true or not. If it is true, code inside
the body of while loop is executed, that is, code inside the braces { } are executed.

Then again the test expression is checked whether test expression is true or not. This
process continues until the test expression becomes false

Syntax:-

while ( expression )
{
Single statement
or
Block of statements;
}

Flowchart:

Dr. Shobha N, Assistant Prof., CSD 18


Introduction to C Programming DSCE

BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{

statements; //body of loop .

} statements; // body of loop.

} while( Condition );

Dr. Shobha N, Assistant Prof., CSD 19


Introduction to C Programming DSCE

BASIS FOR
WHILE DO-WHILE
COMPARISON

Controlling In 'while' loop the controlling In 'do-while' loop the

Condition condition appears at the start controlling condition appears at

of the loop. the end of the loop.

Iterations The iterations do not occur if, The iteration occurs at least

the condition at the first once even if the condition is

iteration, appears false. false at the first iteration.

Alternate name Entry-controlled loop Exit-controlled loop

Semi-colon Not used Used at the end of the loop

‘C’ programming using while-loop :


1. ‘C’ Program to print natural number from 1 to 10 by

# include <stdio.h>
Void main( ) Output:
{ 1 2 3 4 5 6 7 8 9 10
int i=1;
while( i<=10)
{
printf(“%d\n”,i);
i=i+1;
}

Dr. Shobha N, Assistant Prof., CSD 20


Introduction to C Programming DSCE

2. ‘c’ program to print square of number .


#include<stdio.h>
Void main( )
{
int i=1 , j=1;
while (i <=5)
{
j=i*i;
Printf(“%d\t %d”, i ,j);
i=i+1;
}
}

Output:
1 1
2 4
3 9
4 16
5 25

3. ‘C’ Program to print number from 1 to 10 in reverse order.


# include <stdio.h>
Void main( ) Output:
{ 10 9 8 7 6 5 4 3 2 1
int n =10;
while ( n>=0)
{
printf(“%d \n”,n);
n--;
}

4. WAC program to find gcd and lcm of given integers.

#include<stdio.h>
void main()
{
int a,b,m,n;
Output:
Input - m=4 n=2
Gcd=

Dr. Shobha N, Assistant Prof., CSD 21


Introduction to C Programming DSCE

int lcm,gcd,r; Lcm=


clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&m,&n);
a=m;
b=n;
while(n!=0)
{
r=m%n;
m=n;
n=r;
}
gcd=m;
lcm=(a*b)/gcd;
printf("GCD =%d“, gcd);
printf("LCM =%d” , lcm);
}

5. Write a C program to find the factorial of a numbe r, whe re the number is


e ntered by user. (Hints: factorial of n = 1 *2*3*...*n

M e thod-1 M e thod-2
#include<stdio.h> #include<stdio.h>
Void main( ) Void main( )
{ {
int n, fact=1 ; int n ,temp , fact=1;
printf(“enter the number”); printf(“enter the number”);
scanf(“%d”,&n); scanf(“%d”,&n);
while(n>0) temp=n;
{ while (n>0)
fact=fact*n; {
--n; fact=fact*temp;
} temp=temp-1;
P rintf(“factorial=%d”,fact); }
} printf(“% d\n”, fact);
}
Output:
Ente r number=5
Factorial=120
6. WAC program that will generate and print first n Fibonacci numbers.
#include<stdio.h>

Dr. Shobha N, Assistant Prof., CSD 22


Introduction to C Programming DSCE

Void main( )
{
int i=0, j=0, n , sum=1;
printf(“enter the limit of series”);
scanf(“%d”, &n);
while(sum<n)
{
Printf(“%d”, sum);
i=j;
j=sum;
sum=i+j;
}
Printf(“sum of series=%d”, sum);
}

Output: Limit of series n=5 --- 1 1 2 3 5


2. Do -While loop :-

Syntax:

do
{
statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.

Dr. Shobha N, Assistant Prof., CSD 23


Introduction to C Programming DSCE

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop
in C programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

do ... while is just like a while loop except that the test condition is checked at the end of the loop
rather than the start. This has the effect that the content of the loop are always executed at least
once.

‘C’ programming using Do-While loop :

1. ‘c’ program to print numbers from 10 to 19 using do-while loop

#include <stdio.h> Output:


void main () value of a: 10
{ value of a: 11
int a = 10; // local variable definition value of a: 12
value of a: 13
do value of a: 14
{ value of a: 15
value of a: 16
printf("value of a: %d\n", a);
value of a: 17
a = a + 1; value of a: 18
} while( a < 20 ); value of a: 19
}

Dr. Shobha N, Assistant Prof., CSD 24


Introduction to C Programming DSCE

2. ‘c’ program to print number using conditional statement.

#include <stdio.h>

Void main() Value of i is 1


Value of i is 2
{ Value of i is 3
int i=1; Value of i is 4
do
{
printf("Value of i is %d\n",i);
i++;

} while (i<=4 && i>=2);

3. ‘c’ program to print number in reverse order.

#include <stdio.h>

main()
{
int i = 10;
do
{
printf("Hello %d\n", i );
i = i -1;

}while ( i > 0 );
}

This will produce following output:

Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1

Dr. Shobha N, Assistant Prof., CSD 25


Introduction to C Programming DSCE

You can make use of break to come out of do...while loop at any time.

#include <stdio.h>

main()
{
int i = 10;

do{
printf("Hello %d\n", i );
i = i -1;
if( i == 6 )
{
break;
}
}while ( i > 0 );
}

This will produce following output:

Hello 10
Hello 9
Hello 8
Hello 7
Hello 6

Ex ample 1 :

int main()
{
int j=0
do
{
printf("Value of variable j is: %d", j);
j++;
} while (j<=5);

Dr. Shobha N, Assistant Prof., CSD 26


Introduction to C Programming DSCE

}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
Value of variable j is: 4
Value of variable j is: 5

Ex ample 2 :

#include <stdio.h>
main()
{
int j = -5; // initialization
do
{
printf("%d\n", j);
j = j + 1;
}
while(j <= 0); // condition

4. Write a C program to add all the numbers entered by a us e r until user e nters
0.
#include<stdio.h>
Void main()
{
int sum=0,num;
Output :-
do Enter number 3
{ Enter number -2
P rintf(“enter the number”); Enter number 0
scanf(“%d”,&num); Sum=1
sum=sum+num;
}
While (num!=0);

Dr. Shobha N, Assistant Prof., CSD 27


Introduction to C Programming DSCE

P rintf(“sum=%d”,sum);
}
In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal
to 0, the body of do...while loop is again exec uted until num equals to zero.

BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{

statements; //body of loop .

} statements; // body of loop.

} while( Condition );

Controlling In 'while' loop the controlling In 'do-while' loop the

Condition condition appears at the start controlling condition appears at

of the loop. the end of the loop.

Iterations The iterations do not occur if, The iteration occurs at least

the condition at the first once even if the condition is

iteration, appears false. false at the first iteration.

Alternate name Entry-controlled loop Exit-controlled loop

Dr. Shobha N, Assistant Prof., CSD 28


Introduction to C Programming DSCE

BASIS FOR
WHILE DO-WHILE
COMPARISON

Semi-colon Not used Used at the end of the loop

3. The for loop

Syntax:-
for ( initialization ; condition test ; increment or decrement)
{
statements needs to be repeated;

Dr. Shobha N, Assistant Prof., CSD 29


Introduction to C Programming DSCE

How for loop works in C programming?


The initialization statement is executed only once at the beginning of the for loop. Then
the condition test is checked by the program. if test condition is true then the state ments
inside body of fo r loop is executed. Afterwards increment /decrement will be done. If the
test expression is false, for loop is terminated.

Example 1 :
#include<stdio.h>
Void main()
{
int i; Output:
for (i=1; i<=3; i++) hello, World
hello, World
{
hello, World
printf("hello, World\n");
}
}

Explanation:

The for loop in C is executed as follows:

1. The initial counter value is initialized. This initialization is done only once for the entire
for loop.
2. After the initialization, test condition is checked. Test condition can be any relational or
logical expression. If the test condition is satisfied i.e. true then the block of statement inside
the for loop is executed
3. After the execution of the block of statement, increment/decrement of the counter is done.
After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till
the test condition returns false.

Dr. Shobha N, Assistant Prof., CSD 30


Introduction to C Programming DSCE

Example 2 :

#include<stdio.h>
void main() Output:
{ 1 1 This will be repeated 5 times
int i; 2 2 This will be repeated 5 times
for(i=1; i<=5;i++) 3 3 This will be repeated 5 times
{
4 4 This will be repeated 5 times
printf("%d This will be repeated 5 times\n", i);
5 5 This will be repeated 5 times
} 6 End of the program
printf("End of the program");
}

In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is
less than or equal to 5.

Example 3 :

Note : It is necessary to write the semicolon in for loop as shown in the below:

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

Consider, case 1:

1 for(i=0; i<10;)
2{
3 printf(“Interment/decrement not used above”)
4 i=i+1;
5}

In the above program, Increment is done within the body of for loop. Still semicolon is
necessary after the test condition.

Consider, case 2 :

1 i=0;
2 for(; i<10; i++)
3{
4 printf(“Interment/decrement not used above”)

Dr. Shobha N, Assistant Prof., CSD 31


Introduction to C Programming DSCE

5}

In the above program, Initialization is done before the start of for loop. Still semicolon is necessary
before the test condition.
Example 4 :

#include<stdio.h>
Void main()
{
const int max=5;
int i ;
for(i=0 ;i<max ;i++)
printf(%d”,i)
}

Output:- 0 1 2 3 4

Example 5 :

#include<stdio.h>
void main()
{
int i;
for(i=0; i<10 ; i++)
{
printf("hello\n");
printf("world \n");
}
}

Example 5 :

#include <stdio.h>
int main() Output:
{
int i; 0123456789
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

Dr. Shobha N, Assistant Prof., CSD 32


Introduction to C Programming DSCE

‘C’ programming using for loop :

1. Program to print ODD numbers from 1 to 10


# include <stdio.h>
void main( )
{
int i;
for (i=1; i<=10; i+=2)

printf(“%d\n”,i);
}

2. Program to print natural numbers from 1 to 10 in Reverse


# include <stdio.h>
Void main( )
{
int i;
for (i=10; i>=1; i--)
printf(“%d\n”,i);
}

3. Program to accept a number and print mathematical table of the given no.
# include <stdio.h>
void main( )
{
int i,t;
printf("which table u want:");
scanf("%d",&t);
for (i=1; i<=10; i++)
printf("\n%d*%d=%d", t ,i , i*t);
}
4. Write a program to find the sum of first n natural numbers where n is entered by
user. Note: 1,2,3... are called natural numbers.
#include<stdio.h>
void main()
{
int n, i,sum=0;
printf("enter value of n");
scanf("%d",&n);
for(i=1; i<=n ; i++)
{
sum=sum+i;

Dr. Shobha N, Assistant Prof., CSD 33


Introduction to C Programming DSCE

}
printf("summation=%d",sum);
}O u tpu t:
Write a C program to check whether the number n is prime or not prime using for loop.

#include <stdio.h>

int main()
{

int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

for (i = 2; i <= n / 2; ++i) {

if (n % i == 0) {
flag = 1;
break;
}
}

if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);

Dr. Shobha N, Assistant Prof., CSD 34

You might also like