Module 2
Module 2
BECE320E MODULE 2 2
Decision-making constructs
• The if statement
• The switch statement
• The conditional operator
BECE320E MODULE 2 3
The if Statement
• The general format of this statement is as follows:
if ( expression )
program statement
• the printf statement is executed only if the value of count is greater than the
value of COUNT_LIMIT; otherwise, it is ignored.
BECE320E MODULE 2 4
// Program to calculate the absolute value of an integer
int main (void)
{
int number;
printf ("Type in your number: ");
scanf ("%i", &number);
if ( number < 0 )
number = -number;
printf ("The absolute value is %i\n", number);
return 0;
}
BECE320E MODULE 2 5
if-else construct
if ( expression )
program statement 1
else
program statement 2
• Syntax:
if (test condition 1)
{
if (test condition 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
statement x;
BECE320E MODULE 2 10
The else if Construct
BECE320E MODULE 2 11
// Program to implement the sign
function
#include <stdio.h>
int main (void)
{
int number, sign;
printf ("Please type in a number: ");
scanf ("%i", &number);
if ( number < 0 )
sign = -1;
else if ( number == 0 )
sign = 0;
else // Must be positive
sign = 1;
printf ("Sign = %i\n", sign);
return 0;
} BECE320E MODULE 2 12
Conditional Expression -or- The Ternary Operator
• The conditional expression can be used as a shorthand for some if-else statements.
• The general syntax of the conditional operator is:
<expression1> ? <expression2> : <expression3>
• This is an expression, not a statement, so it represents a value.
• The operator works by evaluating expression1. If it is true (non-zero), it evaluates and
returns expression2 . Otherwise, it evaluates and returns expression3.
• The classic example of the ternary operator is to return the smaller of two variables.
• Every once in a while, the following form is just what you needed.
• Instead of... • You just say...
if (x < y) { min = (x < y) ? x : y;
min = x; }
else {
min = y; }
BECE320E MODULE 2 13
/* Program to evaluate simple expressions of the form
value operator value */
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.\n");
scanf ("%f %c %f", &value1, &operator, &value2);
if ( operator == '+’ )
printf ("%.2f\n", value1 + value2);
else if ( operator == '-’ )
printf ("%.2f\n", value1 - value2);
else if ( operator == '*’ )
printf ("%.2f\n", value1 * value2);
else if ( operator == '/’ )
if ( value2 == 0 )
printf ("Division by zero.\n");
else
printf ("%.2f\n", value1 / value2); Note: in this example, value of a variable is
else successively compared against different
printf ("Unknown operator.\n"); values
return 0;
BECE320E MODULE 2 14
}
The switch Statement
General format: • The expression enclosed within parentheses is successively
switch ( expression )
{ compared against the values value1, value2, ..., valuen,
case value1: which must be simple constants or constant expressions.
program statement • If a case is found whose value is equal to the value of
program statement expression, the program statements that follow the case are
...
break;
executed.
case value2: • Note that when more than one such program statement is
program statement included, they do not have to be enclosed within braces.
program statement • The break statement signals the end of a particular case and
...
causes execution of the switch statement to be terminated.
break;
... • Remember to include the break statement at the end of
case valuen: every case.
program statement • Forgetting to do so for a particular case causes program
program statement execution to continue into the next case whenever that case
...
break;
gets executed.
default: • The special optional case called default is executed if the
program statement value of expression does not match any of the case values.
break; BECE320E MODULE 2 15
}
#include <stdio.h> case '*':
int main (void) printf ("%.2f\n", value1 * value2);
{ break;
float value1, value2; case '/':
char operator; if ( value2 == 0 )
printf ("Type in your expression.\n"); printf ("Division by zero.\n");
scanf ("%f %c %f", &value1, &operator, else
&value2); printf ("%.2f\n", value1 / value2);
switch (operator) break;
{ default:
case '+': printf ("Unknown operator.\n");
printf ("%.2f\n", value1 + value2); break;
break; }
case '-': return 0;
printf ("%.2f\n", value1 - value2); }
break; cond_switch.c
BECE320E MODULE 2 16
LOOPING STATEMENTS
BECE320E MODULE 2 17
for LOOP
Consider the scenario of Calculating the Eighth Triangular Number. In general it can be programmed as follows:
#include <stdio.h>
int main (void)
{ for_loop1.c
int triangularNumber;
triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;
printf ("The eighth triangular number is %i\n",
triangularNumber);
return 0;
}
BECE320E MODULE 2 18
• In case if we need to calculate the 200th triangular number using the above
program it becomes more complex.
• for loop makes this simple.
#include <stdio.h>
int main (void)
{
int n, triangularNumber; // syntax:
for ( init_expression; loop_condition; loop_expression )
triangularNumber = 0;
for ( n = 1; n <= 200; n = n + 1 )
triangularNumber = triangularNumber + n;
printf ("The 200th triangular number is %i\n", triangularNumber);
return 0;
}
BECE320E MODULE 2 19
• The first component of the for statement, labeled init_expression, is used to set the initial values
before the loop begins
• an assignment is a valid form of an expression
• The second component of the for statement the condition or conditions that are necessary for the
loop to continue
• the loop_condition of the for statement is specified by the following relational expression
• The final component of the for statement contains an expression that is evaluated each time after
the body of the loop is executed
• Relational operators:
BECE320E MODULE 2 20
Write a Program to generate a table of triangular numbers.
#include <stdio.h>
int main (void)
{
int n, triangularNumber;
printf ("TABLE OF TRIANGULAR NUMBERS\n\n");
printf (" n Sum from 1 to n\n");
printf ("--- ---------------\n");
triangularNumber = 0;
for ( n = 1; n <= 10; ++n ) {
triangularNumber += n;
printf (" %i %i\n", n, triangularNumber);
}
return 0;
}
for_loop2.c
BECE320E MODULE 2 21
//Getting input from the user for_loop3.c
#include <stdio.h>
int main (void)
{
int n, number, triangularNumber;
printf ("What triangular number do you want? ");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
printf ("Triangular number %i is %i\n", number, triangularNumber);
return 0;
}
BECE320E MODULE 2 22
Nested for Loops
Let us consider that if the user has a list of five triangular numbers to be calculated, then nested loops can
be used.
#include <stdio.h>
int main (void)
{
int n, number, triangularNumber, counter;
for ( counter = 1; counter <= 5; ++counter ) {
printf ("What triangular number do you want? ");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
printf ("Triangular number %i is %i\n\n", number, triangularNumber);
}
return 0; nested_for.c
}
BECE320E MODULE 2 23
for Loop Variants
• Multiple Expressions
for ( i = 0, j = 100; i < 10; ++i, j = j - 10 )
...
• Omitting Fields
for ( ; j != 100; ++j )
...
• Declaring Variables
for ( int counter = 1; counter <= 5; ++counter )
BECE320E MODULE 2 24
The while Statement
• Syntax:
while ( expression )
program statement
• The expression specified inside the parentheses is evaluated.
• If the result of the expression evaluation is TRUE, the program statement that immediately
follows is executed.
• Execution of the program then continues with the statement that follows the program statement
// Program to introduce the while statement
#include <stdio.h>
int main (void)
{
int count = 1;
while ( count <= 5 ) {
printf ("%i\n", count);
++count;
} while1.c
return 0;
}
BECE320E MODULE 2 25
for ( init_expression; loop_condition; loop_expression )
program statement
init_expression;
while ( loop_condition ) {
program statement
loop_expression;
}
BECE320E MODULE 2 26
Write a Program to find the greatest common divisor (GCD)of two nonnegative
integer values.
Algorithm:
Step 1: If v equals 0, then you are done and the gcd is equal to u.
Step 2: Calculate temp = u % v, u = v, v = temp, and go back to step 1.
#include <stdio.h>
int main (void)
{
int u, v, temp;
printf ("Please type in two nonnegative integers.\n");
scanf ("%i%i", &u, &v);
while ( v != 0 ) {
temp = u % v;
u = v;
v = temp;
}
printf ("Their greatest common divisor is %i\n", u); while2.c
return 0;
}
BECE320E MODULE 2 27
• Write a Program to reverse the digits of a number. while_reverse.c
#include <stdio.h>
int main (void)
{
int number, right_digit;
printf ("Enter your number.\n");
scanf ("%i", &number);
while ( number != 0 ) {
right_digit = number % 10;
printf ("%i", right_digit);
number = number / 10;
}
printf ("\n");
return 0;
}
BECE320E MODULE 2 28
The do Statement
• a test of the conditions before the loop is executed.
• Therefore, the body of the loop might never be executed at all if the conditions are not satisfied.
• it sometimes becomes desirable to have the test made at the end of the loop rather than at the
beginning. • Execution of the do statement proceeds as follows:
The syntax of this statement is as • The program statement is executed first.
follows: • Next, the loop_expression inside the parentheses is
do
program statement evaluated.
while ( loop_expression ); • If the result of evaluating the loop_expression is TRUE,
the loop continues and the program statement is once
again executed.
• As long as evaluation of the loop_expression continues
to be TRUE, the program statement is repeatedly
executed.
• When evaluation of the expression proves FALSE, the
loop is terminated, and the next statement in the program
is executed in the normal sequential manner.
BECE320E MODULE 2 29
Write a Program to reverse the digits of a number.
dowhile.c
#include <stdio.h>
int main ()
{
int number, right_digit;
printf ("Enter your number.\n");
scanf ("%i", &number);
do {
right_digit = number % 10;
printf ("%i", right_digit);
number = number / 10;
}
while ( number != 0 );
printf ("\n");
return 0;
} BECE320E MODULE 2 30
• break
• continue
BECE320E MODULE 2 31