[go: up one dir, main page]

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

ICP Reference Material

The document discusses input/output operations, decision making, and looping in C programming. It covers the differences between formatted and unformatted input/output functions. Formatted functions allow input/output in a user-defined format while unformatted functions do not. Examples of each type of function are given. Decision making in C can be done with if, if-else, nested if-else statements, else-if ladders, switch statements, and the ?: operator. The structures and syntax of each method are described. Looping can be done with while, do-while, and for statements. Jumps in loops are also mentioned. Example programs are provided to demonstrate various input/output,

Uploaded by

Dimon He
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)
33 views24 pages

ICP Reference Material

The document discusses input/output operations, decision making, and looping in C programming. It covers the differences between formatted and unformatted input/output functions. Formatted functions allow input/output in a user-defined format while unformatted functions do not. Examples of each type of function are given. Decision making in C can be done with if, if-else, nested if-else statements, else-if ladders, switch statements, and the ?: operator. The structures and syntax of each method are described. Looping can be done with while, do-while, and for statements. Jumps in loops are also mentioned. Example programs are provided to demonstrate various input/output,

Uploaded by

Dimon He
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

UNIT-II

UNIT-II 06 Hours
Managing Input and Output Operations: Formatted and Unformatted input and output statements,
Example programs.
Decision making and Branching: Decision making with if, if-else, Nesting of if-else statements, else-if
ladders, switch statement, ?: Operator, goto statement, Example programs.
Decision making and Looping: while statement, do-while statement, for statement, jumps in loops, Example
programs.

Managing Input / Output operations: Formatted and Unformatted input and output statements, Example
programs.

Input output functions in C programming falls into two categories, namely, formatted input output (I/O)
functions and unformatted input output (I/O) functions. In this article we will point out major differences
between them:

Difference between Formatted and Unformatted Functions


Formatted I/O functions allow to supply input or display output in user desired format.
Unformatted I/O functions are the most basic form of input and output and they do not allow to supply input
or display output in user desired format.

printf() and scanf() are examples for formatted input and output functions.
getch(), getche(), getchar(), gets(), puts(), putchar() etc. are examples of unformatted input output
functions.

Formatted input and output functions contain format specifier in their syntax.
Unformatted input and output functions do not contain format specifier in their syntax.

Formatted I/O functions are used for storing data more user friendly.
Unformatted I/O functions are used for storing data more compactly.

Formatted I/O functions are used with all data types.


Unformatted I/O functions are used mainly for character and string data types.

Formatted I/O Example:


#include<stdio.h>
#include<conio.h>

void main()
{
int a;
clrscr();
printf(“Enter value of a:”);
scanf(“%d”, &a);
printf(“ a = %d”, a);
getch();
}
Unformatted I/O Example:
#include<stdio.h>
#include<conio.h>

void main()
{
char ch ;
clrscr();
printf(“Press any character:”);
ch = getche();
printf(“\nYou pressed :”);
putchar(ch);
getch();
}

C - Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is determined to be false.

Decision making statements allow you to decide the order of execution of specific statements in your
program. You can set up a condition and tell the compiler to take a particular action if the condition is met.
In case the condition is not met, you can instruct the compiler to execute a different block of code.

Show below is the general form of a typical decision making structure found in most of the programming
languages −

C programming language assumes any non-zero and non-null


Decision making is about deciding the order of execution of statements based on certain conditions or repeat
a group of statements until certain specified conditions are met. C language handles decision-making by
supporting the following statements,
 if statement (and different forms of if, like, if-else, if-else ladder and Nested if-else)

 switch statement

 conditional operator statement (? : operator)

 goto statement

Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of conditions to be
tested. The different forms are,

1. Simple if statement

2. if....else statement

3. Nested if....else statement

4. Using if else if statement

Simple if statement

The general form of a simple if statement is,

if(expression)
{
statement inside;
}
statement outside;

If the expression returns true, then the statement-inside will be executed, otherwise statement-inside is
skipped and only the statement-outside is executed.
Example:

#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}

output
x is greater than y

if...else statement

The general form of a simple if...else statement is,

if(expression)
{
statement block1;
}
else
{
statement block2;
}
If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and statement-
block2 is executed.
Example:

#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output
y is greater than x

Nested if....else statement

The general form of a nested if...else statement is,

if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}

if expression is false then statement-block3 will be executed, otherwise the execution continues and enters
inside the first if to perform the check for the next if block, where if expression 1 is true the statement-
block1 is executed otherwise statement-block2 is executed.
Example:

#include <stdio.h>

void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}

if else if ladder

The general form of else-if ladder is,

if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

The expression is tested from the top(of the ladder) downwards. As soon as a true condition is found, the
statement associated with it is executed.
Example :

#include <stdio.h>

void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}

Points to Remember

1. In if statement, a single statement can be included without enclosing it into curly braces { ... }

int a = 5;
if(a > 4)
printf("success");

1. No curly braces are required in the above case, but if we have more than one statement
inside if condition, then we must enclose them inside curly braces.
2. == must be used for comparison in the expression of if condition, if you use = the expression will
always return true, because it performs assignment not comparison.

3. Other than 0(zero), all other values are considered as true.

if(27)
printf("hello");

In above example, hello will be printed.


Switch statement in C

When you want to solve multiple option type problems, for example: Menu like program, where one value is
associated with each option and you need to choose only one at a time, then, switch statement is used.

Switch statement is a control statement that allows us to choose only one choice among the many given
choices. The expression in switch evaluates to return an integral value, which is then compared to the values
present in different cases. It executes that block of code which matches the case value. If there is no match,
then default block is executed (if present). The general form of switch statement is,

switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
}

Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value i.e the expression should be an
integer or a variable or an expression that evaluates to an integer.

2. The case label values must be unique.

3. The case label must end with a colon(:)

4. The next line, after the case statement, can be any valid C statement.
Points to Remember

1. We don't use those expressions to evaluate switch case, which may return floating point values or
strings or characters.

2. break statements are used to exit the switch block. It isn't necessary to use break after each block, but
if you do not use it, then all the consecutive blocks of code will get executed after the matching block.

int i = 1;
switch(i)
{
case 1:
printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
}

Output
ABC

1. The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it a break statement in
encountered or the execution reaches the end of the switch block.
2. default case is executed when none of the mentioned case matches the switch expression. The default
case can be placed anywhere in the switch case. Even if we don't include the default
case, switch statement works.

3. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch block. However, nested switch statements should be avoided as it makes the program
more complex and less readable.

Example of switch statement

#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}

Difference between switch and if

if statements can evaluate float conditions. switch statements cannot evaluate float conditions.

if statement can evaluate relational operators. switch statement cannot evaluate relational operators i.e they
are not allowed in switch statement.

Conditional Operator in C (?: Operator)

The conditional operator is also known as a ternary operator. The conditional statements are the decision-
making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?'
and ':'. As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement.

Syntax of a conditional operator

Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:


Meaning of the above syntax.

In the above syntax, the expression1 is a Boolean condition that can be either true or false value.

If the expression1 results into a true value, then the expression2 will execute.

The expression2 is said to be true only when it returns a non-zero value.

If the expression1 returns false value then the expression3 will execute.

The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.

#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable

// usage of conditional operator


(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}

In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the
condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of
the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting"))
otherwise, statement2 will execute, i.e., (printf("not eligible for voting")).

As we know that the behavior of conditional operator and 'if-else' is similar but they have some
differences. Let's look at their differences.

A conditional operator is a single programming statement, while the 'if-else' statement is a programming
block in which statements come under the parenthesis.
A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement
cannot be used for the assignment purpose.

It is not useful for executing the statements when the statements are multiple, whereas the 'if-else' statement
proves more suitable when executing multiple statements.

The nested ternary operator is more complex and cannot be easily debugged, while the nested 'if-else'
statement is easy to read and maintain.

goto statement,

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

A goto statement in C programming provides an unconditional jump from the 'goto' to a labelled statement in
the same function.

NOTE − Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to modify.
Any program that uses a goto can be rewritten to avoid them.

Syntax
The syntax for a goto statement in C is as follows −
goto label;
...

...

Here label is an valid C identifier and it can be set anywhere in the C program above or below
to goto statement.
Flow Diagram

Let's understand the goto statement through an example.

/*To print numbers from 1 to 10 using goto statement*/


#include <stdio.h>
int main()
{
int number;
number=1;

repeat:
printf("%d\n",number);
number++;

if(number<=10)
goto repeat;

return 0;
}
Loops in C

In any programming language including C, loops are used to execute a set of statements repeatedly until a
particular condition is satisfied.

How it Works, The below diagram depicts a loop execution,

As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the
execution breaks out of the loop. After the loop is successfully executed the execution again starts from the
Loop entry and again checks for the Test condition, and this keeps on repeating.

The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After
every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed
again. When the condition check returns false, the loop body is not executed, and execution breaks out of the
loop.
Types of Loop

There are 3 types of Loop in C language, namely:

1. while loop

2. do while loop

3. for loop

while loop

while loop can be addressed as an entry control loop. It is completed in 3 steps.

 Variable initialization.(e.g int x = 0;)

 condition(e.g while(x <= 10))

 Variable increment or decrement ( x++ or x-- or x = x + 2 )

Syntax :

variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}

Output
1 2 3 4 5 6 7 8 9 10

do while loop

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can
be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end,
the condition is checked using while statement. It means that the body of the loop will be executed at least
once, even though the starting condition inside while is initialized to be false. do while loop can be addressed
as an exit control loop. General syntax is,

do
{
.....
.....
}
while(condition)
Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}

5 10 15 20 25 30 35 40 45 50
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.

Syntax, The syntax of a for loop in C programming language is –

for ( init; condition; increment )


{
statement(s);
}

Here is the flow of control in a 'for' loop −

The init step is executed first, and only once. This step allows you to declare and initialize any loop control
variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the
loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.

After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of
loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop
terminates.

Flow Diagram

#include <stdio.h>

int main () {

int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}

return 0;
}

When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Nested for loop

We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,

for(initialization; condition; increment/decrement)


{
for(initialization; condition; increment/decrement)
{
statement ;
}
}

Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}

1
21
321
4321
54321

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as
soon as certain condition becomes true. This is known as jumping out of loop.

1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the program continues
with the statement immediately following the loop.

2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On
encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates

#include <stdio.h>

int main()
{
int i;
double number, sum = 0.0;

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


{
printf("Enter n%d: ", i);
scanf("%lf", &number);

if (number < 0.0) // if the user enters a negative number, break the loop
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
Output

Enter n1: 2.4


Enter n2: 4.5
Enter n3: 3.4
Enter n4: -3
Sum = 10.30

// Program to calculate the sum of numbers (10 numbers max)


// If the user enters a negative number, it's not added to the result

#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 (number < 0.0)


{
continue;
}
sum += number; // sum = sum + number;
}

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

return 0;
}

Reference Sites
https://www.tutorialspoint.com
https://www.studytonight.com
https://www.cprogramming.com
https://www.programiz.com

You might also like