Você está na página 1de 33

UNIT 2

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 proglam to use without having to open or
close the files. These standard files or streams are called:
stdin Connected to the kevboard
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
Connected to t}le first serial communication
Connected to the first parallel

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 VO and Related Built-In VO Fttttc{ions


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
Console Input and Output Functions

Formatted Functions Unformatted Functions

Input Output Input Output


scanfo printfO getchQ putchQ
getchar0 putcharQ
gets0 puts0
getche0

Figure 2.I: Console InpuUOutput Functions


2.1.2.1. FormattedFunctions
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 retum 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: scanfQ

means of the C libran, function scanf.

and automaticallv conveft numbers into proper internal format.

value. If an error occurs. scanf returns EOF.

Syntax
scanf(control string, argl, ar92r......, arg n)

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

The control string consists of three classifications of characters:


l) Format specifiers: The input format specifiers are preceded by avo sign and
which tell scanf0 about the type of data that is to be read next. The format
s^,ecifiers are matched, in order from left to right, with the arguments in the
argument list.

Code Meaninq
7oa Reads a floating-point value.
Voc Reads a single character.
Vod Reads a decimal integer
Vof Reads a floating-point number
Vas Reads a string.
7oP Reads a pointer
Von $qleives an integer value equal to the number ofcharacters read so far

Inputting an Address
To input a memory address, use the %op format specifier. This specifier
crituses scanf0 to read an address in the format defined by the architecture of
the CPU.

2l white Space characters: A white-space character in the control string


causes scanfO to skip over one or more leading white-space characters in the
input stream. A w'hite-space characterjs 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 scanf0 to read and discard matching
characters in the input stream. tr'or exampler"Vod, Tod" causes scanfQ to read
an integer, read and discard a comma, and then read another integer. If the
specified character is not found, scanf0 terminates.

A1l the variables used to receive values through scanf0 must be passed by
their addresses. A11 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 scanf0 call is used:
scanf("Vod", &count);

2.1.2.1.2. Formatted Output: printf0

using the library function printf.


any combination of numerical values,
single characters and strings.
the computer's memory to the standard
output device.

Syntax
printf(control string, argl, ar92r........, arg n)

Where control string refers to a string that contains formatting information, and
argl, arg2... arg n are arguments that represent the indiviqlal output data items.
The arguments can be written as constants, single variabLi'.or alray 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>
#includecconio.h>
int main0
{.}
int a, b, c, d, e, f, g;
clrscr0:
printf("Reading integers from standard input\n " ) ;
printf("---------- -------\n\n'l);
printf("Enter seven integers separated by space: ");
ll scanf("Vod7oi%o7%o1%oo7otVox", &a, &b, &c, &d, &e, &f, &g);
scanf("Vod%oi%o|Voi%oo%ou%ox", &a, &b, &c, &d, &e, &f, &g);
printf("The input displayed as decimal integers is: \n");
pintf("Tod Vod Vod Vod Vod Vod Vod\n" , a, b, c, d, e, f, g);
lltry different format specifier
pintf (" Vo d Voi Vai Voi Vo o Vo\ Vox\n", a, b, c, d, e, f, g) ;
getch0;
)

Output

2.11..2.2. UnformattedFunctions
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 neqd 19 conve{t t"t_\q.-{g1a:-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) gets0 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) getchar0 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(X

3) getche0 Function: This function retllrns a character that has been recently
typed. The typed character is also echo'tid 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 getchar0 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 = getche0;
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 = getch0i

5) putcho Function: They print a character on the screen. This helps the
compiler in single character output.
Syntax
putch(variable name);

6) putchar0 Function: This function outputs a character constant or a character


variable to the standard output device.
Syntax ,
putchar(variable-name) ;

7) puts0.Function: This function outputs a string constant or a string variable


to the standard output device. i

Syntax
puts(variable-name}

Program 2: To illustrate the unformatted functions.


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

void main0
t
char a[30];
gets(a);
puts(a);

getch0;
)

Cr\U se rl\p raverh\Der ktop\Io\W[.f ,exe

-*ffi:-***
Explanation
1) finclude<stdio.h> This heade. 'iil" i, incruded 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 getch0 comes under conio.h header files.
3) main0 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 (Bnter Key) is intemrpted.
6) puts is used to display them back in the console (monitor).

l) Write a short note on Built-in Operators andunctions.


2) Write the function for file handling,.,.
3) Write the basic steps to processing a file.
4) Explain the formatted UO.
5) What are unformatted functions?
1) Explain the following functions with a suitable example.
i) getsQ
ii) putsQ
iii) getch0
UNIT 3

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 Sffucture / 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 Statementsy'Constructs

