FCP 2 If Else

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 83

Introduction to C

Programming

Control Instruction

alter our actions by circumstances.


If the weather is fine, then I will go for a stroll
If the highway is busy I would take a diversion
notice that all these decisions depend on some condition being
met
C language too must be able to perform different sets of
actions depending on the circumstances
C has three major decision making instructions
If statement
if-else statement
SThe conditional operators.
switch statement

Decisions! Decisions!
Last class programs steps are executed sequentially i.e. in the
same order in which they appear in the program.
Many a times, we want a set of instructions to be executed in
one situation, and an entirely different set of instructions to be
executed in another situation.
This kind of situation is dealt in C programs using a decision
control instruction
(a) The if statement
(b) The if-else statement
(c) The conditional operators.

The if Statement
General form
if ( this condition is true )
{
execute this statement ;
}
But how do we express the condition itself in C?
we express a condition using Cs relational operators.
this expression
is true if
x == y
x is equal to y
x != y
x is not equal to y
x<y
x is less than y
x>y
x is greater than y
x <= y
x is less than or equal to y
x >= y
x is greater than or equal to y

/* Demonstration of if statement */
#include<stdio.h>
void main( )
{
int num ;
printf ( "Enter a number less than 10 " ) ;
scanf ( "%d", &num ) ;
if ( num <= 10 )
printf ( "What an obedient servant you are !" ) ;
}

While purchasing certain items, a discount of 10% is offered if


the quantity purchased is more than 1000. If quantity and price
per item are input through the keyboard, write a program to
calculate the total expenses.
void main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;

The current year and the year in which the employee joined the
organization are entered through the keyboard. If the number of
years for which the employee has served the organization is
greater than 3 then a bonus of Rs. 2500/- is given to the
employee. If the years of service are not greater than 3, then
the program should do nothing.

#include<stdio.h>
void main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}
}

The Real Thing


General form
if ( this condition is true )
{ execute this statement ; }
But
if ( expression )
{ execute this statement ; }
expression can be any valid expression
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
C a non-zero value is considered to be true, whereas a 0 is
considered to be false.

The if-else Statement


Can we execute one group of statements if the expression
evaluates to true and another group of statements if the
expression evaluates to false?
Of course! This is what is the purpose of the else statement
General Form
if ( this condition is true )
{
execute this statement ;
}
else
{
execute this statement ;
}

The group of statements after the if upto and not including the
else is called an if block. Similarly, the statements after the
else form the else block.
Notice that the else is written exactly below the if.
Had there been only one statement to be executed in the if
block and only one statement in the else block we could have
dropped the pair of braces.
As with the if statement, the default scope of else is also the
statement immediately after the else.

Example. In a company an employee is paid as under: If his


basic salary is less than Rs. 1500, then HRA = 10% of basic
salary and DA = 90% of basic salary. If his salary is either
equal to or above Rs. 1500, then HRA = Rs. 500 and DA =
98% of basic salary. If the employee's salary is input through
the keyboard write a program to find his gross salary.

#include<stdio.h>
void main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;

Nested if-elses
if we write an entire if-else construct within either the body of the if
statement or the body of an else statement. This is called nesting of ifs.

if ( condition )
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}
else
do this ;

#include<stdio.h>.
void main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ;
scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( "You would go to heaven !" ) ;
else
{
if ( i == 2 )
printf ( "Hell was created with you in mind" ) ;
else
printf ( "How about mother earth !" ) ;
}

Forms of if
The if statement can take any of the following forms:
(a) if ( condition )
do this ;
(b) if ( condition )
{
do this ;
and this ;
}
(c) if ( condition )
do this ;
else
do this ;

Forms of if
(d) if ( condition )
{
do this ;
and this ;
}
else
{
do this ;
and this ;
}

Forms of if
(e) if ( condition )
do this ;
else
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}

(f) if ( condition )
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}
else
do this ;

Nested if-else Example


Example 2.4: The marks obtained by a student in 5

different subjects are input through the keyboard.


The student gets a division as per the following
rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained
by the student.

void main( )
{ int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division ") ;
else
{
if ( per >= 50 )
printf ( "Second division" ) ;
else
{
if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "Fail" ) ;
}
}
}

