Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

Managing I/O Operations

UNIT 2
. INPUT AND OUTPUT STATEMENTS
2.1.1. Introduction
C provides several functions that give different levels of input and output capability.
These functions are, in most cases, implemented as routines that call lower-level
input/output functions. The input and output functions in C are built around the concept
of a set of standard data streams being connected from each executing program to the
basic input/output devices.
These standard data streams or files are opened by the operating system and are
available to every C and assembler program to use without having to open or close the
files. These standard files or streams are called:
stdin Connected to the keyboard
stdout Connected to the screen
stderr Connected to the screen

The following two data streams are also available on


MS DOS-based computers, but not on UNIX or
other multi-user-based operating systems:
stdaux Connected to the first serial communication port
stdpm Connected to the first parallel printer port

A number of functions and macros exist to provide support for streams of various
kinds. The <stdio.h> header file contains the various declarations necessary for the
functions, together with the macros and type declarations needed for the input and
output functions.

2.12. Console Based I/O and Related Built-In I/O Functions


The console input/output functions fall into two categories:
1) Formatted read (input) and display (output) functions.
2) Un-formatted read (input) and display (output) functions, and

Figure 2.1: Console Input/Output Functions


2.1.2.1. Formatted Functions
The formatted input/output functions read and write all types of data values. They
require conversion symbol to identify the data type. Hence, they can be used for both
reading and writing of all data values.

The formatted functions return the values after execution. The return value is equal to
the number of variables successfully read/written. Using this value the user can find
out the errors occurring during reading or writing the data.

2.1.2.1.1. Formatted Input: scanf()


> Input data can be entered into computer from a standard input device by means of
the C library function scanf.
> It is a general purpose console input routine. It can read all built-in data types and
automatically convert numbers into proper internal format.
> The scanf function returns the number of data items successfully assigned a value.
If an error occurs, scanf returns EOF.

Syntax scanf(control string, argl, arg2,……arg n)

Where,
Control string determines how values are read into the variables pointed
to in the argument list.

The control string consists of three classifications of characters:


1) Format Specifiers: The input format specifiers are preceded by a % sign and
which tell scanf() about the type of data that is to be read next. The format
specifiers are matched, in order from left to right, with the arguments in the
argument list.
Code Meaning
%a Reads a floating-point value.
%c Reads a single character.
%d Reads a decimal integer.
%f Reads a floating-point number.
%s Reads a string.
%p Reads a pointer.
%n Receives an integer value equal to the number of characters read so far.

Inputting an Address
To input a memory address, use the %p format specifier. This specifier causes
scanf() to read an address in the format defined by the architecture of the CPU.

2) White Space Characters: A white-space character in the control string causes


scanfQ to skip over one or more leading white-space characters in the input
stream. A white-space character4s either a space, a tab, vertical tab, or a new-line.
3) Non-White-Space Characters in the Control String: A non-white-space
character in the control string causes scanf() to read and discard matching
characters in the input stream. For example, "%d, %d" causes scanf() to read an
integer, read and discard a comma, and then read another integer. If the specified
character is not found, scanf() terminates.

All the variables used to receive values through scanf() must be passed by their
addresses. All argument, i.e., must be pointers, which allows a function to alter the
contents of an argument. For example, to read an integer into the - variable count, the
following scanf() call is used:
scanf("%d", &count);

2.I.2.I.2. Formatted Output: printf()


> Output data can be written from the computer onto a standard output device using
the library function printf.
> This function can be used to output any combination of numerical values, single
characters and strings.
> The printf function moves data from the computer’s memory to the standard output
device.

Syntax
printf(control string, argl, arg2, ............ arg n)
Where control string refers to a string that contains formatting information, and argl,
arg2... arg n are arguments that represent the indivf&aal output data items. The
arguments can be written as constants, single variables or array names, or more
complex expressions. Function references may also be included.

Multiple character groups can be contiguous, or they can be separated by other


characters, including white space characters.

Program 1: /* Formatting through standard input and output*/


