Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

UNit 2 Conditional Operator and Control Statements

Uploaded by

Priyanka Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

UNit 2 Conditional Operator and Control Statements

Uploaded by

Priyanka Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

KCA102 Conditional Operator and Control Statements

Session 2022-23
Conditional Operator
C offers a special type of operator for decision making, also known as ternary operator which
is the conditional operator ( ?: in combination) to construct conditional expressions.

Operator Description
? : Conditional Expression
If an expression contains a condition
-relational operators
-logical operator
Conditional operators return
 one value if condition is true and
 returns another value is condition is false.

This operator is also called as ternary operator.


Syntax:
(Condition? true_value: false_value);

Flow chart for Conditional Operator


Example :
Let A=5
B=7
Big= A>B?A:B
Where if True than ?A and if False than : B
if A is greater than 200, 0 is returned else 1 is returned. This is equal to if else conditional
statements.
#include <stdio.h>
int main()
{
int a=10, b ;
b = ( a >=10 ? 1 : 0 ) ;
printf("a value is %d\n", a);// output 10
printf("b value is %d", b);// output 1
}

include <stdio.h>
int main()
{
int a, b, max ;
printf(“\n Enter any Two numbers”);
scanf(“%d%d”, &a, &b);
max = ( a>b ?a :b ) ;
printf("Max value is %d\n", max);
}

include <stdio.h>
int main()
{
int a, b, c, max ;
printf("\n Enter any Three numbers");
scanf("%d%d%d", &a, &b,&c);
max = ( (a>b&&a>c)?a:(b>c?b:c)) ;// Conditional Operator with logical &
// max = ( a>b?(a>c?a:c):(b>c?b:c));// Nested of Conditional Operator
printf("Max value is %d\n", max);
}
include <stdio.h>
int main()
{
int a, b, c, max ;
printf("\n Enter any Three numbers");
scanf("%d%d%d", &a, &b,&c);
// max = ( (a>b&&a>c)?a:(b>c?b:c)) ;// Conditional Operator with logical &
max = ( a>b?(a>c?a:c):(b>c?b:c));// Nested of Conditional Operator
printf("Max value is %d\n", max);
}
Control Statements in C
To control the Execution flow of statements in a program/programming languages uses
control statements.
1. Conditional Statements
a. Decision Making statements
Decision making where a condition id given to decide which statement or block of
statements will be executed for required actions
 if Statement,
 if...else statement
 Nested if (If with-in if, If.. else…with-in If else)
b. Branching
Selection statement are used to make one-time decisions in C Programming, that is, to
execute some code/s and ignore some code/s depending upon the test expression.
 switch statement
c. Looping (or) Iterative statements
Looping is deciding how many times to take a certain action.
 for loop
 do while loop
 while loop
2. Unconditional jumping
 goto statement (No or Low use of goto statement in structured/Modular
Programming Approach)
 IF STATEMENT: In if statement, a given condition is evaluated and it executes only true
block of statement(s)
Syntax
if(condition)
True statement; //if condition is true than a statement to be executed

If(condition)
{ // if condition is true than block of statements to be executed
Statement 1;
Statement 1;
Statement 1;

}

Example
Age=?
if(age>=18)
printf(“ you are eligible to vote”);

Note if there is only one statement no need to use being and end ‘{‘ ‘}’ or if more
than one statements or a block of statements then {}will be used
 if else statement in C programming language it is used to execute a set of statements if
condition is true and execute another set of statements when condition is false.
Only either if block or else block of code gets executed (not both) depending on the
outcome of condition.
Syntax:
if
(condition_expression)
{
statements; //code to be execute if the condition_expression is true
}
else
{
statements; //code to be execute if the condition_expression is false
}

 Nested if else statement : In C programming language, if we use further an if.else statement


within an if or else block than we call is nested if..else statement
 It is used to execute a set of statements if condition is true and further evaluates the inner
