C – Unit II

UNIT 2: CONTROL STRUCTURES

 

2.1 DATA INPUT OUTPUT FUNCTIONS

 

Input means to provide the program with some data to be used in the program and Output means to display data on screen or write the data to a printer or a file.

C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result.

In this tutorial, we will learn about such functions, which can be used in our program to take input from user and to output the result on screen.

All these built-in functions are present in C header files, we will also specify the name of header files in which a particular function is defined while discussing about it.

 

scanf() and printf() functions

 

The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

 

#include<stdio.h>

 

void main()

{

// defining a variable

int i;

/*

displaying message on the screen

asking the user to input a value

*/

printf(“Please enter a value…”);

/*

reading the value entered by the user

*/

scanf(“%d”, &i);

/*

displaying the number as output

*/

printf( “\nYou entered: %d”, i);

}

 

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered on screen.

 

You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is known as format string and this informs the scanf() function, what type of input to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect.

 

Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.

 

We can also limit the number of digits or characters that can be input or output, by adding a number with the format string specifier, like “%1d” or “%3s”, the first one means a single numeric digit and the second one means 3 characters, hence if you try to input 42, while scanf() has “%1d”, it will take only 4 as input. Same is the case for output.

 

In C Language, computer monitor, printer etc output devices are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.

 

NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it.

int i = printf(“studytonight”);

In this program printf(“studytonight”); will return 12 as result, which will be stored in the variable i, because studytonight has 12 characters.

 

getchar() & putchar() functions

 

The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. You can use this method in a loop in case you want to read more than one character. The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time. In case you want to display more than one characters, use putchar() method in a loop.

 

#include <stdio.h>

 

void main( )

{

int c;

printf(“Enter a character”);

/*

Take a character as input and

store it in variable c

*/

c = getchar();

/*

display the character stored

in variable c

*/

putchar(c);

}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.

 

 

gets() & puts() functions

 

The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes the string str and a trailing newline to stdout.

 

str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not able to understand this now.)

#include<stdio.h>

 

void main()

{

/* character array of length 100 */

char str[100];

printf(“Enter a string”);

gets( str );

puts( str );

getch();

}

 

When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.

 

Difference between scanf() and gets()

 

The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too.

 

If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part after space. But gets() function will read it completely.

 

 

 

2.2 SIMPLE C PROGRAMS

 

Program to Display “Hello, World!”

 

#include <stdio.h>

int main()

{

// printf() displays the string inside quotation

printf(“Hello, World!”);

return 0;

}

 

Output

 

Hello, World!

 

Program to Print an Integer

 

#include <stdio.h>

int main()

{

int number;

 

// printf() dislpays the formatted output

printf(“Enter an integer: “);

 

// scanf() reads the formatted input and stores them

scanf(“%d”, &number);

 

// printf() displays the formatted output

printf(“You entered: %d”, number);

return 0;

}

Output

 

Enter a integer: 25

You entered: 25

 

Program to Add Two Integers

 

#include <stdio.h>

int main()

{

int firstNumber, secondNumber, sumOfTwoNumbers;

 

printf(“Enter two integers: “);

 

// Two integers entered by user is stored using scanf() function

scanf(“%d %d”, &firstNumber, &secondNumber);

 

// sum of two numbers in stored in variable sumOfTwoNumbers

sumOfTwoNumbers = firstNumber + secondNumber;

 

// Displays sum

printf(“%d + %d = %d”, firstNumber, secondNumber, sumOfTwoNumbers);

 

return 0;

}

 

Output

 

Enter two integers: 12

11

12 + 11 = 23

 

 

2.3 FLOW OF CONTROL

 

Every procedural language provides statements for determining the flow of control within programs. Although declarations are a type of statement, in C the unqualified word statement usually refers to procedural statements rather than declarations. In this chapter we are concerned only with procedural statements.

 

