Unit-2 Intro to Prog (AK23)
Unit-2 Intro to Prog (AK23)
Unit-2 Intro to Prog (AK23)
Control Structures
Simple sequential programs, Conditional Statements (if, if-else, Switch). Loops (for, while, do-while), Break
and Continue.
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.
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)
{
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.
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);
getch();
return 0;
}
Output:
Enter candidate age: 20
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);
return(0);
}
Output:
: Enter marks :
Telugu: 96
English: 86
Maths: 77
Hindi: 66
Physics: 65
Chemistry: 88
Total: 478
Average: 79.00
Result: Distinction
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;
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.
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
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.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
a) The for loop:
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.
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
The for loop will iterate only one time. So, it is not
7. for ( p=1; n<=17; n++ );
advisable.
#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.
#include<stdio.h>
int main()
{
int i=1, n, d, rev;
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
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;
… … …
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.
#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
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;
#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;
•
Like a break, continue should be protected by an if statement. You are unlikely to use it very often.
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