// Reading integers
#include<stdio.h>
#include<conio.h>
int main()
{
int a, b, c, d, e, f, g;
clrscr();
printf("Reading integers from standard input\n");
printf(" ------------ ------------ ------------ \n\n");
printf("Enter seven integers separated by space: ");
// scanf("%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g);
scanf("%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g);
printf("The input displayed as decimal integers is: \n");
printf("%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g);
// try different format specifier
printf("%d %\ %i %i %o %u %x\n", a, b, c, d, e, f, g);
getch();
}
Output

Reading integers from standard input


Enter seuen integers separated by space: 2 5 6 9 0 1 2
The input displayed as decimal integers is:
2 5 6 9 0 12 2 5 6 9 0 12

2.I.2.2. Unformatted Functions

The unformatted input/output functions only work with the character data type. They
do not require conversion symbol for identification of data types because they work
only with character data type. There is no need to convert the data. In case, values of
other data types are passed to these functions, they are treated as the character data.

The unformatted functions also return values, but the return value of unformatted
function is always the same.

Following are some unformatted functions.


1) gets() Function: This function accepts a string from the standard input device. The
length of the string is limited by the declaration of the string variable. The input
string may consist of multiple words. Typing Enter key completes the input.
Syntax
gets(variable_name);
2) getchar() Function: This function returns a character that has been recently typed.
The typed character is echoed to the computer screen. After typing the appropriate
character, the user is required to press Enter key.
Syntax
variable_name = getchar();
3) getche() Function: This function returns a character that has been recently typed.
The typed character is also echoed to the computer screen (‘e’ stands for echo). But
the user is not required to press the Enter key after typing a character. The
advantage of this function over getchar() function is that as soon as the user types a
character, the character is immediately accepted. In reduces the user’s action to
single key.

Syntax
variable_name = getche();
4) getch() Function: This function returns a character that has been recently typed.
But, neither the user is required to press Enter key after entering the character nor
the typed character is echoed to the computer screen. This function has advantages
over the other functions in the applications where the user wants to hide the input.
This input is usually the password used for system security.
Syntax
variable_name = getch();
5) putch() Function: They print a character on the screen. This helps the compiler in
single character output.
Syntax
putch(variable_name);
6) putchar() Function: This function outputs a character constant or a character
variable to the standard output device.
Syntax
putchar(variable_name);
7) puts()-Function: This function outputs a string constant or a string variable to the
standard output device.
Syntax
puts(variable_name);
Program 2: To illustrate the unformatted functions.
#include<stdio.h>
#include<conio.h>

void main()
{
char a[30];
gets(a);
puts(a);

getch();
}
Output
$ C:\Users\pravesh\Desktop\To\VIU.exe ^ ® ................................................... .... -

this is Thakur Publishers.
[his is Thakur Publishers. I

4 m : > 1
Explanation
1) #include<stdio.h> This header file is included because, the C in-built statements
gets and puts used in the program comes under stdio.h.
2) #include<conio.h> This header file is used because the C in-built function
getch() comes under conio.h header files.
3) mainO function is the place where C program execution begins.
4) Array a[] of type char size 30 is declared.
5) gets is used to receive the user input to the array, gets stops receiving user input
only when the Newline character (Enter Key) is interrupted.
6) puts is used to display them back in the console (monitor).
2.2. EXERCISE
Write a short note on Built-in Operators and’Functions.
2) Write the function for file handling^
3) Write the basic steps to processing a file.
4) Explain the formatted I/O.
5) What are unformatted functions?
1) Explain the following functions with a suitable example.
i) gets()
ii) puts()
iii) getch()

Flow of control in a program is to be handled carefully. Control flow relates to the


ordering of execution of statements in a program.
C has basically two types of control structures:
1) Selection or Branching
i) Decision Making Structure / Conditional Branching Statements
a) If
b) If-else
c) Switch
ii) Un-conditional Branching Statements/ Jump statements
a) Return
b) Break
c) Continue
d) Goto
2) Iteration or Loop Control Structure
i) For
ii) While
iii) Do-while
Control Statements/Constructs

Selection/Branching Iteration/Looping

I , . !

Conditional Type Unconditional Type


if if-else switch return break continue goto

Figure 3.1: Program Control Statements/Constructs in C

3.2. DECISION MAKING STRUCTURES