In the C language, statements can be written only within the body of a function; more specifically, only within compound statements. The normal flow of control among statements is sequential, proceeding from one statement to the next. However, as we shall see, most of the statements in C are designed to alter this sequential flow so that algorithms of arbitrary complexity can be implemented. This is done with statements that control whether or not other statements execute and, if so, how many times. Furthermore, the ability to write compound statements permits the writing a sequence of statements wherever a single, possibly controlled, statement is allowed. These two features provide the necessary generality to implement any algorithm, and to do it in a structured way.

 

2.4 IF

 

if (testExpression)

{

// statements

}

 

The if statement evaluates the test expression inside the parenthesis.

 

If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.

If the test expression is evaluated to false (0), statements inside the body of if is skipped from execution.

 

To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check out relational and logical operators.

 

Flowchart of if statement

 

// Program to display a number if user enters negative number

 

// If user enters positive number, that number won’t be displayed

 

#include <stdio.h>

int main()

{

int number;

 

printf(“Enter an integer: “);

scanf(“%d”, &number);

 

// Test expression is true if number is less than 0

if (number < 0)

{

printf(“You entered %d.\n”, number);

}

 

printf(“The if statement is easy.”);

 

return 0;

}

 

Output 1

Enter an integer: -2

You entered -2.

The if statement is easy.

 

When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is displayed on the screen.

 

Output 2

Enter an integer: 5

The if statement in C programming is easy.

 

When user enters 5, the test expression (number < 0) becomes false and the statement inside the body of if is skipped.

 

2.5 IF-ELSE

 

The if…else statement executes some code if the test expression is true (nonzero) and some other code if the test expression is false (0).

 

Syntax of if…else

 

if (testExpression) {

// codes inside the body of if

}

else {

// codes inside the body of else

}

 

If test expression is true, codes inside the body of if statement is executed and, codes inside the body of else statement is skipped.

 

If test expression is false, codes inside the body of else statement is executed and, codes inside the body of if statement is skipped.

 

Flowchart of if…else statement

 

// Program to check whether an integer entered by the user is odd or even

 

#include <stdio.h>

int main()

{

int number;

printf(“Enter an integer: “);

scanf(“%d”,&number);

 

// True if remainder is 0

if( number%2 == 0 )

printf(“%d is an even integer.”,number);

else

printf(“%d is an odd integer.”,number);

return 0;

}

 

Output

 

Enter an integer: 7

7 is an odd integer.

 

When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the statement inside the body of else statement printf(“%d is an odd integer”); is executed and the statement inside the body of if is skipped.

 

2.6 WHILE

 

The syntax of a while loop is:

while (testExpression)

{

//codes

}

where, testExpression checks the condition is true or false before each loop.

 

How while loop works?

 

The while loop evaluates the test expression.

If the test expression is true (nonzero), codes inside the body of while loop are exectued. The test expression is evaluated again. The process goes on until the test expression is false.

When the test expression is false, the while loop is terminated.

Flowchart of while loop

 

// Program to find factorial of a number

// For a positive integer n, factorial = 1*2*3…n

 

#include <stdio.h>

int main()

{

int number;

long long factorial;

 

printf(“Enter an integer: “);

scanf(“%d”,&number);

 

factorial = 1;

 

// loop terminates when number is less than or equal to 0

while (number > 0)

{

factorial *= number;  // factorial = factorial*number;

–number;

}

 

printf(“Factorial= %lld”, factorial);

 

return 0;

}

 

Output

Enter an integer: 5

Factorial = 120

 

2.7 DO WHILE

 

he do..while loop is similar to the while loop with one important difference. The body of do…while loop is executed once, before checking the test expression. Hence, the do…while loop is executed at least once.

 

do

{

// codes

}

while (testExpression);

 

How do…while loop works?

 

The code block (loop body) inside the braces is executed once.

 

Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).

 

When the test expression is false (nonzero), the do…while loop is terminated.

 

// Program to add numbers until user enters zero

 

#include <stdio.h>

int main()

{

double number, sum = 0;

 

// loop body is executed at least once

do

{

printf(“Enter a number: “);

scanf(“%lf”, &number);

sum += number;

}

while(number != 0.0);

 

printf(“Sum = %.2lf”,sum);

 

return 0;

}

 