This is a straight forward program. Observe that the program


uses nested if-elses.
This leads to three disadvantages:
(a) As the number of conditions go on increasing the level of
indentation also goes on increasing. As a result the whole
program creeps to the right.
(b) Care needs to be exercised to match the corresponding ifs
and elses.
(c) Care needs to be exercised to match the corresponding
pair of braces.
All these three problems can be eliminated by usage of
Logical operators.

Use of Logical Operators


C allows usage of three logical operators, namely, &&, || and !.
These are to be read as AND OR and NOT respectively.
The first two operators, && and ||, allow two or more
conditions to be combined in an if statement.
Operands

Results

!x

!y

x && y

x || y

0
non-zero
non-zero

non-zero
0

non-zero 0

void main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
}

Two distinct advantages in favour of this program:


1) The matching of the ifs with their corresponding elses gets
avoided, since there are no elses in this program.
2) In spite of using several conditions, the program doesn't
creep to the right. In the previous program the statements
went on creeping to the right.

Control Instruction

alter our actions by circumstances.


If the weather is fine, then I will go for a stroll
If the highway is busy I would take a diversion
notice that all these decisions depend on some condition being
met
C language too must be able to perform different sets of
actions depending on the circumstances
C has three major decision making instructions
If statement
if-else statement
Logical Operators
The conditional operators.
switch statement

The Case Control Structure


make a choice between a number of alternatives rather than
only one or two
Choice is more complicated than merely selecting between two
alternatives.
C provides a special control statement that allows us to handle
such cases effectively;
rather than using a series of if statements

Decisions Using switch