3.2.1. Introduction
C has various kinds of statements that permit the execution of a single statement, or
a block of statements, based on the evaluation of a test expression or permit the
selection of the statement to be executed among several statements based on the
value of an expression or a control variable.
Conditional branching and selection statements include constructs like:
1) if «.
2) if-else
3) if-else-if
4) switch

C supports two selection statements: if and switch. In addition, the “?” operator is an
alternative to if in certain circumstances.

3.2.2. if Statement
The general syntax and flowchart of the if statement is given below.
Syntax
if (expression)
{
statement;
}

Where, statement may consist of a


single statement, a block of statements, or nothing (in the case of empty statements).
The else clause is optional.

3.2.3. if-else Statement


If expression evaluates to true (anything other than 0), the statement or block that
forms the target of ‘if is executed; otherwise, the statement or block that is the target
of else will be executed, if it exists. Only the code associated with if or the code
associated with else executes, never both.

Syntax
if (expression)
{
statement;
}
else
{
statement;
}

<—

Flowchart
Program 1: /*To check the number as even or odd using if-else statement*/
#include<stdio.h>

#include<conio.h> •

void main()
{
int n; clrscr();
printf("Enter any number (which is to be checked as even or odd): );
scanf("%d", &n);
if (n%2==0) /* test for even*/
printf("%d number is even number",n);
else
printf("%d is an odd number" ,n);

getchQ;

°utPut — ufKMd

3.2.4. Nested if-else Statement


The ‘if block is called nested if the ‘if block itself contains another set of if statements.
The output of the innermost ‘if serves as the input of the next outermost and so on.

Flowchart
Program 2: /*To demonstrate nested else-if*/
#include<stdio.h>
#include<conio.h>
void main()
{
int units, custnum;
float charges;
clrscr();
printf("Enter customer number and units consumed\n");
scanf("%d %d", &custnum, &units);
if(units<=200)
charges=0.5*units;
else if(units<=400)
charges=100+.65* (units-200);
else if(units<=600)
charges=230+0.8*(units-400);
else
charges=390+(units-600);
printf( \n\n Customer No. %d: Charges=%.2f\n", custnum, charges)-
getch(); ’
}
Output
, . ^ gx
nter customer number and units consumed 671

Customer No.4: Charges=461.

3.2.5. Switch Statement


C has a built-in multiple-branch selection statement, called switch, which successively
tests the value of an expression against a list of integer or character constants. When a
match is found, the statements associated with that constant are executed until break or
end of switch is encountered.
Break statement interrupts the normal flow of control and then moves to the end of the
code or resumes to the normal execution. This is another form of the multiway decision.

The default statement is executed if no matches are found. The default is optional, and
if it is not present, no action takes place if all matches fail.
Syntax
switch (expression)
{
case constant l:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:

statement sequence

break;

default
statement sequence
}

Properties of Switch Statement


1) The ‘switch’ differs from ‘if because switch can only test for equality, whereas ‘if
can evaluate any type of relational or logical expression.
2) No two case constants in the same switch can have identical values. Of course, a
switch statement enclosed by an outer switch may have case
constants that are in common.
3) If character constants are used in the switch statement, they are automatically
converted to integers.
Program 3:
/*illustrating the switch statement.
#include <stdio.h>
#include<conio.h>
main()
{
int Grade = 'L';
switch( Grade)
{
case 'A' : printf( "Excellent\n");
break;
case 'B': printf( "Good\n");
break;
case 'C': printf( "Fine\n");
break;
case 'D': printf( "OK\n");
break;
case 'F : printf( "You must do better than this\n");
break;
default : printf( "What is your grade anyway?\n");
break;
}
getch();

Output
■ C:\Users\pravesh\Desktop\t\bftwi.,, ^ ®

3.3. LOOP CONTROL STRUCTURES


3.3.1. Introduction
A loop can be a pre-test loop or be a post-test loop:
1) Pre-Test Loop: In a pre-test loop, the condition is checked before the
beginning of each iteration. If the test expression evaluates to true, the
statements associated with the pre-test loop construct are executed and the
process is repeated till the test expression becomes false. On the other hand if
the test expression evaluates to false, the statements associated with the
construct are skipped and the statement next to the loop is executed. So for
such a construct, the statements associated with the construct may not be
executed even once.
2) Post-Test Loop: In the post-test loop, the code is always executed once. At the
completion of the loop code, the test expression is tested. If the test expression
evaluates to true, the loop repeats; if the expression is false the loop
terminates.
C has three loop constructs:
1) while,
2) for, and
3) do-while.

The first two are pre-test loops and do-while is a post-test loop. In the post-test loop,
the code is always executed once.

3.3.2. ‘for’ Loop


Allow a set of instructions to be repeatedly executed until a certain condition is
reached. This condition may be predetermined or open ended.

Syntax:
for (initialization; condition; increment) statement;

Figure 3.3: Flowchart of For Loop

Where,
1) Initialization: The first is a run before the loop is entered. This is usually the
initialization of the loop variable.
2) Condition: The second is a test, the loop is exited when this returns false.
3) Increment: The third is a statement to be run every time the loop body is
completed. This is usually an increment of the loop

The initialization is an assignment statement that is used to set the loop control
variable. The condition is a relational expression that determines when the loop
exits.
The ‘for’ loop continues to execute as long as the condition is true. Once the
condition becomes false, program execution resumes on the statement following the
for.
For example, consider the following loop that prints the numbers less than 3.
Expression 2(test expression)

Expression 1 (initialization) A
Expression 3(increment/update)

int 1; for(i=0;
i<3fi++)

printf(“%d”, i);

for keyword
Compound
statement

Program 4:/* illustrating for loop*/