Output

 

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70

 

2.8 FOR LOOP

 

The syntax of for loop is:

for (initializationStatement; testExpression; updateStatement)

{

// codes

}

 

How for loop works?

 

The initialization statement is executed only once.

 

Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated.

 

This process repeats until the test expression is false.

The for loop is commonly used when the number of iterations is known.

To learn more on test expression (when test expression is evaluated to nonzero (true) and 0 (false)), check out relational and logical operators.

 

for loop Flowchart

 

// Program to calculate the sum of first n natural numbers

// Positive integers 1,2,3…n are known as natural numbers

 

#include <stdio.h>

int main()

{

int num, count, sum = 0;

 

printf(“Enter a positive integer: “);

scanf(“%d”, &num);

 

// for loop terminates when n is less than count

for(count = 1; count <= num; ++count)

{

sum += count;

}

 

printf(“Sum = %d”, sum);

 

return 0;

}

 

Output

 

Enter a positive integer: 10

Sum = 55

 

2.9 NESTED CONTROL STRUCTURES

 

The if…else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if…else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

 

Syntax of nested if…else statement.

if (testExpression1)

{

// statements to be executed if testExpression1 is true

}

else if(testExpression2)

{

// statements to be executed if testExpression1 is false and testExpression2 is true

}

else if (testExpression 3)

{

// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true

}

.

.

else

{

// statements to be executed if all test expressions are false

}

 

// Program to relate two integers using =, > or <

 

#include <stdio.h>

int main()

{

int number1, number2;

printf(“Enter two integers: “);

scanf(“%d %d”, &number1, &number2);

 

//checks if two integers are equal.

if(number1 == number2)

{

printf(“Result: %d = %d”,number1,number2);

}

 

//checks if number1 is greater than number2.

else if (number1 > number2)

{

printf(“Result: %d > %d”, number1, number2);

}

 

// if both test expression is false

else

{

printf(“Result: %d < %d”,number1, number2);

}

 

return 0;

}

 

Output

 

Enter two integers: 12

23

Result: 12 < 23

 

2.10 SWITCH

 

The switch statement is often faster than nested if…else (not always). Also, the syntax of switch statement is cleaner and easy to understand.

 

Syntax of switch…case

switch (n)

​{

case constant1:

// code to be executed if n is equal to constant1;

break;

 

case constant2:

// code to be executed if n is equal to constant2;

break;

.

.

.

default:

// code to be executed if n doesn’t match any constant

}

 

When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered.

The break statement is used to prevent the code running into the next case.

 

switch Statement Flowchart

 

// Program to create a simple calculator

// Performs addition, subtraction, multiplication or division depending the input from user

 

# include <stdio.h>

 

int main() {

 

char operator;

double firstNumber,secondNumber;

 

printf(“Enter an operator (+, -, *, /): “);

scanf(“%c”, &operator);

 

printf(“Enter two operands: “);

scanf(“%lf %lf”,&firstNumber, &secondNumber);

 

switch(operator)

{

case ‘+’:

printf(“%.1lf + %.1lf = %.1lf”,firstNumber, secondNumber, firstNumber+secondNumber);

break;

 

case ‘-‘:

printf(“%.1lf – %.1lf = %.1lf”,firstNumber, secondNumber, firstNumber-secondNumber);

break;

 

case ‘*’:

printf(“%.1lf * %.1lf = %.1lf”,firstNumber, secondNumber, firstNumber*secondNumber);

break;

 

case ‘/’:

printf(“%.1lf / %.1lf = %.1lf”,firstNumber, secondNumber, firstNumber/secondNumber);

break;

 

// operator is doesn’t match any case constant (+, -, *, /)

default:

printf(“Error! operator is not correct”);

}

 

return 0;

}

 

Output

 

Enter an operator (+, -, *,): –

Enter two operands: 32.5

12.4

32.5 – 12.4 = 20.1

 

2.11 BREAK

 

The break statement terminates the loop (for, while and do…while loop) immediately when it is encountered. The break statement is used with decision making statement such as if…else.

 

