0% found this document useful (0 votes)
4 views15 pages

Unit-2 Intro to Prog (AK23)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

UNIT 2

Control Structures
Simple sequential programs, Conditional Statements (if, if-else, Switch). Loops (for, while, do-while), Break
and Continue.

Simple Sequential Programs: .


Sequence of statements are written in order to accomplish a specific activity. So statements
are executed in the order they are specified in the program. This way of executing statements
sequentially is known as Sequential control statements.
There is an advantage that is no separate control statements are needed in order to execute
the statements one after the other.
Disadvantage is that there is no way to change the sequence. The solution for this is
branching and loop control structures.

Example: / * Program to illustrate sequential flow of execution */


#include <stdio.h>
#include <conio.h>
int main()
{
float farenhite, celsius;

printf("Enter degree in farenhite\n");


scanf("%f", &farenhite);

celsius=(float)5/9*(farenhite-32);

printf("result=%f\n", celsius);
getch();
return 0;
}
Explanation: Execution begins from the main. We enter a farenhite degree value. Control
moves to the formula which will convert farenhite into celsius and then equivalent celsius value is
output.
Some more Examples:
/* Prog. to print Multiplication Table */ /* Prog. to do arithmetic operations */ /* Prog. to scan diff. i/p and print o/p */
#include <stdio.h> #include<stdio.h> #include <stdio.h>
int main() int main() int main()
{ { {
int n; int a,b,c; int num;
printf("Which Mul. Table to print: “); printf(“enter a,b values\n”); char ch;
scanf("%d", &n); scanf(“%d%d”,&a,&b); float f;
printf(“ 1 * %d = %d \n”, n, 1*n); c=a+b; printf("Enter the integer: ");
printf(“ 2 * %d = %d \n”, n, 2*n); printf(“sum=%d\n”,c); scanf("%d", &num);
printf(“ 3 * %d = %d \n”, n, 3*n); c=a-b; printf("\nEntered integer is: %d", num);
printf(“ 4 * %d = %d \n”, n, 4*n); printf(“sub=%d\n”,c); printf("\n\nEnter the float: ");
printf(“ 5 * %d = %d \n”, n, 5*n); c=a*b; scanf("%f", &f);
return(0); printf(“mul=%d\n”,c); printf("\nEntered float is: %f", f);
} c=a/b; printf("\n\nEnter the Character: ");
printf(“div=%d\n”,c); scanf("%c", &ch);
c=a%b; printf("\nEntered integer is: %c", ch);
printf(“mod=%d\n”,c); return 0;
return 0; }
}

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
Conditional Statements (if, if-else, switch): .

Selection Control Statements also called as Decision control statements and Conditional
Statements allow the computer to take decision. And force to work under given condition. A Selection
Control Statement gives the control to the computer for taking the decisions.

Four selection control instruction which are implemented in C are following:

a) if statement
b) if-else statement
c) Nested if-else statement
d) if-else Ladder
e) switch

a) Simple if statement:

The simple if (or) if only statement takes care of true condition only. It has only one block.

Syntax:
if (condition is true)
{

block of executable Statements;

Example:

#include<stdio.h>
#include<conio.h>
int main( )
{
int m,n;
clrscr();
printf(“Enter any two number: ”);
scanf(“%d %d”, &m, &n);

if( m-n == 0 )
{
printf(“ The entered numbers are equal. \n”);
}

getch();
return 0;
}

Output:
Enter any two number: 50 50
The entered numbers are equal.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 2
b) if-else statement:

The if-else statement is an extension of the if statement. The if-else statement takes care of
true as well as false conditions. It has two blocks.

• One block is for if and it is executed when the condition is true.


• The other block is of else and it is executed when the condition is false.
• The else statement cannot be used without if.
• No multiple else statements are allowed without one if.

Syntax:
if(expression is true)
{
Statement-A;
}
else
{
Statement-B;
}

Example:

#include<stdio.h>
#include<conio.h>
int main( )
{
int age;
clrscr( );
printf(“Enter candidate age: \n”);
scanf(“%d”, &age);

if( age >= 18 )


printf(“ Eligible to cast vote \n“);
else
printf(“ Not Eligible to cast vote ”\n);

getch();
return 0;
}

Output:
Enter candidate age: 20
Eligible to cast vote

Enter candidate age: 17


Not Eligible to cast vote

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
c) Nested if-else statement:

