C Programming Chapter 3

advertisement
Programming in C
Chapter 3: Loops and Decisions
Definition: Decision making statements are the statements which are used to take some decision
depending upon certain conditions. In C language we can use following statements for decision
making.
(i)
if statement
(ii)
switch statement
(iii)
goto statements
(iv)
conditional operator
1. if statement: If statement is used for decision making purpose. It takes a condition part if this
condition is true then some statements are executed otherwise these statements are ignored. If
statements may be divided into following four sub-types.
(a) simple if
(b) if……..else
(c) nested if
(d) if ladder
We’ll see all of above statements one by one.
(a) simple if: The syntax of simple if is given below.
if (condition)
{
s1;
s2;
sn
}
If given condition is true then all the statements s1, s2……sn will be executed.
Example 5.1: Program to show the use of simple if statement.
int main()
{
int a;
printf(“\nEnter the value of a”);
scanf(“%d”,&a);
if ( a < 10 ) /*check if condition is true*/
{
printf(“\nLess than 10”);
}
return 0;
}
(b) if …..else statements: If we want to execute some particular statements if condition
is true and other statements if condition is false then we use if………..else statements.
Syntax of if……..else is:
if (condition)
{
s1;
s2 ; /*executed when condition is true. */
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
else
{
s3; /* executed when condition is false */
s4;
}
Example: Program to show the use of if……else statement.
int main()
{
int a,b;
printf(“\n Enter the value of a & b”);
scanf(“%d%d”,&a,&b);
if ( a < b)
{
printf(“\na is less than b”);
}
else
{
printf(“\nb is less than or equal to a”);
}
return 0;
}
Example: Get any number from keyboard and check whether this number is even or odd.
int main()
{
int n;
printf(“\nEnter any value");
scanf(“%d”,&n);
if( n % 2 == 0) /*if number is divisible by 2 */
{
printf(“\nNumber is even");
}
else
{
printf(“\nNumber is odd");
}
return 0;
}
Note1: Else part is optional. So sometimes it may generate misunderstanding of the code. Like in
following example we may confuse that else part is of which if.
int main()
{
int a,b,c,d;
d=5;
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
printf(“\nEnter the value of a and b”);
scanf(“%d%d”,&a,&b);
if(d<10)
if (a<b)
z=a;
else
z=b;
return 0;
}
Note2: else part is assigned to the closest if.
Note3: To write the clearer coding we should use curly braces with each if and else and also use
indentation. Like above example is clearer when we write as follow:
int main()
{
int a,b,c,d;
d=5;
printf(“\nEnter the value of a and b”);
scanf(“%d%d”,&a,&b);
if(d<10)
if (a<b)
c=a;
else
c =b;
return 0;
}
(c) Nested If: When there is an if statement inside other if statement then it is called nested if.
Syntax is:
if (condition1)
{
if (condition2)
{
if(Condition3)
{
}
else /* else of inner most if */
{
}
}
else /* else of second if */
{
}
}
Note: It is not necessary to use the else part of each if statement.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
Example 5.4: Program to show the use of nested if statement.
int main()
{
int x;
printf(“\nEnter any value”);
scanf(“%d”,&x);
if (x<10)
{
if(x>=0)
{
printf(“\n Positive number”); }
else
{
printf(“\n Negative number”);}
}
else
{
printf(“\n Number is greater than or equal to 10”); }
return 0;
}
(d) else if ladder: If we want to take multi-way decision using if statement , we use ladder if.
Syntax is :
if( condition1)
{
}
else if (condition2)
{
}
else if (condition3)
{
}
else
{
}
Here all the conditions are checked one by one until a true condition is found. If one true
condition is found then the body of that if is executed and remaining conditions are left
unchecked. If all conditions fail then else part is executed. Here is given one program based on
ladder if.
Example: Get a value from user between 1 and 4. If user enters 1 then print North, if user
enters 2 then print South, if user enters 3 then print East, and if user enters 4 then print
West. If user enters other than these values then print number is out of range.
#include<stdio.h>
int main( )
{
int n;
printf(“\nEnter the value b/w 1 and 4”);
scanf(“%d”,&n);
if (n==1)
{
printf(“\n North”);
}
else if (n==2)
{
printf(“\n South”);
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
else if (n==3)
{
printf(“\n East”);
}
else if (n==4)
{
printf(“\n West”);
}
else
{
printf(“\nInvalid direction ”); }
return 0;
}
Note1: We can write any no. of ‘else if ‘statements without else part.
Note2: Conditions of two ‘else if’ part may be same. But only first part will be executed.
Note3: Observe output
#include<stdio.h>
int main()
{
int a=1;
if(a==1)
{
printf(“\nIf Part”);
a++;
}
else if(a==2)
{
printf(“\nIn first else if part”);
a++;
}
else if(a==3)
{
printf(“\nIn Second else if”);
}
else
{
printf(“\nIn Else Part”);
}
return 0;
}
Example: Program to find the greatest number among three entered numbers.
int main()
{
int a,b,c;
printf(“\nEnter the value of a, b and c”);
scanf(“%d%d%d”,&a,&b,&c);
if ( a >= b && a > c)
{
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
printf(“\nGreatest number is %d”,a);
}
else if (b > a && b > c)
{
printf(“\nGreatest number is %d”,b);
}
else
{
printf(“\nGreatest number is %d”, c);
}
return 0;
}
Exercise 1: Draw programs in which give five options
1. Entered number
2. Square
3. Cube
4. power four
5. exit
Take any number from user and ask for option number. If he enters 1 then print number itself, if
he enters 2 then print square of number, if he enters 3 then enter cube and so on. If option is
different then all above then print option does not available.
(2) switch statement: switch statement is used when we want to check multiple conditions one
by one. With switch statement we use cases. In each case we give some constant value.
One value is passed into switch statement. This value is matched with constants given in case. If
any value is found matched then body of that case is executed. If one match is found then next
cases are left unchecked. If no case is matched then default part is executed. switch is used when
we already know about the values which will come in switch statement so that we can give those
values in advance in case statement. Syntax is as follow
switch (expression)
{
case constantvalue1 :
s1;
s2;
break ;
case constantvalue2:
s4;
s5;
break;
default:
s6;
s7;
break;
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
Expression may be any arithmetic expression or may be name of variable too. But ‘constant
value’ must be of constant type. We cannot use variables here. If we want we can write here as
2+3 etc. An example is given below.
Example: Program to show the use of switch statement.
int main( )
{
int n;
printf(“\nEnter value”);
scanf(“%d”,&n);
switch (n) /*pass value of n in switch*/
{
case 1:
printf(“\n In first case”);
break;
case 2:
printf(“\n In second case”);
break;
case 4:
printf(“\n In fourth case”);
break;
default :
printf(“\n In default”);
break;
}
return 0;
}
Note1. If we keep the expression portion blank i.e. do not write anything then it gives errors.
Note2. Constant value of two cases cannot be same.
Note3. Default part is not necessary to be included.
Note4. It is not necessary that constant value of case part should come in a particular order.
Note5. If we do not use break statement in a case then execution goes case by case until a break
is encountered or closing curly brace of switch statement is encountered.
Note6. We can put default section anywhere in the program. But its meaning doesn’t change i.e.
it is called when no case is matched.
Note7. We can use ‘case’ without ‘default’ and ‘default’ without ‘case’. Even if we can use
switch without case and default but this will not be reachable code. Like
switch(1)
{
printf(“\n Hello”);
printf(“\n Hye”);
}
Note8: We cannot use float values in switch () statement and in cases.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
Note9: What will be the output of the following codes?
(i) switch(val)
{
case ‘A’ :
printf(“\n Hello”);
break;
case 65:
printf(“\n Hye”);
break;
}
(ii) switch(2.3)
{
case 2:
printf(“\nIn case 2”);
break;
case 3:
printf(“\nIn case 3”);
break;
default
printf(“\nIn default part”);
}
(iii) switch(2)
{
case 2.1:
printf(“\nIn case 2”);
break;
case 3:
printf(“\nIn case 3”);
break;
default
printf(“\nIn default part”);
}
(iv) switch(int(2.3))
{
case 2:
printf(“\nIn case 2”);
break;
case 3:
printf(“\nIn case 3”);
break;
default
printf(“\nIn default part”);
}
(v) switch(2)
{
case int(2.1):
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
printf(“\nIn case 2”);
break;
case 3:
printf(“\nIn case 3”);
break;
default
printf(“\nIn default part”);
}
(vi) switch(2)
{
case :
}
(vii) switch(2)
{
case 1:
printf(“\n In case 1”);
case 2:
printf(“\n In case 2”);
case 3:
printf(“\n In case 3”);
default:
printf(“\nIn default part”);
}
(viii) switch(2)
{
default:
printf(“\n In default”);
case 1:
printf(“\n In case 1”);
case 2:
printf(“\n In case 2”);
case 3:
printf(“\n In case 3”);
}
Example: Write a program in which there are following four options.
1. Addition
2. Subtraction
3. Multiplication
4. Division
Get option values by user and then get two values from user. If he enters 1 as option then sum
will be printed if he enters 2 then subtraction will be printed and so on. If no match is found then
print option not available.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
int main()
{
int a , b, opt;
float c;
printf(“\n1. Addition \n2. Subtraction \n3. Multiplication \n4. Division”);
printf(“\n Enter any option”);
scanf(“%d”,&opt);
switch(opt)
{
case 1:
printf(“\nEnter two values”);
scanf(“%d%d”,&a,&b);
c = (float)a + b; //cast conversion//
printf(“\nAddition is %f”, c);
break;
case 2:
printf(“\nEnter two values”);
scanf(“%d%d”,&a,&b);
c = (float)a - b;
printf(“\nSubtraction is %f”, c);
break;
case 3:
printf(“\nEnter two values”);
scanf(“%d%d”,&a,&b);
c = (float)a * b;
printf(“\nMultiplication is %f”, c);
break;
case 4:
printf(“\nEnter two values”);
scanf(“%d%d”,&a,&b);
c =(float) a / b;
printf(“\nDivision is %f”, c);
break;
default:
printf(“\nOption not available”);
break;
}
return 0;
}
Exercise 2: Make all the programs of ‘else…..if ladder’ statements using Switch()
statement.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
3. goto statement: goto statement is used in a program to switch the control of the program
execution to a predefined label. This is generally used with if statement. This affects the
execution time so this statement must be avoided for decision making.
If we use goto statement then we have to give a label name where the goto statement will send
the control. Following example will clarify the concept.
Example: Program to perform addition of two numbers multiple times.
#include<conio.h>
#include<stdio.h>
int main()
{
int a,b,c;
char ch;
start: /* Label for goto statement */
clrscr();
printf(“\nEnter first number”);
scanf(“%d”,&a);
printf(“\nEnter second number”);
scanf(“%d”,&b);
c=a+b;
printf(“\nSum is %d”, c);
printf(“\nDo u want more y/n”); /* Ask for more */
fflush(stdin);
scanf(“%c”,&ch);
if(ch==’y’ || ch==’Y’)
goto start; /*send control back to label start */
return 0;
}
Example : Program to print values from 1 to 5.
#include<stdio.h>
int main()
{
int i=1;
start:
printf(“\n%d”,i);
if(i<5)
{
i++; /*increase value of i by 1 */
goto start; /*send control back to label*/
}
return 0;
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
4. Conditional Operator statement: This is actually an operator denoted as (? :). This operator
plays the role as a decision making statement. Example will clear it.
int a=3, b=4, c;
c=(a<b)?a:b;
Here (a<b) is condition. In this expression if condition is true then value of a will be assigned to
c otherwise value of b will be assigned.
Example: Draw a program to find the greater number between two numbers.
#include<stdio.h>
int main()
{
int a,b,c;
printf(“\nEnter two numbers”);
scanf(“%d%d”,&a,&b);
c = a>b?a:b;
printf(“\nGreater number is %d”,c);
return 0;
}
Loop Control Mechanism:
Definition: Loops are the statements, which are used to execute certain statements repeatedly.
This is controlled by some condition statements. Loop will be executed till the condition is true.
When condition is false loops are terminated. In C we have three types of loops.
1. for loop
2. while loop
3. do while loop
We can categorize the loops into two types.
 Entry controlled loop.
 Exit controlled loop.
Entry controlled loops are the loops where condition is checked first then all statements of loop
are executed if condition is true. Exit controlled loops are the loops in which statements are
executed at least once and then condition is checked if condition is true then again whole body is
executed. In this manner we can say that while and for are the entry control loops whereas do
while loop is exit control loop.
1. for loop: For loop is most frequently used in C language. It contains three parts of a loop in a
single line that are initialization part, test condition part and increment/decrement part which are
separated by semicolon (;). Syntax of for loop is:
for( initialization; test condition; increment/decrement)
{
s1;
s2;
sn;
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
1. Initialization: In this part, we give some initial value to the loop control variable. We
can even do the both declaration and initialization here.
Such as: for(int i=1;i<10;i++)
{
}
2. Test condition: - In this part, any condition is given to test whether to continue or
terminate the loop. If condition is true then loop is continued if condition is false then
loop is terminated.
3. Increment/Decrement: In this part, some calculation is done generally on the control
variable. In part1 we can initialize many variables with control variable. Each
initialization is separated by comma. Same thing happens in part 3, we can perform many
calculations in part three each separated by comma.
Execution of for loop: When execution of for loop starts then first time when for loop is started
part 1 and part 2 are executed. That is control variable is initialized and tested. If condition is true
then statements contained in for loop’s body are executed. When execution reaches at the last
statement of the for loop then after executing last statement execution goes to part 3 where
calculations are performed generally for control variable. And then part 2 is executed i.e.
condition is checked again then all the statement of for loop are executed again. This cycle goes
until the condition is false.
Example: program to demonstrate the use of for loop.
#include<stdio.h>
int main ( )
{
int i;
for (i=0; i<3; i+ +)
{
printf(“\n%d”, i);
}
return 0;
}
Output:
0
1
2
Note1: - part1 and part2 are executed when loop is executed first time. Other times part3 and
part2 are executed.
Note2: - We can leave all the part blank. But we have to use semicolon two times like for (; ; )
Note3: - We leave the condition part blank then this loop is always considered as true (Infinite
loop).
Note4: - We should always try to avoid the use of control variable for calculations.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
Example: Draw a program in which find all the even numbers less than 50.
int main()
{
int i;
/* loop to print all even numbers less than 50*/
for(i=0;i<50;i++)
{
if(i%2==0) /* check for evenness*/
printf(“\n%d”,i);
}
return 0;
}
Example: WAP in which print the table of 3
int main()
{
int i,count=0;
for(i=0;i<10;i++)
{
count+=3;
printf(“\n%d”,count);
}
return 0;
}
Example : WAP to print the table of any number. Get the value from keyboard.
int main()
{
int i,n,term;
printf(“\n Enter the number”);
scanf(“%d”, &n);
for(i=1;i<=10;i++)
{
term= n*i;
printf(“\n%d”,term);
}
return 0;
}
Example: Program to print all even numbers from a to b. Get the value of a & b from K/B.
int main()
{
int a, b , i;
printf(“\n Enter the value of a and b”);
scanf(“%d %d”, &a,&b);
for(i=a ; i<=b ; i++)
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
{
if( i % 2==0)
{
printf(“\n %d”, i);
}
}
return 0;
}
Example: Program to calculate the cube of any number. Get number from keyboard.
int main()
{
int num,i, pow=1;
printf(“\n Enter the number.”);
scanf(“%d”,&num);
for(i=0 ; i<3 ; i++)
{
pow=pow*num; /* Calculates the power */
}
printf(“\n The cube of %d is %d”, num, pow );
return 0;
}
Example: Program to calculate the b power of a ie. a^b. Get the value of a & b from k/b.
int main()
{
int a ,i,b,pow=1;
printf(“\nEnter the value of a and b.”);
scanf(“%d%d”, &a, &b);
for ( i = 0 ; i < b ;i++ ) /* loop executes for b times*/
{
pow = pow * a;
}
printf(“\n %d ^ %d is %d”, a,b,pow);
return 0;
}
Example: Write a program to find the factorial of any number.
# include<stdio.h>
int main( )
{
int fact =1; int i,n;
printf(“\n enter the number”);
scanf(“%d”,&n); /*get number*/
/*loop to calculate factorial*/
for(i=1; i<=n; i++)
{
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
fact = fact*i; /* stores the factorial */
}
printf(“\n Factorial of %d is %d”,n, fact);
return 0;
}
Example: Program to print the sum of following series.
1 + 2 + 3 ……………… + 10.
int main()
{
int i,sum=0;
/* loop to calculate the sum of above series */
for(i=0 ; i<=10 ; i++)
sum = sum + i;
printf(“\n Sum of above series is %d”, sum);
return 0;
}
Example: Program to print the sum of following series.
x + x^2 + x^3 + x^4 +………………………x^10. Get value of x from keyboard.
int main()
{
int x, term=1 ,i,sum=0;
printf(“\n Enter the value of x”);
scanf(“%d”,&x);
for(i=0;i<10;i++) /* loop to add 10 terms */
{
term=term*x; /* calculates the term*/
sum=sum+term; /* adds terms */
}
printf(“%d”,sum);
return 0;
}
Example: Program to calculate following series.
x/1 + x/2 + x/3 +………………………….x/10.
int main()
{
int x,i;
float sum=0,term=1;
printf(“\nEnter the value of x”);
scanf(“%d”,&x);
for(i=1 ; i<=10 ; i++)
/* loop to add 10 terms */
{
sum =sum + (float)x/i;
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
printf(“\nSum of the series is %f”, sum );
return 0;
}
Break and continue statements:
break statement: This statement is used to break a loop. Whenever a break statement is
encountered, control goes out of body of the loop without checking conditional part of the loop.
Example: Loop to print numbers from 1- 4 using infinite loop.
#include<stdio.h>
int main()
{
int i;
for ( i =1; 1 ; i++)
{
if ( i==5)
break;
printf(“\n %d”,i);
}
return 0;
}
Continue statement: This statement is also used in loops. Whenever this statement is
encountered it sends the control directly to the conditional part (part3 for ‘for loop’) without
running the remaining part of the loop’s body. After that loop continues with sequential
execution.
Example: Program to print numbers from 1 – 10 except 5.
int main()
{
int i;
for ( i=1 ; i<=10 ;i++)
{
if(i==5)
{
continue;
}
printf(“\n %d”,i);
}
return 0;
}
Example: Program to check whether a number is prime or not.
int main()
{
int n,i;
printf(“\nEnter the number.”);
scanf(“%d”,&n);
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
/*loop to check prime number*/
for(i =2;i<n;i++)
{
if(n%i==0) /* if number is divisible*/
{
printf(“\nNumber is not prime”);
break;
}
}
if(i==n)
printf(“\nNumber is prime.”);
return 0;
}
Nested loop: One loop inside other loop is called nested loop. This may be while loop, for loop
or do…..while loop.
Example: Program to print table from 1-10.
int main()
{
int i,j,term;
/*loop to control row */
for ( i=1;i<=10;i++)
{
/* loop to control column */
for ( j=1;j<=12 ; j++)
{
term=i*j;
printf(“%d”,term);
}
printf(“\n”);
}
return 0;
}
Example: Program to print following output.
1
12
123
1234
12345
#include<stdio.h>
int main()
{
int i, j;
/*loop to control rows */
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
for(i=1;i<=5;i++)
{
/*loop to control colums*/
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
printf(“\n”); /* get control in next line */
}
return 0;
}
Example: Program to print all the prime numbers less than a given number.
int main()
{
int num,j,i;
printf(“\n Enter the number.”);
scanf(“%d”,&num);
/*loop to take all the numbers one by one*/
for(i=2;i<num;i++)
{
/*loop to check primness */
for (j=2;j<i; j++)
if(i%j==0)
break;
if(i==j)
printf(“\n %d”,i); /*print prime number i*/
}
return 0;
}
2. while loop: while is also a loop control mechanism. Syntax of while loop is given below:
initialization;
while(condition)
{
s1;
s2;
…..
Sn;
Increment/decrement;
}
Loop will execute till the condition is true.
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
Example: Program to print all the even numbers less than a given number using while loop.
#include<stdio.h>
int main()
{
int i,n;
printf(“\n Enter the value.”);
scanf(“%d”,&n);
i=0; /* initialize i with 0*/
/* loop to print all even numbers starting from 0 */
while(i<=n) /*check the condition */
{
if ( i%2==0) /* check evenness */
{
printf(“\n %d”,i);
}
i++; /*increase the value of i by one */
}
return 0;
}
Example: Program to calculate the sum of all the digits of a number.
#include<stdio.h>
int main()
{
int rem , sum=0,n,n1;
printf(“\nEnter the value.”);
scanf(“%d”,&n);
n1=n; /* take one copy of actual value */
while(n1>0)
{
rem = n1%10; /*get remainder*/
n1= n1/10; /*terminate unit digit */
sum = sum + rem; /* get sum of digit*/
}
printf(“\nThe sum of digits of number %d is %d”, n,sum);
return 0;
}
Example: WAP to check whether an entered number is Armstrong or not. An Armstrong
number of three digits is an integer such that the sum of the cubes of its digits is equal to the
number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371
#include<stdio.h>
int main()
{
int rem,sum=0,num,num1;
printf(“\n Enter the value.”);
scanf(“%d”,&num);
num1=num; /* take another copy of the number*/
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Programming in C
while(num1>0)
{
rem = num1%10; /*get remainder*/
sum = sum + rem*rem*rem; /* add the cube of digit in sum*/
num1=num1/10; /* terminate unit digit*/
}
if( num==sum) /* check if sum of digit is equal to number*/
{
printf(“\nNumber is Armstrong.”); }
else
{
printf(“\n Number is not Armstrong.”);
}
return 0;
}
3. do…while() loop: This is an exit controlled loop. It is different than above two loops in
respect of execution of its body. Here, body of loop is executed first and then condition is
checked. If condition is true then again body is executed else the loop is terminated. It continues
till the condition is true. Syntax of do… while() loop is:
Initialization;
do{
s1;
s2;
.
.
sn;
increment/decrement;
}while(condition);
Example: Write a program in which you can add two numbers till your desired times.
#include<stdio.h>
int main()
{
int a,b,c;
char ch;
do{
printf(“\nEnter first Number.”);
scanf(“%d”,&a);
printf(“\nEnter Second Number.”);
scanf(“%d”,&b);
c=a+b;
printf(“\n Sum is %d”,c);
printf(“\n Do U want to add more nos? y/n”);
fflush(stdin); /* to clear input buffer */
scanf(“%d”,&ch); /* take input y/n from user */
}while(ch==’y’||ch==’Y’); /*if user enters y*/
return 0;
}
Compiled by: Er. Khurshid Alam, kh.alam@yahoo.com
Download