[go: up one dir, main page]

0% found this document useful (0 votes)
30 views24 pages

Computing Fundamentals: Dr. Muhammad Yousaf Hamza

The document discusses the conditional operator and switch statement in C programming. It explains that the conditional operator allows embedding an if statement into an expression in a compact form. The switch statement provides a convenient way to write a large decision tree where decisions depend on the value of the same variable, compared to nested if-else statements. Examples are given to demonstrate the basic syntax and usage of conditional operator and switch statement.

Uploaded by

Danish Zahoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views24 pages

Computing Fundamentals: Dr. Muhammad Yousaf Hamza

The document discusses the conditional operator and switch statement in C programming. It explains that the conditional operator allows embedding an if statement into an expression in a compact form. The switch statement provides a convenient way to write a large decision tree where decisions depend on the value of the same variable, compared to nested if-else statements. Examples are given to demonstrate the basic syntax and usage of conditional operator and switch statement.

Uploaded by

Danish Zahoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Computing Fundamentals

Dr. Muhammad Yousaf Hamza


Deputy Chief Engineer, PIEAS
Conditional Operator

Dr. Yousaf, PIEAS


Conditional Operator
if ( a < b)
c = a + 5;
else
c = b + 8;

// We can do this in compact form as


c = a < b ? a + 5 : b + 8; //Ternary conditional operator (?:)
Evaluate first expression. If true, evaluate second,
otherwise evaluate third.

Dr. Yousaf, PIEAS


Conditional Operator
• Ternary conditional operator (?:)

– Takes three arguments (condition, value if true,


value if false)

– Our pseudocode could be written:


grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );

Dr. Yousaf, PIEAS


Conditional Operator

• The conditional operator essentially allows you to embed an


“if” statement into an expression
• Generic Form
exp1 ? exp2 : exp3 if exp1 is true
value is exp2
(exp3 is not evaluated)
if exp1 is false,
value is exp3
(exp2 is not evaluated)
Dr. Yousaf, PIEAS
Conditional Operator
• Example:
z = (x > y) ? x : y;
• This is equivalent to:
if (x > y)
z = x;
else
z = y;

Dr. Yousaf, PIEAS


switch statement

Dr. Yousaf, PIEAS