The numbers of Logical conditions are checked for executing various statements by using
nested if-else statements.

Syntax: if(condition)
{
if(condition)
{
Statement-A;
}
else
{
Statement-B;
}
}
else
{
Statement-C;
}

… … …
Statement-D;
… … …

Example: Write a program to find largest number among three numbers using nested if.

#include<stdio.h>
int main()
{
int x, y, z;
printf("\n Enter the values of x, y, z: ");
scanf("%d %d %d", &x, &y, &z);
printf("\n Largest among three numbers is: ");
if( x > y )
{
if( x > z )
printf(" x = %d \n", x);
else
printf(" z = %d \n", z);
}
else
{
if( z > y )
printf(" z = %d \n", z);
else
printf(" y = %d \n", y);
}
return 0;
}

Output:
Enter three numbers x, y, z: 56 89 78
Largest out of three numbers is: y = 89

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
d) if-else Ladder statement:
There is another way of putting if’s together when multipath decisions are involved to solve
the given task. A multipath decision is a chain of if’s in which the statement associated with each
else is an if.

Syntax:

if(condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
… … …
… … …
else if(condition-n)
Statement-n;
else
Default statement;
… … …
Statement-x;
… … …

Example: Write a C program to find the average of six subjects and display the results as follows,

AVERAGE RESULT .
< 40 FAIL
>=40 & <50 THIRD CLASS
>=50 & <60 SECOND CLASS
>=60 & <75 FIRST CLASS
>=75 & <100 DISTINCTION

#include<stdio.h>
int main()
{
int sum=0, tel, eng, math, hin, pys, chem;
float avg;
printf("\n: Enter marks :\n Telugu: \nEnglish: \nMaths: \nHindi: \nPhysics: \nChemistry: \n\n");
scanf("%d%d%d%d%d%d", &tel, &eng, &math, &hin, &pys, &chem);
sum=tel+eng+math+hin+pys+chem;
avg=sum/6;
printf("Total : %d \n Average: %.2f", sum, avg);

if( tel<40 || eng<40 || math<40 || hin<40 || pys<40 || chem<40 )


{ printf("\n Result: Fail"); }
else if( avg>=40 && avg<50 )
{ printf("\n Result: Third Class"); }
else if( avg>=50 && avg<60 )
{ printf("\nResult: Second Class"); }
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
else if( avg>=60 && avg<75 )
{ printf("\n Result: First Class"); }
else if( avg>=75 && avg<100 )
{ printf("\nResult: Distinction"); }

return(0);
}

Output:
: Enter marks :
Telugu: 96
English: 86
Maths: 77
Hindi: 66
Physics: 65
Chemistry: 88

Total: 478
Average: 79.00

Result: Distinction

e) switch statement (or) Case control (or) switch()…case:

The Case control statements allow the computer to take decision as to be which statements
are to be executed next.

• It is a multi-way decision construct facilitate number of alternatives has multi way decision
statement known as “switch statement”.
• First, in the option parentheses - give the condition. This condition checks to match, one by
one with case constant.
• If value match then its statement will be executed.
• Otherwise, the default statement will appear.
• Every case statement terminates with ‟ : ”

Syntax:
switch(option)
{
case option_1 : statements;
break;

case option_2 : statements;


break;
… … …
… … …

case option_n : statements n;


break;

default : statements;
break;
}

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
Example 1:

1. Write a program to convert years into Minutes, Hours, Days, Months, and Seconds using
switch statements.

#include<stdio.h> 2. Write a program to convert Decimal into Words.