Selection/Branching Iteration/Looping

do-while
Conditional Type Unconditional Type

if - else switch retum break ssllinus $oto

Figure 3.1: Program Control Statements/Constructs in C

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) If
t Condition
statement;
l

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)
t
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 main0
t
int n;
clrscr0;
as even or odd):'');
printf(,,Enter any number (which is to be checked
scanf("7od", &n);
if (nVo2==O) /* test for even*/
pintf(" %od number is even number"'n) ;
else
pintf("Vodis an odd number",n);
getch0;

Outpgt... ..,

3.2.4. Nested if-else Statement


The
.if block is called nested if the 'if bl0ck itself contains another
set of if statements'
so on'
Th" oo,pu, of the innermost 'if serves as the input of the
next outermost and

condition-l
?

condition-2
Block statement-l 2

condition-n
,!

Flowchart
Program 2: l*To demonstrate nested else-ifx/
#include<stdio.h>
#include<conio.h>
void mainQ
{
int units, custnum;
float charges;
clrscr0;
printf("Enter customer number and units consumed\n");
scanf(" Vo d 7o d", &custnum, &units) ;
if(units<=200)
charges=0.5*units;
else if(units<=400)
charges= 1 00+. 65 * (units-200) ;
else if(units<=600)
charges=230+0. 8 * (units-400) ;
else
charges=390+(units-600) ;
printf("\n\n customer No. zod: charges=vo.2fln", custnum,
charges);
getch0;
)

Output

3.2.5. SwitchStatement
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 intemrpts 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 multi-
way 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.
+a
Syntax
switch (expression)
{
case constantl:
statement seque[ce
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;

default
statement sequence
)
Entry

switch
expression

lExpression = Valle-l nl Blockl I

Expresslqn = Value-2
-l
;,^;I
,yM"rcpD"f".tt ,l D_ejautt
k
tilocK

Statement-x

Figure 3.2: Flowchart of Switch Statement

Properties of Switch Statement


lt *" 'switch' differs from 'if' because switch can only test for equality,
whereas.ifcanevaluateanytypeofrelationalorlogicalexpression.
2)Notwocaseconstantsinthesameswitchcanhaveidenticalvalues.of
course'aswitchStatementenclosedbyanouterswitchmayhavecase
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>

main0
t
int Grade ='L';
switch( Grade )
{
case'A' : printf( "Excellent\n" );
break;
case'B' : print( "Good\n" );
break;
case'C' : print( "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?\o"
);
break;
)
getch0;
)

Ou
r* C;\Users\Fra';esf;\Deslctpp\tXbih,ri,,, E3 tr

3.3.L. Introduction
A logp can be a pre-test loop or be a post-test loop:
1) Pre'Test Loop: rn 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 blcomes 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 clnstruct
may not be
executed even once.
2) Post'Test Loop: the post-test loop, the code is always executed
ln once. At
the completion of the loop code, the test expression ls tested.
expression evaluates to true, the loop repeats; if the
If the test
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. tfor' 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;

Condition

Figure 3.3: trlowchart ofFor 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 whenthis 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
conclition beclmes 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 I (initialization)
Expression 3 (incremenUupdate)

inti; 1
7 fo(i=o: i<3'i++)
forkeyword
- | printf("7od", i);
Co*pounay'Li
statement

Program 4:/* illustrating for loop*/


#include <stdio.h>
#include <conio.h>
main0
{
int i;
int j = 19'
for( i = 0; i <= j; i ++ )
{
printf("Hello %d\n", i );
)
getch0;
)

Output
Ciuser:1,!rBlelh\Ee:ktaprt'rbit!'Jile^exe m . lel

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 lloop
triggers the inner locp again. This repeats until the outer loop finishes. A btreal
within either the inner or outer loop would intemrpt this process. Consider the
following program to illustrate the concept of nested for loop.
Program 5: /*To Generate Multiplication Tabres of a Range of Numbers*/
#include<stdio.h>
#include<conio.h>
void mainQ
{
int m, n, i, j, p;
clrscr0;
printf("Enter Lower limit \n");
scanf("7od", &m);
printf("Enter Upper limit \n");
scanf("7od", &n);
for(i = m; i 4= n; i++)
t
for( - 1;j <= 10;j++)
{
p=i*j;
pintf("Va4d" , P);
)
printf("\n");
)
getchQ;
)