switch ( integer expression )
{
case constant 1 :
do this ;
break;
case constant 2 :
do this ;
break;
case constant 3 :
do this ;
break;
default :
do this ;

Integer expression that will yield an integer value


Integer constant or expression that evaluates integer
keyword case is followed by an integer or a character
constant.

If a = 10, b = 12, c = 0, find the values of the expressions in


the following table:
Expression
Value
a != 6 && b > 5
a == 9 || b < 3
! ( a < 10 )
! ( a > 5 && c )
5 && c != 8 || !c

What would be the output of the following programs:


void main( )
{
char suite = 3 ;
switch ( suite )
{
case 1 :
printf ( "\nDiamond" ) ;
case 2 :
printf ( "\nSpade" ) ;
default :
printf ( "\nHeart") ;
}
printf ( "\nI thought one wears a suite" ) ;
}

void main( )
{
int c = 3 ;
switch ( c )
{
case 'v' :
printf ( "I am in case v \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
case 12 :
printf ( "I am in case 12 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}

void main( )
{
int k, j = 2 ;
switch ( k = j + 1 )
{
case 0 :
printf ( "\nTailor") ;
case 1 :
printf ( "\nTutor") ;
case 2 :
printf ( "\nTramp") ;
default :
printf ( "\nPure Simple Egghead!" ) ;
}

void main( )
{
int i = 0 ;
switch ( i )
{
case 0 :
printf ( "\nCustomers are dicey" ) ;
case 1 :
printf ( "\nMarkets are pricey" ) ;
case 2 :
printf ( "\nInvestors are moody" ) ;
case 3 :
printf ( "\nAt least employees are good" ) ;
}

void main( )
{
int i = 1 ;
int ch = 'a' + 'b' ;
switch ( ch )
{
case 'a' :
case 'b' :
printf ( "\nYou entered b" ) ;
case 'A' :
printf ( "\na as in apple" ) ;
case 'b' + 'a' :
printf ( "\nYou entered a and b" ) ;
}

There are three ways for taking decisions in a program. First way
is to use the if-else statement, second way is to use conditional
operators and third way is to use the switch statement
The default scope of the if statement is only the next statement.
So, to execute more than one statement they must be written in a
pair of braces.
An if block need not always be associated with an else block.
However, an else block is always associated with an if
statement.
&& and || are binary operators, whereas, ! is a unary
operator.
In C every test expression is evaluated in terms of zero and nonzero values. A zero value is considered to be false and a non-zero
value is considered to be true.
Assignment statements used with conditional operators must be
enclosed within a pair of parenthesis.

Increment and Decrement Operators

The increment operator ++


The decrement operator -Precedence: lower than (), but higher than * / and %
Associativity: right to left
Increment and decrement operators can only be applied
to variables, not to constants or expressions

Increment Operator
If we want to add one to a variable, we can say:

count = count + 1 ;
Programs often contain statements that increment
variables, so to save on typing, C provides these shortcuts:

count++ ; OR
++count ;
Both do the same thing. They change the value of count by
adding one to it.

Post increment Operator


The position of the ++ determines when the value
is incremented. If the ++ is after the variable, then
the incrementing is done last (a post increment).

int amount, count ;

count = 3 ;
amount = 2 * count++ ;

amount gets the value of 2 * 3, which is 6, and


then 1 gets added to count.
So, after executing the last line, amount is 6 and
count is 4.

Preincrement Operator
If the ++ is before the variable, then the
incrementing is done first (a preincrement).

int amount, count ;

count = 3 ;
amount = 2 * ++count ;

1 gets added to count first, then amount gets the


value of 2 * 4, which is 8.
So, after executing the last line, amount is 8 and
count is 4.

#define
These macro definitions allow constant values to be declared
for use throughout your code.
Syntax:
#define CNAME value
#define CNAME (expression)
#include <stdio.h>
#define NAME "TechOnTheNet.com"
#define AGE 10
void main()
{
printf("%s is over %d years old.\n", NAME, AGE);
}

Review

Branching/Decision
Logical Operator
Conditional Operator
Increment and Decrement Operator

The Loop Control Structure


so far used either a sequential or a decision control
instruction.
the calculations were carried out in a fixed order,
an appropriate set of instructions were executed depending
upon the outcome of the condition being tested Exactly once
The versatility of the computer lies in its ability to perform a
set of instructions repeatedly.
This involves repeating some portion of the program either a
specified number of times or until a particular condition is
being satisfied.
This repetitive operation is done through a loop control
instruction.
Group of instructions that are executed repeatedly
while(until) some condition remains true.

Branching

Condition

Loops

Statement
list

Condition

Statement
list

The while Loop


There are three methods by way of which we can repeat a
part of a program. They are:
(a) Using a while statement
(b) Using a for statement
(c) Using a do-while statement
It is often the case in programming that you want to do
something a fixed number of times
Ex. calculate gross salaries of ten different persons,
Ex. Convert temperatures from centigrade to Fahrenheit for
15 different cities.
The while loop is ideally suited for such cases.

The while Loop

Condition

Statement
list

while(Condition)
{
Statement list
}

The general form of while is as shown below:


initialize loop counter ;
while ( test loop counter using a condition )
{
do this ;
and this ;
increment loop counter ;
}

/* Calculation of simple interest for 3 sets of p, n and r */


void main ( )
{
int p, n, count ;
float r, si ;
count=1;
While(count <= 3)
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
// or
/* */
count=count+1; //count++;
its comment
}
}

In the place of condition there can be any other valid which


expression evaluates to a non-zero value
while ( i + j*2)
while ( i >= 10 && j <= 15)
Must test a condition that will eventually become false
int i = 1 ;
while ( i <= 10 )
printf ( "%d\n", i ) ;
We can also used decrement
int i = 5 ;
while (i>= 1 )
{
printf ("\nMake the computer literate!" ) ;
i=i-1;
}

Loop counter can be float also.


float a = 10.0 ;
while (a<10.5 )
{
printf ("\n thats execute!" ) ;
a=a+0.1;
}
What will be the output?
int i = 1 ;
while ( i <= 32767)
{
printf ( "%d\n", i ) ;
i=i+1;
}

Example 1: while
char ans = n;

(ans != Y || ans != y')

while (ans != Y && ans != y)


{
}

printf(Will you pass this exam?);


scanf(%c\n,ans);

Printf(Great!!);

Can I put

; here?

No!!

Example 2: while
Will there be any problem?
int no_times;

What if one inputs 1?

printf(How many times do you want to say?);


scanf(%d,&no_times);
while (no_times != 0)
{
printf(Hello!\n);
no_times--;
}
printf(End!!);

while (no_times > 0)

Example 3: while
int a, b, sum;
printf(This program will return the );
Printf(summation of integers from a to b.\n\n);
printf(Input two integers a and b:);
printf(%d%d, &a, &b);
sum = 0;
while (a <= b)
{
sum += a;
a++;
}

Dont forget to set

sum = 0;
sum = sum + a;

+= ,*=,-=,/=,%=
compound assignment operator
They modify the value of the operand to
the left of them.

printf(The sum is %d, sum);

Example 4: while
int a, b, sum=0;
printf(This program will return the sum );
printf( of odd numbers between a and b.\n\n);
printf(Input two integers a and b:);
scanf(%d%d, &a ,&b);
while (a <= b)
{
if (a % 2)
sum += a;
a++;
}

3, 4, 5, 6 , 7
a

2, 3, 4, 5, 6 , 7

printf(The answer is ,sum);

if (a % 2 == 0)
a++;
while (a <= b)
{
sum += a;
a += 2;
}

Example 5: while

3N+1 problem

long n,i=0;
printf(Input an integer:);
scanf(%d,&n);
while (n > 1)
{
if (n % 2)
n = 3*n+1;
else
n /= 2;
printf(%d:%d,++i,n);
}
printf(Done!!);

Will we always get out of a loop?


That is the question!! No one knows!

Input an integer:7
1:22
2:11
3:34
Input an integer:11
4:17
1:34
5:52
2:17
6:26
Input an integer:3759
3:52
7:13
1:11278
4:26
8:40
2:5639
5:13
9:20
3:16918
6:40
10:10
4:8459
7:20
11:5
5:25378
8:10
12:16
6:12689
9:5
13:8
7:38068
10:16
14:4
.....
11:8
15:2
.....
12:4
16:1
83:16
Done!! 13:2
84:8
14:1
Press any
key to
continue
85:4
Done!!
86:2
Press any key to continue
87:1
Done!!
Press any key to continue

Review
Loops
While loop

Counter Controlled loop


int i = 1 ;
Printf(How many times repeat these statements);
Scanf(%d,&n)
while (i<= 10 ) //while(i<=n)
{
printf ("\nWelcome!" ) ;
i = i+1 ;
}

Condition Controlled loop


char ans = y;
while (ans == y && ans == Y)
{

printf(Enter students details);


.......
Printf(Do you want to submit another student details);
Scanf(%c,&ans);

}
....
....
Printf(Great!!);

The for Loop


The for allows us to specify three things about a loop in a
single line:
Setting a loop counter to an initial value.
Testing the loop counter to determine whether its value has
reached the number of repetitions desired.
Increasing the value of loop counter each time the program
segment within the loop has been executed.

The general format for a for loop


for (Initialization_action; Condition; Condition_update)
{
statement_list;
}

/* Calculation of simple interest for 3 sets of p, n and r */


main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
}
}

The general format for a for loop


1

for (Initialization_action; Condition; Condition_update)


{
statement_list;
}
Factorial of n is

n(n-1)(n-2)...21

int n,f=1;
Printf(ENter a number to find factorial);
scanf(%d,&n);
for (i=2; i<=n; i++)
{
f *= i;
}
printf(The factorial of %d is %d ,n,f);

Compare: for and while


1

for (Initialization_action; Condition; Condition_update)


{
statement_list;
}

int n,f=1;
cin >> n;
for (i=2; i<=n; i++)
{
f *= i;
}

i=2;
while (i<=n)
{
f *= i;
i++;
}

printf(The factorial of %d is %d ,n,f);


63

int n,i;

int n,i;

n = 100;

n = 100;
i = 1;

for (i=1; i <= n; i+


+)
{
statement_list;
}

v.s.

while (i <= n)
{
statement_list;
i++;
}

64

The comma operator

We can give several statements separated by commas in


place of Initialization, condition, and updating.

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


fact = fact * i;
for (sum=0, i=1; i<=N, i++)
sum = sum + i * i;

do-while
do
{

printf(Will you pass this exam?);


scanf(%c,&ans);
} while (ans != Y);

Statement
list

Condition

printf(Great!!);

do
{

Statement list
} while (Condition);
; is required
66

Example 1: do-while
int i;
....
do
{
printf( Please input a number between 10 and 20:;
printf(%d,i);
} while (i < 10 || i > 20);
......

67

Suppose your Rs 10000 is earning interest at 1% per month. How many months until you double
your money ?
my_money=10000.0;
n=0;
while (my_money < 20000.0) {
my_money = my_money*1.01;
n++;
}
printf (My money will double in %d months.\n,n);

Break and Continuein a loops


break

The
statement in a for loop will force the
program to jump out of the for loop immediately.

continue

The
statement in a for loop will force the
program to update the loop condition and then
check the condition immediately.

for (Initialization_action; Condition; Condition_update)


{
statement_list;
}
69

Nested loops (loop in loop)


b

printf(%d%d,a,b);

*************
*************
*************
*************

for (int i = 0; i < a; i++)


{
for (int j=0; j<b; j++)
{
printf(*);
}
}

70

Nested loops (2)


b

int a,b;
Printf(Enter two values);
scanf(%d%d,&a,&b);
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
if (j > i)
break;
printf(*);
}
}

*
**
***
****

Nested loops (3)


b

int a,b;
Printf(Enter two values);
scanf(%d%d,&a,&b);

*
**
***
****

if (j > i) break;

for (int i = 0; i < a; i++)


{
for (int j=0; j<b && j <
<=i;
i; j++)
{
printf(*);
}
}
72

Nested loops (4)


a

int a,b;

*************
************
***********
**********

cin >> a >> b;


for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
if (j < i)
printf( );
else
printf(*);
}
}

73

Nested loops (5)

int a,i,j;
scanf(%d,a);

*
***
*****
*******
*********
***********

for (i = 0; i < a; i++) {


for (j=0; j<a; j++) {
if (j < a-i)
printf(" ");
else printf("*");
}
for (j=0; j<a; j++) {
if (j > i) break;
printf("*");
}
}

74

Break in a loop
break

The
statement in a loop will force the
program to jump out of the loop immediately.

do
{

r = p % i;
if (r == 0) break;
i++;
} while (i < p);
do {
printf(Will you pass this exam?);
scanf(%c,&ans);
if (ans == y || ans == Y) break;
} while (ans != Y && ans != y);
cout << Great!!;
75

Continue in a loop
continue

The
statement in a loop will force the
program to check the loop condition immediately.

do {
printf(Will you pass this exam?);
scanf(%c,&ans);
if (and != Y && ans != y) continue;
printf(Great?);
break;
} while (true);
....
76

Example 5: SUM = 12 + 22 + 32 +...+ N2


int main () {
int N, count, sum;
printf(Enter limit of series)
scanf (%d, &N) ;
sum = 0;
count = 1;
while (count <= N)
{
sum = sum + count*count;
count = count + 1;
}
printf (Sum = %d\n, sum) ;
return 0;
}

Evaluate Sine Series: sin x = x - ((x^3)/3!) + ((x^5)/5!) - ..


1.
2.
3.
4.
5.
6.
7.
8.

Declare variables i,n,j integers ;x, t,s,r as float


Input and read the limit of the sine series,n.
Input and read the value of angle(in degree),x.
Convert the angle in degree to radian,x=((x*3.1415)/180)
Assign t=r and s=r.
Initialize i as 2.
Initialize j as 2.
while(j<=n) repeat the steps a to d.
a)Find t=(t*(-1)*r*r)/(i*(i+1))
b)Find s=s+t
c)Increment i by 2.
d)Increment j by 1.
9. End while.
10. Print the sum of the sine series,s.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,j,ch;
float x,t,s,r;
printf("\nENTER THE LIMIT");
scanf("%d",&n);
printf("\nENTER THE VALUE OF x:");
scanf("%f",&x);
r=((x*3.1415)/180);
t=r;
s=r;
i=2;
for(j=2;j<=n;j++)
{
t=(t*(-1)*r*r)/(i*(i+1));
s=s+t;
i=i+2;
}
printf("\nSUM OF THE GIVEN SINE SERIES IS %4f",s);

Specifying Infinite Loop

Formatted output
%d (print as a decimal integer)
%6d (print as a decimal integer with a width of at least 6 wide)
%f (print as a floating point)
%4f (print as a floating point with a width of at least 4 wide)
%.4f (print as a floating point with a precision of four characters after
the decimal point)
%3.2f (print as a floating point at least 3 wide and a precision of 2)

You might also like