#include <stdio.h>
#include <conio.h> main()
{
int i;
int j = 10;

for( i = 0; i <= j; i ++ )
{
printf("Hello %d\n", i);
}
getch();
}
Output
C:\UserAprevesh\Desktop\t\bitv vise.exe

3.3.3. Nested for Loops


A nested for loop is a loop within a loop, an inner loop within the body of an outer
one. How this works is that the first pass of the outer loop triggers the inner loop,
which executes to completion. Then the second pass of the outer * loop triggers the
inner loop again. This repeats until the outer loop finishes. A $reak within either the
inner or outer loop would interrupt this process. Consider the following program to
illustrate the concept of nested for loop.
Program 5: /*To Generate Multiplication Tables of a Range of Numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
For example, printing numbers less than or equal to 4.
int m, n, i, j, p;
clrscr();
printf("Enter Lower limit \n");
scanf("%d", &m);
printf("Enter Upper limit \n");
scanf("%d", &n);
for(i = m; i <= n; i++)
{
for(j = 1; j <= 10; j++)
{
P = i*j;
printf("%4d", p);
}
printf("\n");
}
getch();
}

Lout; r * I imit
Enter
5 Upper li mit
tnt e r
510 10 15 20 25 30 35 43 45 50
6 12 18 24 30 3& 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 2V 36. 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Output _____________________

3.3.4. ‘while’ Construct


While loop check the test condition at the top of the loop, which means that the body
of the loop will not execute if the condition is false to begin with. This feature may
eliminate, the need to perform a separate conditional test before the loop.

Syntax:
while(condition)
{
statements;
}

Figure 3.4: Flowchart of While Loop

For example, printing numbers less than or equal to 4


Test Expression

Here statement is an empty statement, a single statement, or a block of statements. The


condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true. When the condition becomes false, program control passes
to the line of code immediately following the loop.
For example, averaging a List of Numbers; A while statement is used here to calculate
the average of a list of n numbers. The strategy will be based on the use of a partial
sum that is initially set equal to zero, then updated as each new number is read into the
computer. Thus, the problem very naturally lends itself to the use of a while loop.
Working of while Loop
1) Assign a value of 1 to the integer variable count. This variable will be used as a
loop counter.
2) Assign a value of 0 to the floating-point variable sum.
3) Read in the value for the integer variable n.
4) Carry out the following steps repeatedly, as long as count does not exceed n.
i) Read in one of the numbers in the list. Each number will be represented by the
floating-point variable x.
ii) Add the value of x to the current value of sum.
iii) Increase the value of count by 1.
5) Divide the value of sum by n to obtain the desired average.
6) Write out the calculated value for the average.
Program 6: /*Illustrating while loop*/.
#include <stdio.h>
#include <conio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20)
{
printf("value of a: %d\n", a);
a++;
}
getch ();
}
For example, printing numbers less than or equal to 4.

