Professional Documents
Culture Documents
Bca C Language 2&3
Bca C Language 2&3
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.
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.
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.
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.
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);
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.
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.
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);
Syntax
puts(variable-name}
void main0
t
char a[30];
gets(a);
puts(a);
getch0;
)
-*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).
Selection/Branching Iteration/Looping
do-while
Conditional Type Unconditional Type
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
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... ..,
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.
default
statement sequence
)
Entry
switch
expression
Expresslqn = Value-2
-l
;,^;I
,yM"rcpD"f".tt ,l D_ejautt
k
tilocK
Statement-x
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.
Syntax:
for(initialization; condition; increment) statement;
Condition
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
Output
Ciuser:1,!rBlelh\Ee:ktaprt'rbit!'Jile^exe m . lel
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
)
whileKeyword /
\*ilii;&=_r
fl
I nrind("7od",
i;;
ComPound Statement4l t++l
L)
int main 0
t
/* local variable definition */
int a = l0;
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
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);
)
. C r.User3tr,,. {:3 ry
t.
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.
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.
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.
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.
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.
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.,,
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
)
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)
/* 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
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 ;
Explanation: The code describes the switch case usage wounded with .for, loop
for function calling of upper_to_lower and lower_to_upper.
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;
)
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) ;
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
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:
)
switch(c)
{
case 1: All_sum(n,m);
break;
case 2: Odd_sum(n,m);
break;
break;
case 4 : exit(0);
)
getch();
return 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);
)
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