condition and similarly for else clock also .
Only either if block or else block of code gets executed (not both) depending on the
outcome(True/false) of condition.
Syntax:
if
(condition_expression)
Outer {
//statement

if(condition)
{ statements; //code to be execute if the condition_expression is true

} Inner
if else
else
{

}
}
else
{
statements; //code to be execute if the condition_expression is false

if(condition)
{ statements; //code to be execute if the condition_expression is true

} Inner else
if else
else
{

Example
Age=?
if(age>=18)
{
printf(“ you are eligible to vote”); // if condition true this statement will be executed

}
else // if condition false, this statement will be executed
{
printf(“ Sorry, you are not eligible to vote”);
}
#include <stdio.h>
int main()
{
int a, b, max;
printf("\n Enter any two numbers");
scanf("%d%d", &a, &b);
if(a>b)
max=a;
else
max=b;
printf("\n Max. out of two numbers %d",max);
}
find max out of 3 numbers
Algorithm1
Step 1: declare three variables
step 2: read the value of three variables
step 3: compare var1 and var2 and find max out of these two
step 4: compare big out of two with var3 and find max out of three
step 5: display the max value

Start

Declare three Variables as

A, B, C

Read value of
A, B, and C

False
Ture
Big=B Ma=A
If A>B

False
Max=C
If max>C

Ture

Display max

Stop
Now lets try to make alteration in Algorithm
Step 1: read any three values in three variables
step 2: compare var1 and var2 find max
step 3: compare max with var3 and move bigger value to max
step 4: display the max value

The if else statement checks whether condition_expression is true or false.


If the condition_expression is true, then the block of code inside the if statement is executed
but if condition_expression is false, then the block of code inside the else statement is
executed.

Not:e Both if and else block of statements can never execute at a time.

Flow chart of if Else

Program to show use of If Else Control Statement


#include<stdio.h>
int main()
{
int sub_marks;
printf("Enter your Marks : ");
scanf("%d", &marks);
if(marks < 40){
printf("You Failed :(\n");
}
else {
printf("Congrats You Passed :)\n");
}
}
Find max out of Three
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("\n Enter any two numbers");
scanf("%d%d%d", &a, &b,&c);
if(a>b)
{
if (a>c)
max=a;
else
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
printf("\n Max. out of two numbers %d",max);
}
Find Max number out of Three
include <stdio.h>
int main()
{
int a, b, c, max;
printf("\n Enter any tthree numbers");
scanf("%d%d%d", &a, &b,&c);
if(a>b&&a>c)
max=a;
else
if(b>c)
max=b;
else
max=c;
printf("\n Max. out of two numbers %d",max);
}
Check Alphabet
#include <stdio.h>
int main() {
char character;
printf("Enter a Character\n");
scanf("%c", &character);
if((character >= 'a' && character <= 'z')||(character >= 'A' && character <= 'Z')){
printf("%c is an Alphabet\n", character);
} else {
printf("%c is Not an Alphabet\n", character);
}

return 0;
}

#include <stdio.h>
int main(){
char c;
printf("Enter a Character: ");
scanf("%c", &c);

/* Check if input alphabet is member of set{A,E,I,O,U,a,e,i,o,u} */

if(c == 'a' || c == 'e' || c =='i' || c=='o' || c=='u' || c=='A'


|| c=='E' || c=='I' || c=='O' || c=='U'){
printf("%c is a Vowel\n", c);
} else {

printf("%c is a Consonant\n", c);


}
getch();
return 0;
}
WAP to Check Leap Year
void main(){
int year;
printf("Enter a year for leap year check\n");
scanf("%d", &year);
/* if (year is not divisible by 4) then (it is a common year)
* else if (year is not divisible by 100) then (it is a leap year)
* else if (year is not divisible by 400) then (it is a common year)
* else (it is a leap year)
*/
if(year%4 != 0){
printf("%d is not a leap year\n", year);
} else {
if(year%100 == 0){
if ( year%400 == 0){
printf("%d is a leap year\n", year);
} else {
printf("%d is not a leap year\n", year);
}
} else {
printf("%d is a leap year\n", year );
}
}
switch Case Statement in C (Branching/ Selection Control Statement)
switch statement allows a variable/ Expression to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch
case.
Rules apply to a switch statement −
 The expression used in a switch statement must have an integer or a char type (Single
Char value)/literal,
 Any number of case statements within a switch are allowed. Each case is followed by
the value to be compared to and a colon.
 constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
 variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 a break statement is used to terminate the case, and the flow of control jumps to the
next line following the switch statement.
 Break is not mandatory to use with every case. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true.
 No break is needed in the default case.
What If else laddr
Day= 1-7
If Day= 1
Study COA
Else
If Day= 2
Study C prog
Else
If Day = 3
Study DM
…..
If Day = 7
Do Relex

Example 1
#include <stdio.h>
int main()
{
int n1, n2, result;
char ch[]="*";
printf(" \n Enter any two numbers");
scanf("%d%d",&n1,&n2);
printf(" \n Enter any operator to perform airthematic Operation +, -, *, /, ");
scanf("%c",&ch);
switch(ch)
{
case '+' : { result= n1+n2;
printf("\n Sum of Two numbers = %d", result);
break;
}
case '-' : {
result= n1-n2;
printf("\n Substraction of Two numbers = %d", result);
break;
}
case '*' : {
result= n1*n2;
printf("\n multiplication of Two numbers = %d", result);
break;
}

case '/': {
result= n1*n2;
printf("\n division = %d", result);
break;
}
default: printf("\n Case not matched ");
}
}
Example 2
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Example 3: Print Appreciation on grade entered by user

int main ()
{
char grade;

switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}

LOOPING (Repeated Execution- execute again and again until the given condition
becomes false )
A loop is a conditional Control statement
 A Loop executes the sequence of statements as many number of times until the stated
condition becomes false.
 loop consists of two parts,
 a body of a loop : What to repeat { }
 a control statement. Condition to begin Repetition or terminate the repetition
 control statement is a combination of some conditions that direct the body of the loop
to execute until the specified condition becomes false.
 The purpose of the loop is to repeat the same code a number of times.
1. Entry controlled loop (Like while loop or for loop): In an entry controlled loop, a
condition is checked before executing the body of a loop. It is also called as a pre-checking
loop.

2. Exit controlled loop (like do while loop): In an exit controlled loop, a condition is
checked after executing the body of a loop. It is also called as a post-checking loop.

Prerequisite for Looping


 Initialization happens and the counter variable gets initialized.
 Specifying Condition that is checked to control the repetition,
like the counter variable is tested for the given condition, if the condition returns true then the
C statements inside the body of for loop gets executed, if the condition returns false then the
for loop gets terminated and the control comes out of the loop.
 Counter variable is incremented or decremented, depending on the operation (++ or –

Types of Loops in C Lang


Three types of Looping Statements used in C,
1. for loop (pre-defined number of times to repeat is known in Advance)
 for repeating the execution fixed number of times and
 the terminal condition is known in advance
Syntax
for(initialization of counter; counter Condition; counter increment or decrement)
{
// body of the loop statement which you want to repeat
}
Counter is used to count the repetition
Print your name 5 times
Int counter;
Char name[]=”John”
for(counter=1;counter<=5;counter++) // Control Statement
{
printf(“\n My name is ”);
printf(“\t %s ”,name);
}
void main()
{
int counter,num;
for(counter=1, counter<=15;counter++)
{
num=counter*counter
printf(“%d ”, num)
}

Task print 1 5 times


11
22
33
44

Using for loop


for(c=1,d=1;c<=5&&d<=5;c++,d++)
{
printf(“%d %d”,c,d);
}

2. while loop: Entry Condition Controlled loop


it checks condition first and if given condition is true than body of loop will be executed
otherwise loop will be terminated.
It may be possible that loop will not execute even once
syntax
Initialization
while(condition)//control statement
{
// body of loop
}

//int counter//initialization before looping


while(counter>=5)// Control Statement
{
printf(“My name is John”);
counter++; //counter increment/decrement in the body of loop
}

3. do while loop Exit Condition Controlled loop


do-while loop continues until a given condition satisfies.
It is also called post tested loop.
used when it is necessary to execute the loop at least once
Syntax
It executes first the body of loop and then checks condition.
So this loop will execute at least once
do
{
// code to be executed repeatedly
} while(condition);

Woking with loops

Let number = 17
Table 5

Logic 5*1 =5 7*1=7 17*1=17

5*2=10 7*2=14 17* 2=34

5*3=15 7*

5*4=20

5*5=25
5*6=30
5*7=35
5*8=40
5*9= 45
5*10=50

Seq 1-10

for(seq=1;seq<=10;seq++)//control statement repeating the


{
Tablevalue= Number * seq
prinft(“\n %d * %d = %d”,number, seq,tablevalue);

Program to print table for the given number


#include main()
{
int seq, num,tval;
printf("Enter a number: ");
scanf("%d",&num);
for(seq=1;seq<=10;seq++)
{
tvalue=num*seq;
printf("\n %d", t);

}
}

Using While loop


while(c<=10)
{
t=number*c;
printf("%d \n", t);
c=c+1;
}

1
12
123
1234
12345
123456
**************************************************************************
*****/

#include <stdio.h>

int main()
{
int r, c;
for(r=1;r<=6;r++)
{
printf("\n");

for (c=1;c<=r;c++)
{
printf("%d ",c);
}
}

}
col1 col2
Row1- >1 2 3 4 5 6
Row2- >12345
1234
123
12
1
#include <stdio.h>

int main()
{

int r, c;
int n;
printf("\n Enter no of rows");
scanf("%d",&n);

for(r=n; r>=1; r--)


{ printf("\n");
for (c=1;c<=r;c++)
{
printf("%d ",c);
}
}

You might also like