Output _______________
m C:\Users\pravesh\De5 =. m ss

3.3.5. ‘do-while’ Loop

Unlike for and while loops, which test the loop condition at the top of the loop, the
do-while loop checks its condition at the bottom of the loop. This means that a do-
while loop always executes atleast once. The general form of the do-while loop is
given below:
Syntax:
do
{
statement;
} while(condition);

' Figure 3.5: Flowchart of do-while Loop

Although the curly braces are not necessary when only one statement is present, they
are usually used to avoid confusion with the while. The do-while loop iterates until
condition becomes false.
For example, consider the following loop that prints Heel three times.
do keyword

Compoun
d
statement

while
keyword
Program 7: /*Illustrating do-while statement*/
#include <stdio.h>
#include <conio.h>

int main ()
{
/* local variable definition */

int a = 10;

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a= a + 1;
}while( a < 20 );
getch();
}
Output
] CAUsers\pravssh\De: \ * ‘

3.4. JUMP STATEMENTS


There are certain control statements, which terminate either a loop or a function.
There are four such statements namely,
1) Return Statement,
2) Exit Statement,
3) Break Statement,
4) Continue Statement, and
5) Jump Statements.

3.4.1. Return Statement


The statement is written return expression; where the expression is optional. The
return causes a value to be returned from the current function to its caller. If the
expression is missing, then an unknown value is passed back to the caller - this is
almost certainly a mistake unless the function returns void.
For example, consider the following program:
For example, consider the following program:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
int b = 5;
a = fl(b);
printf("a=%d", a);
getch();
}
fl(al)
int al;
{
int a2;
a2 = 5 * al;
printf(”a2=%d", a2);
retum(a2);
}
The value of a2 is calculated in function fl() and is returned to the calling function using
retum() statement and hence output of program is:

C:/UsersV. f=i '~J


i2 =25 L=25

3.4.2. Exit Statement


exit() is used to exit the program as a whole. In other words it returns control to the
operating system.

The general form of exit statement is:

exit(int status);

After exit() all memory and temporary storage areas are all flushed-out and control goes
out of program. In contrast, the return() statement is used to return from a function and
return control to the calling function.

Also in a program there can be only one exit() statement but a function can have
number of return statements. In other words, there is no restriction on the number of
return statements that can be present in a function.
exit() statement is placed as the last statement in a program since after this program is
totally exited. In contrast return statement can take its presence anywhere in the
function. It need not be presented as the last statement of the function.

It is important to note that whenever a control is passed to a function and returns back,
some value gets returned. Only if one uses a return statement the correct value would
get returned from the called function to the calling function.

The difference between break and exit() is that the former terminates the execution of a
loop in which it is written, while exit() terminates the execution of the program itself.

3.4.3. Break Statement


This is a simple statement. It only makes sense if it occurs in the body of a switch, do,
while or for statement. When it is executed the control of flow jumps to the statement
immediately following the body of the statement containing the break.

Its use is widespread in switch statements, where it is more or less essential to get the
control that most people want.

The use of the break within loops is of dubious legitimacy. It has its moments, but is
really only justifiable when exceptional circumstances have happened and the loop has
to be abandoned. It would be nice if more than one loop could be abandoned with a
single break but that is not how it works.

Program 8: /*Illustration of break statement*/


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int i;
printf("checking the working of break statement\n");
printf("if the break statement is encountered then user window exits");
for(i = 0; i<l 00; i++)
{
if(getchar() == 's')
break;
printf("%d\n", i);
}
exit(0);
getch();
}
Explanation: It reads a single character from the program’s input before printing the
next in a sequence of numbers. If an ‘s’ is typed, the break causes an exit from the
loop.

3.4.4. Continue Statement


This statement has only a limited number of uses. The rules for its use are the same as
for break, with the exception that it does not apply to switch statements.
Executing a continue starts the next iteration of the smallest enclosing do, while or for
statement immediately. The use of continue is largely restricted to the top of loops,
where a decision has to be made whether or not to execute the rest of the body of the
loop.

If the body of the for loop is large then the continue statement is used to induce an
extra level of indentation and enhance readability. Program below illustrate the
concept of continue statement.