int main()
{ #include<stdio.h>
long int ch, min, hrs, ds, mon, yrs, se; int main()
{
int n;
printf("\n [1] MINUTES"); printf("\n: Enter a Digit 10 – 15: ");
printf("\n [2] HOURS"); scanf("%d”, &n);
printf("\n [3] DAYS"); switch(n)
printf("\n [4] MONTHS"); {
case 10 : printf(“ Ten ”);
printf("\n [5] SECONDS"); break;
printf("\n [0] EXIT"); case 11 : printf(“ Eleven ”);
break;
printf("\n Enter your choice:"); case 12 : printf(“ Twelve ”);
scanf("%ld", &ch); break;
case 13 : printf(“ Thirteen ”);
break;
if( ch>0 && ch<6 ) case 14 : printf(“ Fourteen ”);
{ break;
printf(" Enter how many years: "); case 15 : printf(“ Fifteen ”);
scanf("%ld", &yrs); break;
default : printf(“Invalid. Enter 10-15 only.\n”);
} break;
mon=yrs*12; }
ds=mon*30; return 0;
ds=ds+yrs*5; }
hrs=ds*24;
Output: Enter a Digit 10 – 15: 14
min=hrs*60; Fourteen
se=min*60;

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 7
switch(ch) 2. Write a program to print ‘a’ as “A is for apple”,
{ ….. …..
case 1 : printf("\n MINUTES: %ld", min);
break; #include<stdio.h>
int main()
case 2 : printf("\n Hours: %ld", hrs); {
break; char ch;
case 3 : printf("\n Days: %ld", ds); printf("\n: Enter a Char a – e: ");
break; scanf("%c”, &ch);
case 4 : printf("\n Months: %ld", mon); switch(ch)
{
break; case ‘a’ : printf(“ A is for Apple. ”);
case 5 : printf("\n seconds: %ld", se); break;
break; case ‘b’ : printf(“ B is for Ball ”);
case 0 : printf("\n Exe. Terminated "); break;
exit(); case ‘c’ : printf(“ C is for Cat ”);
break;
break; case ‘d’ : printf(“ D is for Dog ”);
default : printf("\n Invalid choice "); break;
break; case ‘e’ : printf(“ E is for Elephant ”);
} break;
getch();
… … … …
return 0; … … … …
}
case ‘z’ : printf(“ Z is for Zebra ”);
Output: break;
[1] MINUTES default : printf(“ Invalid. Enter a-z only. \n”);
break;
[2] HOURS }
[3] DAYS return 0;
[4] MONTHS }
[5] SECONDS
[0] EXIT Output: Enter a Char a – e: a
A is for Apple.
Enter your choice: 2
Enter how many years: 1
Hours: 8760

Loops (for, while, do-while): .


ITERAION CONTROL STATEMENTS:

Iteration Control Statements also called as Repetition or Loop Control Statements. This type
of statements helps the computer to execute a group of statements repeatedly. This allows a set of
instruction to be performed until a certain condition is reached.

What is a loop?
A loop is defined as a block of statements which are repeatedly executed for certain number
of times.

There are three types of loops in C:


a) for loop
b) while loop
c) do-while loop

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
a) The for loop:

There are three parts / portions / blocks of for loop:


a) Counter initialization.
b) Check condition.
c) Modification of counter.

Syntax:
for (variable initialize; check condition; modify counter)
{
statements 1;
-----------;
-----------;
statements n;
}

Explanation:

1. The initialization is usually an assignment that is used to set the loop control variable.
2. The condition is a relational expression that determines when the loop will exit.
3. The modify counter defines how loop control variables will change each time the loop is repeated.

* These three sections are separated by semicolon (;).


* The for loop is executed as long as the condition is true. When, the condition becomes
false the program execution will resume on the statement following the block.
* Advantage of for loop over other loops:
All three parts of for loop (i.e., counter initialization, check condition, modification of
counter) are implemented on a single line.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
Some more usage format about for loop:

Sl Usage Meaning

we can assign multiple variables together in for


1. for ( p=1, n=2; n<17; n++ )
loop.
The increment section may also have more than
2. for (n=1, m=50; n<=m; n=n+1, m=m-1)
one part as given.
The test condition may have any compound
3. for ( i=1, sum=0; i<20 && sum<100; ++I )
relation as given.
It is also permissible to use expressions in the
4. for ( x=(m;n)/2; x>0; x=x/2) assignment statements of initialization and
increment section as given.
we can omit the initialization and increment
5. for ( ; m!=100 ; )
section to set up time delay.

6. for ( ; ; ) Infinite loop. (use ctrl + break to quit execution)

The for loop will iterate only one time. So, it is not
7. for ( p=1; n<=17; n++ );
advisable.

Example 1: Write a C program to print 1 upto 10 nos using for loop.

#include <stdio.h>
int main()
{
int counter;
for (counter =1; counter<=10; counter++)
{
printf("%d \n", counter);
}
return 0;
}

Output:
1 2 3 4 5 6 7 8 9 10

Example 2: Write a C program to print 10th Multiplication Table upto 10 using for loop.