3.3.4.'while'Construct
While loop &reck 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)
{
stetements; Condition
)

Figure 3.4: f,'lowchart of While Loop


For example, printing numbers less than or equal to 4.
Test Expression

whileKeyword /
\*ilii;&=_r
fl
I nrind("7od",
i;;
ComPound Statement4l t++l
L)

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 ofcount 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 0
t
/* local variable definition */
int a = l0;

/* while loop execution */


while( a<20)
{
printf("value of a: c/od\n", a);
a++;
)
getch0;
)

9utpttt- . _
r C:\User51pr€sesh\Bes"..

3.3.5. tdo-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
t
statement;
) while(condition);

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.
dokeyword i=0
-....->oo
fi
Printf("Heel") :
---+l
Compound
statement [j**'
while -) while(i<4):
>
keyword \
Test expression
Program 7: /*Illustrating do-while statementt/
#include <stdio.h>
#include <conio.h>

int main 0
{
/* local variable definition x/
int a = 101

/* do loop execution x/
do
{
printf("value of a: 7od\n", a);
a=a+1;
)while( a<20);
getch( );
)

Output
],. f, rr.U:eI:"3iEr::!r C:si:ir ;:, t', i:'-., ; ;: :r.

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
5l Jr,rmp Statements. t

3.4.1.. ReturnStatement
The statement is written retum 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.
-
o
For example, consider the following program:
#include<stdio.h>
#include<conio.h>
main0
t
int a;
intb=5;
a = f1(b);
printf("a=Vod", u);
getch0;
)

f1(a1)
int a1;
{
int a2;
a2=5 * al;
pintf("a2=Vod", a2);
return(a2);
)

The value of a2 is calculated in function f10 and is returned to the calling


function using return0 statement and hence output of program is:

. C r.User3tr,,. {:3 ry

t.

3.4.2. Exit Statement


exit0 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 exit0 all memory and temporary storage areas are all flushed-out and
control goes out of program. In contrast, the return0 statement is used to return
from a function and return control to the calling function.

Also in a program there can be only one exit0 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.
exitO 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 exitO is that the former rerminates the
execution of a loop in which it is written, while exit0 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?nost 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 mainQ
{
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<100; i++)
{
if(getchar0 -='s')
break;
printf("7od\n", i);
)
exit(0);
getch0;
)
C rr,U re rs\p ra';es!r\De: ktc p\t\bifiryi se.exe

before printing
Explanation: It reads a single character flom the program'sinput
an exit from
the next in a sequence of nuftbers. If an 's1 is typed, the break
causes
the loop.

3.4.4. Continue Statement its use are the


This statement has only a limited number of uses. The rules for
same as for break, with the exception that it does not apply to switch statements'

do, while
Executing a continue starts the next iteration of the smallest enclosing
restricted to the top
or for staiement immediately. The use of continue is largely
the rest of the
of loops, where a decision has to be made whether or not to execute
body of the looP.
is used to induce
Ifthe body of the for loop is large then the continue statement
readability. Program below illustrate the
an extra level of indentation and inhance
concept of continue statement.

Program 9: /*Illustrating continue statement*/'


#includecstdio.h>
#include<conio.h>

int main (;
{
/* local variable definition */
int a = l0;

/* do loop execution
*/
do
t
if( a == 15)
t
/* skip the iteration */
a=a+li
continue;
)
printf("value of a: Vod\n", a);
a++; *
)while( a<20 ):

getch0;
]r
Out
:ril f r1,U se l.; !.p ra,,.rsh\ Ses kt* p,J'ib,itrri se.,,

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 goti
statement is,

goto Ll;
/* whatever you like here t/
Llz l* anything else 8/

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 ipace
only exists for the function containing the label, so label names can be."-r.ed i,
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 ind of u
statement. For example, consider the following statement: "o*pouni

label_at_end: ; /x empty statement */

)
Because
The goto works in an obvious way, jumping to the labeled statements.
cannot jumP
the name of the label is only visible inside its own function, You
from one function to another one.

while for (
(...........) t
{
for
if (error) (...........)
goto stoP; t

Jump
within
loop I
L_*
ii'i"""oi,i."l
goto abc;

abc:
Exit
from
loop Exit
froml
two
rooos[*
f-
I

]
if (etor)
goto effor;

)
stop: :T:.
'";)" " b)

Jumping with GOTO Statement

Program 10: /*Illustrating Goto statementx/'


#include <stdio.h>
#in.lude<conio.h>
;n1 pzirr (r
{r
/* local variable definition */
int a = 10;

/* do loop execution */
LOOP:do
t
if( a == 15)
{
/* skip the iteration */
a=a+l;
goto LOOP;
)
printf("value of a: 7od\n", a);
a++;

)while( a<2O);