Program 9: /*Illustrating continue statement*/.


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

int main ()
{.
/* local variable definition */

int a = 10;

/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;

}while( a < 20 );

getch();
}

C:\U se rs\p ravesh\Des kto p\t\fas t’.vi» e. c=. @


..
ualue of a: 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
u a lue of a: ii
ualue of a: 12
yalue of a: 13
ualue of a:' 14'
ualue of a: 16
ualue of a- 17
ualue of a - IS
ualue of a: * 19

Output

3.4.5. goto Statements


It is used to alter the normal sequence of program execution by transferring control
to some other part of the program. The general syntax of the goto statement is,

goto LI;
/* whatever you like here */
LI: /* anything else */

A label is an identifier followed by a colon. Labels have their own ‘name space’ so
they cannot clash with the names of variables or functions. The name space only
exists for the function containing the label, so label names can be re-used in different
functions. The label can be used before it is declared, too, simply by mentioning it in
a goto statement.

Labels must be part of a full statement, even if it is an empty one. These usually ,
only matters when you are trying to put a label at the end of a compound statement.
For example, consider the following statement:

label_at_end: ; /* empty statement */


The goto works in an obvious way, jumping to the labeled statements. Because the
name of the label is only visible inside its own function, you cannot jump from one
function to another one.
Program 10: /*Illstrating Goto statement*/.
#ihclude <stdio.h> ’
#indude<conio.h>
int main ()
{
/* local variable definition */

int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20);

getch();
}
Output ____________
* C^Userc\pravesh\Deslctop\t\bitwise.exe ’_«=>. ED S3
alue of a: 10 ................................
alue of a: 11
alue of a: 12
alue of a: 13
alue of a: 14
alue of a: 16
alue of a: 17
alue of a: 18
alue of a: 19

|* rrr . . ►;
-V - -------------------------------------------------------------- -- ------
-------------------------------------------------------------------- ■
3.4.6. Difference between Break and Continue Statement
Table: Break Statement versus Continue Statement
Break Statement Continue Statement
1) Can be used in switch statement. 1) Cannot be used in switch statement.
2) Causes premature exit of the loop enclosing it. 2) Causes skipping of the statements following it in
the body of the loop.

3) The control is transferred to the statement 3) Control is transferred back to the loop.
following the loop.
4) The loop may not complete the intended 4) The loop completes the intended number of
number of iterations. iterations.