#include<stdio.h>
int main() Output:
{ 10 * 1 = 10
int i, n; 10 * 2 = 10
printf(“ Enter which table to print: “); 10 * 3 = 10
scanf(“%d”, &n); 10 * 4 = 10
for (i =1; i<=10; i++) 10 * 5 = 10
{ 10 * 6 = 10
printf(" %d * %d = %d \n", n, i, n*i); 10 * 7 = 10
} 10 * 8 = 10
return 0; 10 * 9 = 10
} 10 * 10 = 100

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
b) while loop:

It is a primitive type looping control because it repeats the loop a fixed no. of time. It is also
called entry-controlled loop statements.

Syntax:
while (test condition)
{
body of loop;
}

Explanation:

The test condition is evaluated if the condition is true, the body of loop will be executed.

Example 1: Write a program to print the entered number in reverse order?

#include<stdio.h>
int main()
{
int i=1, n, d, rev;

printf(" Enter the number of digits: ");


scanf("%d", &d);

printf("\n Enter the number which is to be reversed: ");


scanf("%d", &n);

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
printf("\n The reversed number is: ");
/* Compare with for loop
while( i <= d ) for( i=1; i<=d; i++)
{ {
rev = n%10; rev = n%10;
printf("%d", rev); printf("%d", rev);
n = n/10; n = n/10;
i++; }
} */

return(0);
}

Output:
Enter the number of digits: 4
Enter the number which is to be reversed: 7896
The reversed number is: 6987

Enter the number of digits: 4


Enter the number which is to be reversed: 3692
The reversed number is: 2963

c) do-while loop:

The minor Difference between the working of while and do-while loop is the place where the
condition is tested. The while tests the condition before executing any of the statements within the
while loop. As against this, the do-while loop tests the condition after having executed the statement
within the loop.

syntax:
do
{
… … …
body of loop;
… … …

} while (test condition);

Explanation:

It first executes the body of the loop, and then evaluates the test condition. If the condition is
true, the body of loop will be executed again and again until the condition becomes false.

Example 1: Write a program to find the numbers using do while loop.

#include<stdio.h>
#include<math.h>
int main()
{
int y, x=1;
printf("\n Print the numbers and their cubes ");
printf(" \n =========================");
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
do
{
y = pow(x, 3);
printf("%5d %27d\n", x, y);
x++;
} while( x <= 10 );

return(0);
}

Output:
Print the numbers and their cubes
==========================
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

Break and Continue: .

Jumping Out of Loops:

In various scenarios, you need to either exit the loop or skip an iteration of loop when certain
condition is met. So, in those scenarios are known as jumping out of the loop. There are two ways
in which you can achieve the same.

i) break statement:

We have already met break in the discussion of the switch statement. It is used to exit from
a loop or a switch, passing control to the first statement beyond the loop or a switch. With loops,
break can be used to force an early exit from the loop, or to implement a loop with a test to exit in
the middle of the loop body. A break within a loop should always be protected within an if statement
which provides the test to control the exit condition.

When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.

In case of nested loop, if the break statement is encountered in the inner loop then inner loop
is exited.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 13
Syntax:
Statements;
… … …
break;

It can be used with for, while, do-while and switch statements.

Example: Write a C program to explain the use of “ break “ statement.

#include<stdio.h>
int main()
{
int counter;
for (counter=1; counter<=10; counter++)
{
if(counter == 5)
{
break;
}
printf("%d \n", counter);
}
return 0;
}

Output: 1 2 3 4

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 14
ii) continue statement:
Continue Statement sends the control directly to the test-condition and then continue the loop
process. On encountering continue keyword, execution flow leaves the current iteration of loop, and
starts with the next iteration.
This is similar to break but is encountered less frequently. It only works within loops where its
effect is to force an immediate jump to the loop control statement.
Syntax:
statement 1;
continue;
statement 2;

• In a while loop, jump to the test statement.


• In a do while loop, jump to the test statement.
• In a for loop, jump to the test, and perform the iteration (looping).

Like a break, continue should be protected by an if statement. You are unlikely to use it very often.

Example: Write a C program to explain the use of “ continue “ statement.


#include<stdio.h>
int main()
{
int i;
for ( i = 1; i <= 10; i++ )
{
if (i == 5) /* If i is equals to 6, continue to next iteration
{ continue; } without printing i value. */
else
{ printf(" %d ", i); } // otherwise print the value of i
}
return 0;
}

Output:
1 2 3 4 6 7 8 9 10

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 15

You might also like