// No use of switch statement
// use of if-else
#include <stdio.h>
int main()
{
int day;
printf("The day number 1 means Monday\n");
printf("Please enter the number of day. \n The number must be
any integer value from 1 to 7\n");
scanf("%d",&day);
if (day == 1)
printf("Monday\n");
else if (day == 2)
printf("Tuesday\n");
else if (day == 3)
printf("Wednesday\n");
// You may complete it yourself
Dr. Yousaf, PIEAS
The if/else Selection Structure
Nested if/else structures
• In previous example, the nested if/else structure is
to be used.
• Test for multiple cases by placing if/else selection
structures inside if/else selection structures
• Deep indentation usually not used in practice
• How can we solve this example more conveniently?

• switch statement is a convenient way to code it.

Dr. Yousaf, PIEAS


Switch Statement
If you have a large decision tree, and all
the decisions depend on the value of
the same variable, you will probably
want to consider a switch statement
instead of a ladder of if...else or else if
constructions.

Dr. Yousaf, PIEAS


// Example of switch statement
#include <stdio.h>
int main()
{
int day;
printf("The day number 1 means
Monday\n");
printf("Please enter the number of day. \n
The number must be any integer value from
1 to 7\n");
scanf("%d",&day);
// Contd. (next page)
Dr. Yousaf, PIEAS
switch(day)
{
case 1: // 1 is one of possible value of day and so on.
printf("Monday\n");
break;
case 2:
printf("Tuesday\n"); break;
// please write cases 3 to 6 yourself
case 7:
printf("Sunday\n");
break;
default:
printf(“You eneterd a wtong number. The number must be an
integer value from 1 to 7\n");
}
getchar(); return 0;
}
Dr. Yousaf, PIEAS
Example of switch statement
#include <stdio.h> case -2:
int main()
{ printf(“I am very smart”);
int num; break;
printf(“Enter an integer from -5 // Write cases -1 to 9 yourself
to 9”) ;
scanf(“ %d”, &num) default:
switch(num) printf(“Default value is:
{ %d", num);
case -5:
printf(“PIEAS is Beautiful"); }
break; getchar();
case -4: return 0;
printf(“CFP is my favorite
subject”); }
break;
case -3:
printf(“I am studying at the
University”);
break;
Dr. Yousaf, PIEAS
Example of switch statement
#include <stdio.h> case 1:
int main()
{ printf(“I am very smart”);
int num; break;
printf(“Enter an integer from -5 // Write cases 2 to 7 yourself
to 4”) ;
scanf(“ %d”, &num) default:
switch(num+3) printf(“Default value is:
{ %d", num);
case -2:
printf(“PIEAS is Beautiful"); }
break; getchar();
case -1: return 0;
printf(“CFP is my favorite
subject”); }
break;
case 0:
printf(“I am studying at
University”);
break;
Dr. Yousaf, PIEAS
• switch
– Useful when a variable or expression is tested for
all the values which can happen and different
actions are taken
• Format
– Series of case labels and an optional default case
switch ( value )
{
case 1:
actions
break
case 2:
actions
break
default:
actions
} Dr. Yousaf, PIEAS
The switch Structure
• Flowchart of the switch structure
true case a break
case a
action(s)
false
true case b break
case b
false action(s)

.
.
.
true case z break
case z
false action(s)

default
action(s)
Dr. Yousaf, PIEAS
switch Statement
• The expression used in a switch statement must have an integral or
character type.
• You can have any number of case statements within a switch. Each case
is followed by the value of decision variable to be compared and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a integer or a characheter.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. 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 appears 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.

Dr. Muhammad Yousaf Hamza


switch Statement
• Case doesn’t always need to have order 1, 2, 3 and so on. They can have
any integer value after case keyword. Also, case doesn’t need to be in an
ascending order always, you can specify them in any order as per the
need of the program.
• The expression provided in the switch should result in an integer value
otherwise it would not be valid.
• Nesting of switch statements are allowed, which means you can have
switch statements inside another switch. However nested switch
statements should be avoided as it makes program more complex and
less readable.
• Duplicate case values are not allowed.
• The default statement is optional, if you don’t have a default in the
program, it would run just fine without any issues. However it is a good
practice to have a default statement so that the default executes if no
case is matched. This is especially useful when we are taking input from
user for the case choices, since user can enter wrong value, we can
remind the user with a proper error message that we can set in the
default statement. Dr. Muhammad Yousaf Hamza
switch Statement
• An expression must always execute to a result.
• Case labels must be constants and unique.
• Case labels must end with a colon ( : ).
• There can be only one default label.
• switch is a decision making construct in 'C.'
• A switch is used in a program where multiple decisions are
involved.
• A switch must contain an executable test-expression.
• Case label must be constants and unique.
• The default is optional.
• Multiple switch statements can be nested within one
another.

Dr. Muhammad Yousaf Hamza


Example of switch statement
#include <stdio.h> case 'c':
int main() printf("Case C");
{ break;
char ch='b'; case 'z':
switch (ch) printf("Case Z ");
{ break;
case 'd': default:
printf("Case D ");
printf("Default ");
break;
case 'b': }
printf("Case B"); getchar();
break; return 0;
}

Dr. Yousaf, PIEAS


Example of switch statement
#include <stdio.h> // write case ‘-’ Yourself
int main() case ‘*’:
{
char operator;
printf(“%d*%d=%d”,num1,num2,
int num1,num2; num1*num2);
printf(“\n Enter the operator (+, -, break;
*, /):”); case ‘/’:
scanf(“%c”,&operator); printf(“%d / %d =
printf(“\n Enter the Two
numbers:”);
%d”,num1,num2,num1/num2);
scanf(“%d%d”,&num1,&num2); break;
switch (operator) default:
{ printf(“\n Enter the operator
case ‘+’: only”);
printf(“%d+%d=%d”,num1,num2,n break;
um1+num2);
break;
}
getchar(); return 0; }
Dr. Yousaf, PIEAS
Calculator using switch statement
Develop a C code that asks the user to select
the option for maths operation (+,-,*,/,%,sqrt
etc) then ask the user to enter the numbers and
display the result.

Do it Yourself

Dr. Yousaf, PIEAS


In the following a C program is written. It contains
BUGS. ENCIRCLE the bugs. You don’t need to write
them in correct form.
$ include (stdio.h) x=2+
int main () 3;
a+1;
int a, b, x, time_in_minutes, 7distance, b = c;
y; printf(“If I solve wisely, this paper is
int weight in kilogram, sum; easy\n’)
j = 7; x = 9 + (j = 10+11);
scanf(“%d”,a); sum = sum + x;
scanf(“%f”,b); y + = 7;
ptintf(“%d:, y);
printf{“What are you doing?\n”}; g = (a)(a)(a); // it calculates cube of a
time_in_minutes = 53
7distance = 23; getchre();
printf(“The result is %d, ” add_result); Return0;
printf(“ENTER Time in Minutes”);
scanf(“%d”, time_in_minutes)
length = 100;
In the following a C program is written. It contains
BUGS. ENCIRCLE the bugs. You don’t need to write
them in correct form.

You might also like