3.5. PROGRAMS
Program 11: /*To convert upper case to lower case or lower case to upper case
depending on the name it is invoked with as found in argument.*/
#include<stdio.h>
#include<conio.h>
void lower_to_upper();
void upper_to_lower();
void main()
{
int n;
clrscr();
printf("Please enter your choice.\n");
printf("\n");
printf("(l) for upper to lower conversion.\n");
printf("\n(2) for lower to upper conversion.\n");
printf("\nCHOICE:- \n");
scanf("%d", &n);
switch(n)
{
case 1:
{
printf("Please enter a string in upper caseAn");
{
printf("String will be terminated if you press Ctrl + ZAn");
printf("\n");
printf("\nSTRING:- \n");
upper_to_lower ();
break;
}
case 2:
{
printf("Please enter a string in lower case.");
printfO'String will be terminated if you press Ctrl-Z.");
printf(“STRING:- ");
lower_to_upper();
break;
}
default:
printf("ERROR");
}
printf("HAVE A NICE DAY!BYE.");
getch();
}
void upper_to_lower()
{
inti, j;
char c4[80], c3;
for(i=0; (c3=getchar())!=EOF; i++)
c4[i]=(c3>='A' && c3<='Z')?('a' + c3 -'A'):c3;
printf("The lower case equivalent is ");
for(j=0; j<i; j++)
putchar(c4[j]);
return;
}
void lower_to_upper()
{
inti, j;
char c2[80], cl;
for (i=0;(cl=getchar())!=EOF;i++)
c2[i]=(cl>=’a' && cl<='z')?('A' + cl -'a'):cl;
printf("The upper case equivalent is ");
for(j=0; j<i; j++)
putchar(c2[j]);
getch();
}
Output
J3 _ " ____ •{, "
ple^te enter, ^ojul^ \
|<1 ^Toi iQpper to 'JuiV ■ "Cjnuei*:, ICH.
i ^ .%*s.
(?) louer to u#^ier conuers.. jn.

Please enter a string in lower 2.SIRING: 11 he terninated if you press Ctrl-


thakur publications
AZ
The upper case equivalent i;,

HfiKUB I’llBLI GAT IONS ftUE Va.CE DAVf BVE.

Explanation: The code describes the switch case usage wounded with ‘for’ loop for
function calling of upper_to_lower and lower_to_upper.

Program 12: Check whether a number is a perfect number or not.


#include<stdio.h>
#include<conio.h>
int main(){
int num,i= 1 ,sum=0;

printf("Enter a number: ");

scanf(" %d",&num);

while(icnum){
if(num%i==0)
sum=sum+i;
i++;
}
if(sum==num)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);
getch();
return 0;
}

Output __________
«? C:\Dev-Cpp\Exair;

Enter a number: 6
6 is a perfect number
Program 13: /*Program for Prime Number Generation*/
J#inciude<stdio.h>
#include<conio .h> main()
{
int n, i=l, j,c;
clrscr();
printf("\nEnter Number Of Terms\n");
printf("NnPrime Numbers Are Following/n”);
scanf("%d", &n);
while(i<=n)
{
c=0;
for(j=l; j<=i; j++)
{
if(i%j==0)
C++;
}
if(c==2)
printf("%d ", i);
i++;
}
getch();

Output
Turbo f. - ID

Enter Number Of Terms


Prine Numbers Al - Following 2
3 5 ?

Program 14: /*Square root of a number without using Built-In Function*/


#include<stdio.h>
#include<conio.h>
void main()
{
double n, gl, g2;
int flag=0;
clrscr();
printf("\ncode to calculate the square root without inbuilt functio<i\n");
printf("\n");
printf("Enter the no.: ");
scanf("%lf',&n);
printf("\n");
if(n<0)
{
{
n=-n;
flag=l;
}
else if(n==0)
{
printf("The root of %6.41f is", n);
textcolor(GREEN);
cprintf(" %6.41f', g2);
getch();
exit(O);
}
g2=n/2;
do
{
gl=g2;
g2=(gl+n/gl)/2;
}
while((gl-g2)!=0);
if(flag==l)
{
printf("The root of %6.41f is", -n);
textcolor(GREEN);
cprintf(" +/- %6.41f i", g2);
}
else
{
printf("The root of %6.41f is", n);
textcolor(GREEN);
cprintff +/- %6.41f", g2);
}
getch();
}

Output

Explanation: Here the division method is used for the calculation of square root
function. Here the text is colored by using the inbuilt library function textcolour. The
nested if-else and do-while loops are used for the program control flow.
Program 15: Generate Armstrong number upto n.
#include<stdio.h>
#include<conio ,h>

int main()
{
int r;
long number = 0, c, sum = 0, temp;

printf("Enter the maximum range upto which you want to find armstrong
numbers ");
scanf(" %ld" ,&number);

printf("Following armstrong numbers are found from 1 to %ld\n",number);

for( c = 1 ; c <= number ; C++ )


{
temp = c; -
while( temp != 0 )
{
r = temp%10;
sum = sum + r*r*r;
temp = temp/10;
}
if ( c == sum )
printf("%ld\n", c);
sum = 0;
}

getch();
return 0;
}

Output ............ ...................... _____—. .r............... iv-T,


"■*—r ' ' “ ' ......... ... ......... ....... * ! : SJ jaaa&Pi
C.\Cev'C pp\Exan
p!es\VTU
Enter the maximum range upto which you want to find armstrong numbers 600 Following armstrong numbers are found tron 1 to L OAmstrong.exe
153
370
370 407

1i

' " .....................

Program 16: Sum of All numbers From n to m.


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

int main()
{
int m,n,c;
up:
printf("\n Enter Lower Range: ");
scanf("%d", &n);
printf("\n Enter Higher Range: ");
scanf("%d", &m);
if(n>=m){
printf("\nImproper Input\n");
goto up;
}
\ printf("What do you want:\n");
printf("l. Sum of All NumbersAn");
printf("2. Sum of All Odd Numbers:\n");
printf("3. Sum of All Even Numbers:\n");
printf("4. Exit:\n");

scanf("%d", &c);

switch(c)
{
case 1: All_sum(n,m);
break;
case 2: Odd_sum(n,m);
break;
case 3 : Even_sum(n,m);
break;
case 4 : exit(O);
}.
getch();
return 0;
}
//Sum of All Numbers

ALLsum(n,m)

int i,sum = 0;
for(i = n;i <= m ; i++)
{:
sum = sum + i;
}.

printf("\n Sum of all no between %d and %d is %d", n, m, sum);

}
//Sum of All Odd Numbers
Odd_sum(n,m)
{
int x3=n,x4=m,sum=0;
while(x3 <=×4){
if(x3 % 2 != 0)
sum = sum + x3;
x3++;
}

printf("\n Sum of all odd no between %d and %d is %d", n, m, sum);


}
//Sum of All Even Numbers
Even_sum(n,m)
{
int xl=n,j£=m, sum=0;

while(xl <= x2){

if(xl % 2 =* 0)

sum = sum + xl;

xl++;

pnntf("\n Sum of all even no between %d and %d is %d", n, m, sum);


}

Output ___________ ____________________________


CADev-Cpp\Exa'rsples\VTU C' J j'~_odd__e.e > ----- " ' ^
Enter Loner Range: 2
Enter Higher Range: 5 What
do you want:
1. Sum of fill Numbers:
2. Sum of fill Odd Numbers:
3. Sum of‘fill Euen Numbers:
4. Exit:
Sum o 'U. even no be tween 2 ,i»nd 5
, -O Jy"

Program 17: Factorial and Fibonacci Series


#include<stdio ,h>
void factorial(int n); /* function prototype */
void fibonacci(int n);

int main()
{
int n,c;
printf("Enter the Number:\n");
scanf( %d", &n);
printf("What do you want:\n");
printf("l. Factorial:\n");
prin;f("2. Fibonacci Series:\n");
prifiti("3. Exit:\n");
scanf(,;%d", &c);
switch(c)
{
case 1: factorial(n);
break;
case 2: fibonacci(n);
break;
case 3 : exit(O);
}
getch();
return 0;
}
void factorial(int n) /*calculate the factorial */
{int x, count;
unsigned long long int factorial =1;
x=n;
if (x< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else {
for(count=l;count<=x;++count) /* for loop terminates if count>n */
{ factorial*=count; /* factorial=factorial*count */
}
printf("Factorial = %lu",factorial);
}
}
void fibonacci(int n) /*calculate the fibonacci series */
{
int count, x, tl=0, t2=l, display=0;
x=n;
printf("Fibonacci Series: %d+%d", tl, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count<x)
{
display=tl+t2;
tl=t2;
t2=display;
++count;
printf("+");
printf("%d",display);
}}

1
Output
C:\Dev-Cpp\Examples\VTU CVF.J . .... '
tnte . 1. 1 Nui ibet ■7
Wl»-> ( yo m •./. t •
1 I '< * *.. « o l* i ., I - /’ I- j-,
*i>it
Program 18: Write a program to reverse a number and check whether it is
palindrome or not.
#include <stdio.h>
main()
{
int n,temp,rem,reverse=0;
printf("Enter the value of n\n");
scanf("%d",&n);
temp=n;
while(n>0)
{
rem=n%10;
reverse=reverse* 10+rem;
n=n/10;
}
if(temp==reverse)
printf("%d is Palindrome\n",temp);
else
printf("%d is not a Plaindrome\n",temp);
getch();

Output
■ C:\Users\pravesh\Desktop\ToWHJ..., 1=3 ®

j E n t e i * t h e v a l u e of n
1441
1441 is Palindrone ■I

* . rrr : *1

3.6. EXERCISE
1) Explain the statement and compound statement.
2) Write a note on labeled and null statement.
3) What is decision making structure?
4) What is Loop control structure?
5) Explain if statement with a suitable program.
6) Explain the switch statement with a suitable program.
7) Write the difference between while and do-while loop with a suitable example.
8) Explain the jump statement.
9) Write the difference between break and continue.

You might also like