0% found this document useful (0 votes)
19 views31 pages

Module 2

Uploaded by

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

Module 2

Uploaded by

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

Module:2

Control and loop statements


Contents
• Control statements:
• if, if-else, if-else ladder, elseif ladder.
• switch.
• Loops:
• do-while, while.
• for loops and nested loops.
• Break, continue, goto and exit statements.
• Programs on if, switch and loops.

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

• In the program statement


if ( count > COUNT_LIMIT )
printf ("Count limit exceeded\n");

• 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

• The if-else is actually just an extension of the


general format of the if statement.
• If the result of the evaluation of expression is
TRUE, program statement 1, which
immediately follows, is executed; otherwise,
program statement 2 is executed.
• In either case, either program statement 1 or
program statement 2 is executed, but not both.
BECE320E MODULE 2 6
Program to Determine if a Number Is Even or
Odd
#include <stdio.h>
int main ()
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2;
if ( remainder == 0 )
printf ("The number is even.\n");
else
printf ("The number is odd.\n");
return 0;
} BECE320E MODULE 2 7
Determining if a Year Is a Leap Year
// Program to determines if a year is a leap year
#include <stdio.h>
int main (void)
{
int year, rem_4, rem_100, rem_400;
printf ("Enter the year to be tested: ");
scanf ("%i", &year);
rem_4 = year % 4;
rem_100 = year % 100;
rem_400 = year % 400;
if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 ) //Compound Relational Tests
printf ("It's a leap year.\n");
else
printf ("Nope, it's not a leap year.\n");
return 0;
}
BECE320E MODULE 2 8
BECE320E MODULE 2 9
Nested if Statements (if-else Ladder Statement)

• 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

• C programming language contains three different program


statements for program looping.
• They are known as
• the for statement,
• the while statement, and
• the do statement.

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;
}

o/p: The eighth triangular number is 36

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

You might also like