getch0;
)
9utpqt
S (l'\U se rr rp ra,,,eshlrBesktcp\t\birr*ise"exe

3.4.6. Difference between Break and Continue Statement


Table: Break Statement Continue
Break Statement Continue Statement
ll Can be used in switch statement. 1) Cannot be used in switch
2) Causes premature exit of the loop 2) Causes skipping of the staternents
enclosing it. following it in the body of the loop.

J) lhe control is transfered to the statement 3) Control is tansferred back to the loop
followins the looo.
4) The loop may not complete the intended 4) The loop completes the intended number of
number of iterations. iterations.

Program llz l*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>
finclude<conio.h>

void lower1o_upper0;
void upper_to_lower0;
void main0
t
int n;
clrscr0;
prinf("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("Vod", &n);
switch(n)
{
case 1:
t
printf("Please enter a string in upper case'\n");
printf("String will be terminated if you press Ctrl + Z'\n");
Printf("\n");
Printf("\nSTRING:- \n");
uPPer-to lower0;
break;
)
case 2:
t
printf("Please enter a string in lower case'");
printf("String will be terminated if you press Ctrl-Z"');
Printf("STRING:- ");
Iower-to-uPPer0;
break;
)
default:
Printf("ERROR");
)
printf("HAVE A NICE DAY! BYE'");
getch0;
)
void upper-to lower0
t
int i, j;
char c4[80], c3;
for(i=O; (c3=getchar0) !=EOF; i++)
c4[i] =(c3>='A' && + c3 -'A')
c3 <=' Z' )? (' a' :c3 ;

printf("The lower case equivalent is ");


for(=O;j<i; j++)
Putchar(c4[j]);
return;
)
void lower-to-uPPer0
{
int i, j;
' char c2[80], cl;
for (i=O;(c 1 =getchar0) ! =EOF;i++)
c2[i]=(c1>='a' &&c1<='z')?('A' + c1 -'a'):c1;
printfl;fne upper case equivalent is ");
for(=Q; j<i; j++)
- Putchar(c2[f]);
getchO;
)
Output

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 main0{
int num.i=l,sum=0;

printf("Enter a number: ");


scanf("%od" ,&num);

while(i<nurn)i
if(numToi==0)
sum=Sum+i;
i++;
)
if(s,tm==irum)
prirrtf("'7od is a perfect number",i);
else
printf("Vod is not a perfect number",i);
getchQ;
return 0;
)

9ut"t ,i ? ,=, .r, --


. C iDer'-r*p;:\Exan:.,. *9_lWC@
Program 13: /*Program for Prime Nurlrber Generation*/
#inchde<stdio.h>
#include<conio.h>
main0
t
int n, i=1, j,c;
clrscr$;
printf("\nEnter Number Of Terms\n");
printf("\nPrime Numbers Are Following\n");
scanf("%od", &n);
while(i<=n)
{
c=0;
for(=l' j<=i; j++)
t
1f(i7oj==91
c++;
)
if(c==2)
pintf("Vad ",i);
i++;
)
getch0;
)

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