Syntax of break statement

 

break;

 

The simple code above is the syntax for break statement.

 

 

 

Flowchart of break statement

 

How break statement works?

 

 

 

// Program to calculate the sum of maximum of 10 numbers

// Calculates sum until user enters positive number

 

# include <stdio.h>

int main()

{

int i;

double number, sum = 0.0;

 

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

{

printf(“Enter a n%d: “,i);

scanf(“%lf”,&number);

 

// If user enters negative number, loop is terminated

if(number < 0.0)

{

break;

}

 

sum += number; // sum = sum + number;

}

 

printf(“Sum = %.2lf”,sum);

 

return 0;

}

 

Output

 

Enter a n1: 2.4

Enter a n2: 4.5

Enter a n3: 3.4

Enter a n4: -3

Sum = 10.30

 

This program calculates the sum of maximum of 10 numbers. It’s because, when the user enters negative number, the break statement is executed and loop is terminated.

 

2.12 CONTINUE

 

The continue statement skips some statements inside the loop. The continue statement is used with decision making statement such as if…else.

 

Syntax of continue Statement

 

continue;

 

Flowchart of continue Statement

 

 

 

How continue statement works?

 

// Program to calculate sum of maximum of 10 numbers

// Negative numbers are skipped from calculation

 

# include <stdio.h>

int main()

{

int i;

double number, sum = 0.0;

 

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

{

printf(“Enter a n%d: “,i);

scanf(“%lf”,&number);

 

// If user enters negative number, loop is terminated

if(number < 0.0)

{

continue;

}

 

sum += number; // sum = sum + number;

}

 

printf(“Sum = %.2lf”,sum);

 

return 0;

}

 

Output

 

Enter a n1: 1.1

Enter a n2: 2.2

Enter a n3: 5.5

Enter a n4: 4.4

Enter a n5: -3.4

Enter a n6: -45.5

Enter a n7: 34.5

Enter a n8: -4.2

Enter a n9: -1000

Enter a n10: 12

Sum = 59.70

 

In the program, when the user enters positive number, the sum is calculated using sum += number; statement.

 

When the user enters negative number, the continue statement is executed and skips the negative number from calculation.

 

2.13 GO TO

 

The goto statement is used to alter the normal sequence of a C program.

Syntax of goto statement

 

goto label;

… .. …

… .. …

… .. …

label:

statement;

The label is an identifier. When goto statement is encountered, control of the program jumps to label: and starts executing the code.

 

// Program to calculate the sum and average of maximum of 5 numbers

// If user enters negative number, the sum and average of previously entered positive number is displayed

 

# include <stdio.h>

 

int main()

{

 

const int maxInput = 5;

int i;

double number, average, sum=0.0;

 

for(i=1; i<=maxInput; ++i)

{

printf(“%d. Enter a number: “, i);

scanf(“%lf”,&number);

 

// If user enters negative number, flow of program moves to label jump

if(number < 0.0)

goto jump;

 

sum += number; // sum = sum+number;

}

 

jump:

 

average=sum/(i-1);

printf(“Sum = %.2f\n”, sum);

printf(“Average = %.2f”, average);

 

return 0;

}

 

Output

 

  1. Enter a number: 3
  2. Enter a number: 4.3
  3. Enter a number: 9.3
  4. Enter a number: -2.9

Sum = 16.60

 

Reasons to avoid goto statement

 

The use of goto statement may lead to code that is buggy and hard to follow. For example:

one:

for (i = 0; i < number; ++i)

{

test += i;

goto two;

}

two:

if (test > 5) {

goto three;

}

… .. …

Also, goto statement allows you to do bad stuff such as jump out of scope.

That being said, goto statement can be useful sometimes. For example: to break from nested loops.

 

2.14 COMMA OPERATOR

 

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

 

The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

 

/* comma as an operator */

int i = (5, 10);  /* 10 is assigned to i*/

int j = (f1(), f2());  /* f1() is called (evaluated) first followed by f2().

The returned value of f2() is assigned to j */