#include<stdio.h>
#include<conio.h>
void main0
{
double n, gt, 92;
int flag=0;
clrscrO;
printf("\ncode to calculate the square root without inbuilt functiorr\n");
printf("\n");
printf("Enter the no.: ");
scanf("7olf',&n);
printf("\n");
if(n<0)
n-n;
flag-l;
)
else if(n==0)
{
printf("The root of Vo6.4lf is", n);
textcolor(GREEN);
cprintf(" Vo6.4lf', g2);
getch0;
exit(0);
)
gZ=nl2;
do
t
o1
D^ =o)'
b-r
g2=(gt+ntgt)tZ;
)
while((g1-g2)!=0);
if(flag==l)
{
printf("The root of Vo6.4lf is", -n);
textcolor(GREEN);
cprintf(" +l- Va6.4lf i", g2);
)
else
{
printf("The root of Vo6.4lf is", n);
textcolor(GREEN);
cprintf(" +l- 7o6.4lf', g2);
)
getch0;
)

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 mainQ
{
int r;
long number = 0, c, sum = 0, temP;

printf(''Enterthemaximumrangeuptowhichyouwanttofindafinstrong
numbers ");
sc anf( " 7o1d", &number) ;

printf("Following armstrong numbers are found from I to 7o1d\n",number);

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

temP = s'
while( temP != 0 )
{
r = temp7al0;
sum=sum+r*r*r;
temp = temP/lO;
)
if(c==sum)
printf("Told\n", c);
sum = 0;
)

getch0;
return 0;
II

Outout
:-.
C:\Der- C pp ,E .a-; l:s ,!TLl i ,An jtrong ele

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


#include<stdio.h>
#inclurlecconio.h>

int mainO
{
int m,n,c;
.-_ "- up:
printf("\n Enter Lower Range: ");
scanf("7od", &n);
printf("\n Enter Higher Range: ");
scanf("7od", &m);
if(n >= m)(
printf( "\nlmproper Input\n") ;
goto up:
)

printf("What do you want:\n");


printf("1. Sum of All Numbers:\n");
printf("2. Sum of All Odd Numbers:\n");
printf("3. Sum of All Even Numbers:\n");
printf("4. Exit:\n");
scanf("Vod", &c);

switch(c)
{
case 1: All_sum(n,m);
break;
case 2: Odd_sum(n,m);
break;

break;
case 4 : exit(0);
)
getch();
return 0;
)

//Sum of All Numbers


.,r,*All-sum(n,m)
":.. int
t
i,sum = 0;

for(i=n;i<=m;i++)
{
sum=Sum+i;
)
printf("\n Sum of iill no betwge n Vad and Vod is Vod,,,n, m, sum);
)
//Sum of All Odd Numbers
Odd_sum(n,m)
t
int x3=n,x4=fil,SUm=O;
while(x3 +x4)[
if(x3 7o 2 t= 0)
sum=sum+x3;
x3++;
)
printf("\n Sum of all odd no between %od and o/cd is %od" , n, m, sum);
)
//Sum of Al1 Even Numbers
Even-sum(n,m)
{
int xl=n.t2=m. sum=O:
while(xl <.= x2)1
1f(xl 7o 2 =i O)
sum=sum+x1;
x1++;
)
pnntf("\n Sum of all even no between %od ando/ad\s Ead" , n, m, sum);
)

C,.\D*r-L F p'ExatrPler',!rTU C Su*.-cCd-e;e

Program 17: Factorial and Fibonacci Series


#irrc1.:de<st<iio.h>
void factorial(int n); /* function prototyPe *l
void fibonacci(int n);

int main0
t
int n,c;
printf("Enter the Number:\n") ;
scanf('7od", &n);
printf("What cio You want:\n");
printf(" 1. Factorial:\n");
" prin.f("2. Fibonacci Series:\n");
prtptfr." 3. Exit:\n" ) ;
scanf(rEod", &c)'
switch(c)
{
case 1: factorial(n);
break;
case 2: fibonacci(n);
break;
case 3 : exit(O);
)
getch0;
return 0;
)
void factorial(int n) /*calculate the factorial */
{int x, count;
unsigned long long int factorial=1;
x=Il]
if(x<0)
printf("Error!!! Factorial of negative number doesn't exist.");
else {
for(count=l;count<=x;++count) /* for loop terminates if counDn */
{ factorial *=count; /* factorial=factorial*count */
)
printf( "Factorial = Vola",factoial) ;
)
)
void fibonacci(int n) /*calculate the fibonacci series */
t
int count, x, t1=0, t2=1, display=0;
x=n;
printf("Fibonacci Series: 9kd+Vod" , tl, t2); /* Displaying first two terms */
count=2; l* count=2 because first two terms are already displayed. */
while (countcx)
{
display=1laP;
tl=t2;
t2=display;
++count;
printf("+");
pintf (" Vo d", displ ay) ;
)l
Output
-i,rr, .1E
F Cr\De!-Cpp\Examples'rVTU C\f.. ,- El sj
Program 18: Write a program to reverse a number and check whether it is
palindrome or not.
#include <stdio.h>
main0
{
int n,temp,rem,reverse=0;
printf("Enter the value of n\n");
scanf("7od",&n);
temP=n;
while(p0)
{
rem=n%ol0;
reverse=reverse* 1 O+rem;
n=n/10;
)
if(temp-=everse)
pintf(" Vod is Palindrome\n",temp);
else
pintf("Vod is not a Plaindrome\n",temp);
getch0;
)

putput
w f,{Usem\pravesh\Desktop\,To\WU.,.. -) tA

l) Explain the statement and compound statement.


2) Write a note on labeled and null statement.
3) What is decision making structure?
4) What is [,oop 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.

Você também pode gostar