PPS SOLVED Previous Years Questions PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

·_C PRoaRAMMING...,.

3__
PREVIOUS YEARS QUESTIONS

- Here, in the above array declaration total J6 bytes


I. SHORT ANSWER TYPE QUESTIONS of memory is al located, beca~se int data type occupies 2
bytes in rpemory. All the element_s _ o! ~rray contain'
, Q.1 Why do we include <stdio.h> in our programs? garbage value because we .have not m1t1a!1zed the,array
• {R.T.U. 2018/ . eleme,nts. ·Index of array 1s used to retrieve and store
ariy value at a particular R()Sition ~f the ~Y- Array.index
Aas. #include<stdio.b> always starts from Oand ends.with (size - I).
· This line includes a header file which-is "stdio.h" to
our program. :•stdio.h" means Standard Input Output ifferentiate between a ·character lJnd a string.
header file. This file contains· prototypes of some . /R.T.U.1018/
prede~ned functions like printfQ'and scanf():
~ns~ Difference •between Character and String
· Q.2 Defme a /"fiction. {/!..T.U. 2018/ ·A ch~acter is just a single character enclosed in single
. .
quotes.. For ex~ple: .
• Ans. A function is a self-contained block of statements char initial = ·'A'; /* initial declared to be a character*/
that·perronnsa particular task. Once a function has been And a character string is a sequence of O or more
defined and packed it can-be treated as.a.block box that cha,rac,ters enclosed in double .quotes .. Each string is
takes some data· from t~e main program and returns a · terminated by a NULL byte.
value.
ch~ str[] =,"hello, where are you these days?";
C functions can be defined i~to two categories I ' For ex·ample, for a' string contain~g maximum
(a) Standard Library Functions 10 characters, we need to declare. character a'rray of
(b) User,defined Functions sii:~ 11 bytes; as.: 1

char msg[ 11] = "hello dear"; /* 'msg' is 10 char:


Q.3 f!o .Hds an array represented in memory? string*/ :
{R.T.U. 2018/ .Here, 'msg' is a IO characters string while it's declared
and initialized to contain l l characters. Last charac ter b
·Ans. Array Ele~ents in Memory
NULL byte to terminate th~ string '~sg'.
As we have already seen that el~ments of array .
are stored continuously in memory one after one. Consider Q.S
.the following array declaration : rtferent_iate bet~ee~ .Plr +t and ptr ++•*
[R.T.U. 2018/
intarr[8J;
anfO) orr[IJ arrf2l arrf3] arr[-!] . arr[S) ~ [6] AIT'd)' Index Ans. The difference between the ptr++ and *ptr++ can
/ P /'
24
/ - 40 /

II / 2' / 0 / 90, I 77 j -V~lucsof
- arra\'
be explained by an example- ,
2000 2002 2004 2006 2008 201 O " •
, . 2012 2014 Addrcsscs·of '"'ptr.- Holds the ".~lue.
elem~nts
.,ptr - Holds the address . .
-~ ,,.,,.g 1or ir,.,., ....... ~u,,ng
. . - ·• · - · · dition has
·teptr++,.then this will increme tth . . d-of-file con . n-
~ \vr1 • * n e (inacro) EOF to indicate thatan e~F is implementatto s.
•i1v'C t 1·f we wnte ptr++ then it will
I
1 l3U , . crement
m' .
occurred. The actual value ofE T d character code
·,.lf'sS· f *ptr, because++ operator 1s right ·
r.~o . dependent and is djstinct from al_lvau~ber of bytes read,
vS
·oti"e. Block-reading functions retu~ the~ hen the end of file
l ,sJTlple,1''" and if.this is fewer. than asked for,-.t .

(;,Jt'tr::;: 5·'
was reached or an error occurred. =
. . . . .· . . emo,Y for th~
/P.
I

we print *ptr, then we will get the value 5 Q 8 "Structure·declaration re~erves nJ · .,,. valld
J,fo,f . * . . · · • h,ss
· tatement "'''" 2018}
.II"' wifwewnte: ptr++, smce 1t is right structure:Com~entont . . /R.T.U.
· l!ilt n°. e therefore first address will increment a d justification.· -
· jatl" , . · n
f. .11 print the result. • . • • I f on reserves
I ., • ••

.,i1tWl . . . . Ans. The st_at_ement. •~structure dee. ~radJ. i-: · IIowing·


" be explame. m.io d · ly-
erenti.ate between·a . structure and . an .array. . · memory for the structure can -
mann~r; In C programming the memory JS allocate .~:-.-.
/R.T.U. 2018/

r
!JS.
when we declare the variables o'rthe structur~. In°-. :~-.
words .the memory i:s allocated only when we JOstantta e
' · • · bl tructure·
: ,_ro~ - Array ·Struetute the structure. In the absence ·of any vana e, 5
ico01 ar1son
1
· · definition isj~st a·t~mplate th.at ~iHb~ used to _r~;::
An.array is a A structure is a ·memory when a vanable of type .struct JS declared ·
:sasiC
collection of collection of the variables of a structure are defined, we can perform
;
variables of same variables or .
I

data type. a few operations 0~ them. For example,'.we can use th~
different data.
type. ' assignment operator (=) to ·assign the. values of one-_
I
data type Struct variable to another. Another important point· is that
1~rniax
: ·array_name[ size]; . sruct_name{
.
members inside t~e structure.definition are attached-to
I
fype elem~nt I; ·the structure variable, they don't have any existence
' type element2; without structure variable. Member names inside a
..
structure must be different from one ·another, but the
I . member names of two tlifferent structures can be-same . . ..
I
I }variable 1, . .

I variable2, ... ;
:jMemory Array
- stored in
elements are Structure II. LONG ANSWER TYPE QUESTIONS
elements may not

'I

contiguous membfY be stored in a


I

,.
', Q.1 How are strings read from tl,e standard inpui
11 ·location. contiguous
JI
'L
..
,, memory location. , device? Explain the di.fferent functions 11sed to
l kqs~ Array el_ements are Structure
I, .
. perform string input operation. /R;T.CJ. 2018/
accessed by thejr elements are
. · index number. accessed by their Ans. Us!ng %s form~t specifier when we read string,
'::----_ names. · C comptl~r autom~t1cally assign~ all the characters in
Or,erator Array declaration StruC'.ture ,element
.. separate memory ~locks and ~dd a null character ('\0')·
and element . accessing
t .
a.t the end of the stnng. At the time of printing o/c c .
'

a~cessing operator operator is 11 11


• 'fi • . os 1ormat
spect 1er 1s used m printf( ) function and h
'
., is 11
(Dot operator) . . 't .
[ ]" . . . 1 prmts t e
character until 1t reaches '\O'; ·
. ' '
Example:
~at do you· understand ·by £OF? /R.T.U. 2018/ main()
{
%
:~ ~OF ::In computing; end-of-file•(comm?~ly
-~lated EOF) is a condition in a computer operatmg char name[25]; .
I~ Where no more data can be .read from a dat~ pr~tf (" Enter Your Name:-")· ·
The data source is us~ally ca~ied a ~I~.or ~tr~am. scanf
.
( "o/c·s"
0
.,
& name)· '
.. Standard Library, the charactet, teadmg ~~ncttons printf( "\nHello %st" ' ·
\... ·&etchar return a value equal to the symbohc value } · , name); .
lt"t":t.-""'J _ · printf("\nThis character comes ~""ll'l s~
Here is a simple run of the program ... · · 1n str·
times",count); . 1
ng
Enter Your Name :- SANJAY . l(j
}
HeJlo SANJAY!
Output:
Some other String Input/Output Functions
Enter a string: - INQIA IS GREAT
getsO :gets( ) function is declared in "stdio:h".
Enter a character: - A
Using this funcl ion we can read more than one word
;(including spa~s) because it gets tenninate when new This.character
· · comes
- in string 2 ti'mes
line cilaracter (\n) is encountered.
puts0: puts() function is also declared in "stdio.h". Q.2 ·Write ti program in C that rep/ ,
This function can print a string on console, and has inbuilt character·with another character ~ces a give~
new line character ('\n ' ). .· · .. zn the str;11i
getch() : .getch() function is declared in "conio.h". .. ·. ~R. T.u. 2018;
This function reads a character from the console but does Ans. #include ~std10.h> ·
not echo it to the screen. #include <string.h>
getcbe( ) .:getche( ) functio~ is also declared in · int main()
"conio.h". This function reads a character from the , {·
console and echo i( on the screen. ' char str[l qoJ, ch, Newch;
getcharO : getchar() reads a character from the inti;
console and reading is terminated when new line
pri~tf("\n Please Enter any String : ");
· character (\n) rs.entered. The character w,hich we enter
gets(str);
is also displayed on the screen.
putcharO · : putchar( ) prints the character .· . printf("\n PIC;'ase Enter the Character that you
want to Search for :_ ");
argument 6n the sta~dard output.
scanf("¾c", ,&ch);
. If we are using getch0; getche(), get~liar() or
getchar();
putchar() for reading or displaying a string we require a
loop as these functions/macros are used to read or display printf("\n Ple·ase Enter the New Character :");
Jt single character. . · · . · · , scanf("¾c", &Newch);
A program to firid o~currence of·any .par~icul~r for(i = 0; i <= strlen(str); i++)
·character in a string. · .' · {'
#include<stdio.h> if(str[i] = ch)
#include<conio.h> {
void main() . str[i] = Newc.h;
{.
}.
char c,str[ IO];
int i,count=O; · '
· printf("\n The Final String after
Replacing All Oc~urrences of '%c' with '%c' == %s",
clrscrQ;
ch, Newch, str); .
printf("\nEnter a string: -~');
return 0;
tets(str); }.
printf("\nEnter a c~aracter: -");
scanf("%c",&c ); Output:.·
for(i=0;str[i]!= '\0';i++) Please Enter any S,tring : Neelkantg
{ Please Enter.the Character that you want to Search
for: 1g
if(str_[i]=c)
• j 'i
Please Enter the New ·character : h ,,
.}
. count+:+-; . t
•• . ,s· . . , '.
Th e- Fma trmg·after Replacing All Occurren ces 0f g

with 'h' = Neelkanth .


"1 W -u P: ug~~n, to CreQte . . .
Q,J ln/ormat,011 given beta tt .sr,,. ,. •
the data.
. .
.
01
. . ~--1'1,e,, ·,. ~e li>it/; tl,'e
. . elld ""d Pr1111
. .'
--:-------------'Pl
. pr~ntf(''Address· :>n"); ' \
(a) Emp_Id .. . .
Pflhtf(" Area :.");
\

· (b) Name-
g~ts(emp.area};
(i) Firsr Name
Printf("City :.");
(ii) Middle Nanie . · g~ts(e'rrip.city);
.(iii) Last Nanie Prtntf("State :");
(c) Ad4ress- gets(emp.state );
(i) Area
(ii) City - printf("Ag~ :'');
.(iii)-State s~anw·_¾r',&emp.age );
· (d) Age " Prtntf(''Salary :"); ·• .
(e) Salary s~anf("o/or',&~mp.salary); . ·
(j) Designation Prtntf(''Designation :"); · ·
gets(emp.designation);
';#include <stdio.h> . IR.r.v. 2018/
rstrUcture declaration*/ /*print employee details*/
~ct emplp_yee { printf("\nEritered' detail is:\n");
intempld; . printf("Emp_Id: ¾d\n;', einp.empld);
char firs,tn~me[30]; ·
charmiddlename[30]; printf("Nam~'"\n"); .
cha.r lastname[30]; -printf("First Name: %s\n", emp.firstname);
char area[50]; printfC:Middle Name~ %s\n", 'emp.middlenatne);
prmtf("Last Name: %s\n", .emp.lastname);
• • • • .. \ ' f •

char city[30];
char sfate[30]; . . printf("Address-\n"); ·
.float age;
.printf("Area: %s\n", emp,~rea);
float'salary; printf("City: %s\n''; emp.city);
· char designation[30]; printf("State: %s\n", emp.state)~
);

'
printf("Age: %f\n", emp.age);
intmain(J .
·. printf("Salary: %f\n", emp.salary);
\ printf("Designation: %s;', emp.designation);
/*aeclare structure variable*/ return O;
· structempl,oyee emp; }.

I·/'read ~;;iloyee details*/ . · ,at is the advantage of using stru.ctures~


·printf("\nEnter det~i ls·:\n"); Differentiate between a structure and a union.
Printf(''Emp_ld :"); - - . /R. T.U.1018/
,scanf{"o/od", &emp,empld);
· Ans: Advantages of Structure : ·
Print~("First Name:"); _
. 1. Structure is collection of differ~nt types of
gets(emp.firstname ); . , · · variables referenced under one name. By this
Print~("Middle Name :"); ·· ·. ·we ~eed. not define same category variable ·
types in different variables. - .
gets(emp.middlenarn~ );
··2. . Me~qry . is nqt ,allocateq at the ti!lle -of
Printf(~last Naine :'~);
_11:.

1
.. declaration of structure. After creation of
gets(emp.lastname );: · ·• '
structure v~iables me~ory is allocated . . ·
· . ,I • ·
· 3. Nested structure can also be defined.
PPS.36;-------:______________- . ---1 Programming for Proble
4. Continuous memory allocation for structure Ans. Som~times it is ~esirable !<? create ob•: Sob,j~
members. • time. That ts we do not inform the compiler th~ Cts at,.,,
'fi d. d d I atan 0 ·un
5. Structure is a user defined data type, so that it · of a spec, ie type an name nee s to be ere bj~
facilitates user to create variable accoraing to we create an object of. th e approprite type ated. Instead
the requirements. (Un time. This is done by ~llocating memory f~~~~elves at
u , rk' . d fi d d that we need to ~reate. Smee the memory is 11 eobjeq
6. wo mg ts same as pre e ne ata types. objects ''dynamically"(i.e., at run time) ere at· ocatedfo
Structures : Keyword - struct .
obJects . known as dynamic
1s • memory' alloa ion. 0f suchr
l)le structures are the heteroge}leous user · · cation
defined data types where a structure content number of ~e c_ standard Ii~~ provides the function lll;II
data types grouped together. These data types may or to create obJect dynamica1ly. The function take . Oc()
may not be same: E.g. to keep record of students we,· ment the size in bytes of the object to be creat ds a,n~gu.
. h e · te1th
may use following structure returns the pointer to t e created object it w
. as abl er
struct student allocate memory or returns NULL if not. . eto
{ Function Use of Function
char name [30]; ·Allocates' requested size of
int age; malloc() bytes and returns a pointer
char fatlier name [30]; first b e of allocated s ace
char class; - • Allocates space for an array
int totalmarks; calloc() elements, initializes'to zero
} and then returns a pointer to
memo
Thus in this way we can group all common
deallocate the_previously
attributes of an object record and can access all of them freeO allocated s ace ·
via same name.•E.g, we have declared variable-of above Change the size of
structure student. realloc()
reviously allocated s ace
/* declaration */
struct student ram; Syntax of malloc( )
now if we need age of Ram we can store and ptr =(cast-type_*) malloc(byte-size);
retrieve it from
Here, ptr is pointer of cast-type. The malloc()
ram.age;
function returns a pointer to a.n area of memory with size
thus to excess data struct we use . operator.
of b~e size. If the spaee is insufficient, allocation fails
Union : Unions are used to save memory i.e. and returns NULL pointer.
when we declare the union then the space allocated for
use of that union is equal to memory required for the . Example
biggest variable. . iitr = (int*) malloc(l QO * sizeof(int));
Keyword union This statement will allocate -either 200 or 400
Union is also heterogeneous data type. So in it we according to size of int 2 or 4 bytes respectively and the
can use int, char, and float. pointer points to the address of first byte bf memory.
Union data
• I

Syntax of free()
{
int a; free(ptr);
. d.
float p; This statement frees the space allocate 10
char c; memory pointed by ptr.
} d2;
. calloc( ) - . .
In union only one member can be used at a time or ' . . Th!S
only one member contains valid valu~s. !he callo~ () stands for.cont}~uous al~ocauon.does.
function allocates memory at runtime as mal!oc(_) tha~
Q.5 What i$ dynamic memory allocation? What are The difference between malloc() and calloc(~:ereas
the various /unctions in C {(tat are used for' malloc() allocates single block of mem?l'Y hofsaf!le
dynamic memory a/location? Explain. '.-- I • : ' ·callocO allocates multiple blocks ofmemoryeac
/R.T.U. 2018/ size and sets all bytes to zero.
9
,,.,,,,,. for Pr.oblem Sowing r------~,-=::-~:-=-=_=_=_=_=_=_~_;:_=_=_=_=_=_=_=_==_==_==_=_==_=_==_==_==_==_=_=_=~=pPS===:.3
==:7~
~ 11u1i . .
SY :,:(cast-type*)c~lloc(n,
ptf · f element-size)·' Q.6 Wr ~hort note 011 the following functio1t s.
~ere,Ptr is pointer o casrtype. The calloc() function ~ ~e;c,: function, give a program code that
p0inte~ t~ an ;.e~ 0 memory with size of byte demonstrates its usage-
58
... space 1s msu 1c1ent, allocation fails a d
' 1f u•e n returns
£;• fiopen ()
'"-'
f' 1, painter. (ii) fclose O
,V~ llotple (iii)fgets () 18
~;,(float') calloc(25, ,;zeof( float)); (M fseek () ' [R. T- u. io 1
~is statement allofcates contiguous space in Ans. (i) fopenO Function : The first operation needed th
for an array O 25 elements each of size of to be dqne before processing data in a file is to open. c
(lrr,o_rY 4 bytes. file. This is done by the fopen() function.
,,~
' 1.e,
(illll: The prototype offopen() is given below:
1

~ #include <std\o.b> FIL.E * fopen( char * filename, char * mode);


#include <stdlib.h> Where filename specifies ·the name of the file on
in!JllainO the secondary storage and mode specifies whether the
{ frle s?ould be op.ened for reading or writing or for both.
jot nurn, i, *ptr, sum = O; . The fun~liQn fopen() returns a pointer to a_FILE
printf("Enter number of elements:"); object if it could successfully open the· file. It retu rn s
canf("%d", &num); NULL ifjt could not. It is always good to test the value
5
ptr= (int*) calloc(num, sizeof(int)); returned by fopen() function . .
if(ptr = NULL) , - (ii) fcloseO Function: All files opened, must he
closed at the end of the program. This is done by the
{ library function fclose()
printf("Error! memory not allocated."); The prototype of f~lose() is given by
exit(0); · int fc;:lose(fp);
, Where, fp is a pointer to a FILE object of an open
file* . When we close a file using fclose() foll owing
printf("Enter elements of array: ");
operations are pe~~mned :
for(i = O; i < num; ++i)
• The characters in the buffer would be w ritte n to
the file on the disk.
scanf("%d", ptr + i);
• At the end of file a character with ASCH val ue
sum += *(ptr +. i);
26 would-get written.
• The buffer would be removed from memory.
printf(\'Sum = ¾d", sum);
free(ptr); Though most operating systems automatically close
files when the application tenpinates, explicitly closing
return O;
all open files is a good programming practice.
realloc( ) Progra~ to demonstrate fopenQ .& fcloseQ function:
Sometimes previously allocated memory becomes
~sufliictent
· or more memory
· · as compare d #include <stdio.h>
is' required #include <process.h>
l~ao alread Yallocated memory. So, realloc( ) tiunction
·
void main()-"'
.ngethe previous I~ allocated memory (allocated .{ /
~ingrnalloc() and calloc( )) a~d provides new FILE:*fp 1, *fp2;
•e1110 b .
ry locks as required. ch~r a;
Syntax ' 'clrscr();
fp 1=fopen(" A.txt", "r.");
tll':::: reall?~(ptr, newsize);.
. . , .. .
: ... ,if(fpl==NULL).
12
ere,ptr ts reallocated with size of news ""·
• 1' ·• l'
PPS.38 _ _ _ _ _ _ _ _;___ _ _ _ _ _ _;__...;;__ _,;........_--4r=-----
, Pragranunfn,-, Ji
{ · .'::-:-~--=-:.:.:.:::~:1_J,or Pr
.. fp ':= fopen("fiJe.txt", "w+"); Obfellt So
' pu~("cannot open this file"); fputs("This is Neelk_anth", fip)·, ~,
ex1t(I );
} fseek( fp, 7, SEEK_SET );
fp2=fopen('•B.txt'', "w"); fputs(" C Programming Language" fi
if(fp2 NULL) , fclose(fp); ' P);
{· . return(0);
puts(''Not able to open f!lis file"); }
fclose(fpl);
exit(I);
} Q.7 Write aprogram to read datafi
0
do · and write it io a file. Read ti. ' "' the keyb 1
.m t,,e
, fl"'
1,e and display it on th . e111s s1ooa,d
ie co11i
{ , _ e scree11. 1
1'
a=fgetc(fp 1) ;
. a=toupper(a); ;;;;;~~~~~~--:=-=:i-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;~{R~.r,ll.,
• ·',0I!/ I
fputc(a,fp2); Ans. #include< -stdio.h >
} int main()
while(a!=EOF);
fcloseallO;
getch(); · FILE *fp; /* file pointer*/
. char tName[~0];
A;
}
(iii) fgetsO Function : fgets() function reads next . pr}ntf("\nEnter file nam~·to create
n -1 characters and stops when a new line 'character is scanf("%s",fName); ·
· encountered. The newline character is included in the •
array an·d it is ~rminated by '\0'.
/*creating (open) a ~le*/
The prototype offgets() is :
fp=fopen(fName,"w");
char * fgets( char * s, int n, FILE * fp );
/*check file create<l' or not*/
It reads n-1 characters in s: On success it returns
· if(fp==NULL)
on end of file and on error it retums ~NULL.
{
#include <stdio.h> printf("Fj)e does not created!!!'');
#define MAX 15 exlt(0); /*exit from program*/
int main()
{ J
char bufIMAXJ;
fgets(buf, MAX, stdio); printf("File created successfully.");
printf("strilig is: %s\n", but);
return ·o; .• . /*writting into file*/
} putc(' A' ,fp);
putc('B ';fp );
(iv) fseek0 Function : fseek() f4nction can be
putc('C ',fp );
used to directly manipulate the file pointer so that it points
to the desired byte offset. The prototype of fseek() is : printf("\nD~ta written successfully.");
int fseek(FILE *fp, long offset, int origin); fclose(fp);
·· where fp i~ a pointer to a FILE object representing . /*again op~n file to read _data•/ .
a file. fp=fopen(fName,"r"); . .. ...
if(fp==NUL,L)
,·,
,,. . . <stdio.h>
#include . . .· ·. ,. , 1· 1 ' .
··, {
int main,{) { .. ,, . ..
f I •
p~intf(''\nCan.'t open fi.le!.!!");
,:~F1LE1.*.fp; . ...,,. .,._ .
) ~o,.t••contents of file is ·\
.n") ., D' OR
tscuss void pointer
·
r11• and its utility in brief.
P .t••o/oc" ,getc( fp))· .fR.T.U. 2016/
·ot1, '
pr' .t••o/oc",getc( tip))· . Ans. Null Point . N . . . .
·olll · ' .Pointing to not _er ·, ull p~mter 1s a pomter which is
pr:,,tff''o/oC",getc( fp) ); be assi·g· · d hmg. In case, 1f we don't have address to
f'''fclose( fp); ne •to a. pom
· ter, then we can
· simply
. use NULL.

retofll O; ~include <stdio:h>


tntmain()
{
II Null Point~r
f!1,;1e a ptogram ·using po~ters 1 • . .:._
Q,8 ,·n an array. o tnsert a va/ue , int *ptr = NULL;
. /R. T.U. 2018/ printf("The value of ptr is o/ou", ptr);
return O; .
~ude <stdio.h> }
40S·

• . Voi~ Pointer : W~ know that .pointers ~re used to point


l ]. to ~•fferent d_ata types, A float pointer points to float
iol (iata[ S ' l; . variables, int type pointer points to integer ~ariables, a
~tf{''En~r e~enie~ts: "); · char type p.ointer points to character: variables. in C
.there is a generai purpose poiriter that _can point.to ~;
for(i::: O; 1< 5; ++1) . .
d.ata types and is known as void pointer. The void pointer
scanf("o/od", data+ i); is·a generic pointer that can represent any pointer type.
jtintft"You entered: \n"); The syntax of its declaration is given-below :
void *vptr; l*pointerto void *I
for(i === O; i < 5; ++i)
pnntf("%d:°"• *(data -t: i)); In C, pointers to void cannot be directly
return 0; dereferenced like other pointer \'.ariables by using*, the
indirection operator. A suitable_typecast is must priQr to
l . dereferencing a poiri,ter to void as given below :
•• r.
· + dereferencing operator
OJtput:
*((type *)vptr) .
fJlterelements: 11 +.____ type cast
l~ Here, :typ.e refers to any valid C data type. · .
ll Null pointer is a special reserved value of a pointer. A
ii pointer·of any type has such a r~served value. Formally,
each sp~cific pointer.type (int*, char• etc.) has its own
··•dedicated rull-pointer_value. Conceptually, when a pointer
fouentered: · has that null value it is not pointing anywhere. ·
II . Void potnt~r is a specific pointer type - void * - a pointer
l~
.. that poirits to some data location in storage, which doesn't
have any specific type.·So, on9e again, null pointer is a
]J · value, while void pointer is a type. These concepts are
ll totally different and non-comparable.
¼
9 · ·· ,null pointer
- Pointer Arithmetic:
Pointer arithmetic is slightly different from arithmetic W(
· Explain U,e difference between a.all by pointer normally use in our day to day life. There are foi.11
an~ a void pointer. W/1at do you ,ne /R.r.v. 2018/
ar,t/,metic'? · t . -
PPS.40~-------------:i--T--~ --:--, Prograinrnfn
arithmetic operators that can be used on pointers: ++, { ·
- - , +, and .- operators. • inputString[index]
index++; = c;
To understand pointer arithmetic, let us consider that ptr }
is an integer pointer which points. to the address I O?O. inputString[index] = '\0';
Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer- index= O;
ptr++, . . while(inputString[index] != '\0')
After the above operation, the ptr will point to _the ~ocati?n {
I004 because each time ptr is incremented, 1t will pomt putchar(inputString[index]); /* Print st .
to the next integer location which is 4 bytes next to the • rmgsto
current location. This operation will move the pointer to . . · mputString u • re.J ~
index++; . sing))Utchar,
the next memory location without impacting the actual 1
value at the memory location. If ptr points to a character } . . p

whose address is I000, then the above operation will point getch();
to the location I00 I because the next character will be retum -0; . '
avai Iable at I 00 I. }
Pointer Expression How it is enluated ?
Output-
• Enter a string
ptr= ptr + 1 ptr=>ptr + I=> 1000 + 1•4=> 1004 Neelkanth
ptr;+ or ++ptr ptr++ => ptr + I => 1004 + 1•4 => 1008 Neelkanth
ptr = ptr + 5 ptr => ptr + 5 => 1008 + 5•4 => 1028
ptr=ptr-2 ptr => ptr - 2 => 1028 - 2•4 => l020 Q. U , (a) Discuss Enume;ated data type with ih::.
ptr-or-ptr
· · of suitable code'of 'C' language.
ptr => ptr + 2 => l020 + 2•4 => l028
(b) Arrange following operators in oriftr
For example: _ precedence and associativity rules of 'C'.
+, %, <, /, *, = =, I, ++, () /R.T.U.101~
int main()
{ . Ans.(a) Enumera,ed data type: An enumeration daii
type is a user defined type, with values ranging over1
const char •p = "Hello";
finite set of identifiers cal led enumeration constant. F«
while{*p++) example ·
printf("¾c", •p ); enum color {red, blue, green};
return O; · This defines color to be of a new data type_whi~
can·assume the value, red, blue, or green. Each of~
is an enumeration constant. In the program, colorcan ~
Output: a
us~d as new type. A variable of type color can bait
ello any one of the three values: red, blue or green. ftV
example, the statement
Q.10 Write a program in 'C' to read characters one · color c; c++
. by one ahd display it hack.' /R.T.U. 2016/ defines c to be of type color. Internally, the an
compiler treats an enum type (such as color~~
Ans. integer itself. The above identifiers red, blue, an tivelY-
#include <stdio.h> represent the integer values of 0, 1 and 2 respec
#include <conio.h> So, the statements
int main() c = blue; . 11
<<c;
{ count<< "As an int c has the value
• I. • ' II

char inputString[ l 00], c; w1 II prmt As an mt, c has the value 'fled forth~
int index= O; Constant values can be explicitly speci. 1 .,,.cifted
. .
1dent1fiers. When the value for one I.dentifier elernen
is 5r- t
printf("Enter a string\n"); · ,
while((c = getchar()) !=_'\n') /* Read strllig-from ih this m~nner, the ·valu~ of _the nex}or exsrnP1"
incremented by one (next higher mteger).
.• _ ~~er using g~tchar inside while loop•;
. . if the definition of color is
.., ... ing Jof Problern Solufng

,oufll
/11- ,.a•••"'
0
-=-:----;--;--:-;~~~ --:::::------,-.-------------i
color {red•~ 10• blue, !lreen 34} : . cedence level, PPSA1
the statement c red Will a · ' Some of the operators have same pre t d
0 ,~, efore, the statement . ss,gn the value 10 so the Operators of the same precedence are eva u: _e
,, •
'
fh:' signs the value 34 to·c.
blue; ·
(If no v 1 . ·
·
on the• level. This is known as the associa
1
either from 'left to right' or from 'right to left'• depen fmg
· f vity o , ant
1 1 to ngh
i,lr as in the dee aration, it would aa ue is specifi
, ted operator. Like arithmetic operators have left . ft
.aen
,. :i' ·
ssurne the value associativity and assignment operatorshave nghtto 1e .
1;)· enumeration is a conveni~nt Way . t . associativity. . .
0
5 vt integers wit
· h meaningful
• narnes Th associate
h The table provJdes
. the 1st . of o.perators·with
. their
tan ge of generating
. the values autoin
· t·ey ave the precedence !eve I an d assoc1at1v1
· 1· ·ty ·:
.Nanta
((111 . a tea y. Use
r-i eration constants, m general makes th 11 . Table
ienUfTI
. to read an d change at a later date. e program
iss1er f 'C' I Ra11 k Ope rator
. ble code o anguage Description . ' i'\ssociativityJ
5d1ta • f b' l ()
.1nitializat10~ o an o ~ect of the enumeration type Function expression Left to Right ..
[] Array expression Left to Right
,'.1nc lude <std10.h>
Structure operator Left to Right
'
e
nurn SWITCH [off.on];
. Structure operator Left to Right
111 ain O - 2 Urtary minus Right to Left
I ++, Increinent/Decrement Right to Left ·
~urn sWITC~ s1 == on; ~ One's C,ompJ~ment Right to Left'
! Negation Rjght to Left
enum SWITCH s2 == s1, s3_== O; ·
& Address of Right to Left
~n
·ntf("The value
.
of enumeration
.
object
.
s1 is ¾d\n"' s1)·, * Value at address Right to Left
~rintf("The value of enumerat~on ob~ect s2 is ¾d\n", s2); (type) Type cast Right to Left
printft"The value of enumeration object s3 is ¾d\n", s3); sizeof Size in bytes Right to Left
3
) . * Multiplication Left to Right
Output- I
Division Left to Right'
%-
I

Thevalue of enumeration object" s 1 is I 4


' Modulus Left to Right
+
The value of enumeration object s2 is 1 Addition Left to Right
- Subtraction Left to Right
Tue value of enumeration object s3 is 0 5 <<
Remarks : Left shift Left to Right
>> Right shift Left to Right
I Enumerations behave like integers, but it is common 6 < Less tha11
t------:1---------t---:-:----,
Left to Right
for a compiler to issue a warning.message when · <= ' Less than or equal to. Left to Right
an object of !n enumeration type is init_
ialized with > Greater than Left to Right
something other than· one of .its censtants or an >= Greater than ·or equal Left to Right
expres,~ion of its type . to
7
!= Equal to Left to ~gbt
I When the enumeration .objects are init,ialized with
8 -& Not equal to Left to Right
integers, the compil~r will not check that whet~er
the initialized value is v.alid for such an enumeration 9 /\ Bitwise AND Left to Right
or not 10 I Bitwise exclusive OR Left to Right
1 Bitwise inclusive OR Left to Right
Thus, it,is even possible to initialize s3 with -8, 9 11 &&
12 " Logical AND Left10 Right
or any other integer value .
' 13 ? : Logical OR - Left to Right
i\ns,(b) Operator Precedence and Associativity Conditional/ Ternary Right to Left
14 -
In C each •operator has a precedence level Assignment , Right to Left
associated with it Precedence means, the sequence or *== I==-%==
+- - - Right to Left
Ord
er ~f different• operators in an expr~ssion
· •
an d it
&= Right to Left
/rrnines
11 Which operator will' execut~Q first or which
Right to Left
' second 'and so on. There are Pistinct , levels o(
· be long tO one
l\'ei;:ed ence and an operator may of these Right to Left
• ated
~fitls, Operator with a· higher precedence JS evalu
0 Comma
Ore J>erator with -a lower precedence., ·
· Left to Right
1
PPS.42}.-~----..:....---------,-- Progr<:1mmlng for Pro&1e
printf("\nEnter elements of matrix I :\n"); Ill So~

·.
'C' program to Input and display data
in following st,;.ucture. ·
, . .
-for(•i=0; i<rl; ++1) .
for(i=0; j<c 1; ++J)
elements of ./ts!Oti

. i
ftr~,:
Roll-No
Studehl_ .- Name
. . {_ . . .. ' . .

printf(''Enter elements a%d%d:" 1•+ .


Data - of - Birth scanf("%d", &~[i]U]); ' l,JI-});
· Course
Semester f R. r. U. 2016/ } .

printf("\nEnter' elements of matrix ·2·\n")


- - I · · ;//Si~·
Ans. • · · . _e ements of seco Llll'Jng
#~nclude <stdio.h> for(i=0; i<r2; ++i) · . nd111%
intmainO for(j=0; j<c2; ++j)
{ {
. struct dob printf("Enter.elements b%d%d:" i+I .
scanf("%d"; &b[i][i]); · - · ' ,J+I);
{ . ' .

int day; }
int month;- for(i=O;·i<rl; -i:+i)
int year; • ·11 Initializing all elements of res~l(IJlatri t
. for(j=0;j<c2; ++j) · - · ·. x oO
};
struct student { . ,

{ result[i][i] =.O;
int roll; . .} .

· char name[50]; II Multiplying matr,~aandband


struct dob d; , // storing result in result matrix
char course[50]; for(i=0; i<r I; ++i) -
int semester[50]; for(j=O; j<c2; ++j)
} s; for(k=O; k<c 1; ++k) :
. printf("\nRoll - No\n"); - {
scanf("%d", &s.roll); result[ i] [j]+=a[ i] [kI*b[k] [j];
printf("\nStudent - name\n"); ·. }
scanf("%s", &s.name); · printf("\nOutput Matrix:\n"); // Displayi~g the resull
printf("\nDate - of - bir~h\n"); . _ _for(i=0; i<rl·; ++i)
scanf("%d%d%d", &s.d.day, &s.d.m6nth, &s:d.year); -for(j=O; j<c2; ++j)
printf("\nCourse\n");
{ . . .

.
printf("%d", result[i][j]);
(

scanf("%s", &s.course);
printf("\nSemester\n"); · . _if(i.=== c2-1)
scanf("%d", &s.semester); printf("\n\n"); ··· :
return 0;
getch(); • return 0;
}, }

Q.13 Write a 'C' program to m·ultiply two Arrays of Enter elements of matrix 1:
_ . dimension /3 ?< 4] and /4 x 2]. . fR.T.U. 201'6/ Enter elements a 11: 3
Enter elements a 12: -2
Ans ..
Enter efoments al 3: 5
>#inchide <stdio.h>
·- intmain() Enter elements ~14: 5
{ ' .) . . .
Enter elements 1:·3
i_nta[lO][I0], b[l0J[I0], result[I0][IO], i,j, k; Enter elements a22: 0
Enter elements a23: 4
, :..
mt:rl=3,cl=4; r2=.4 ' c2=2·
.~ . ... ' ". .
~ ,ning for Problern Solving
~ ments a24: 5
elements a3 I : 3
elements a32: 0
-,------------IPPSA3
}
flit(( elements a33: 4 functionl O
te!
ier elementsa34: 5 {
inti;
. rer elements of matrix 2: float sum;
611 ier elements b 11: 2
fll r e)emen ts b 12: 3
EJlrer elements b2 I : -9 }
£!Ile 1. Global Variables : The variable m which has
rer elements b22: 0
been declared before the main is called global variable.
:ter elements b3 l : 0 It can be used in all the functions in the program. It need
rer elements b32: 4 not be declare in other functions. A global-variable is also
:terelements b4 l: 3 known as an external variable.
f_.ptereleme~ts b42: -9 2. Local Variables : The variables i, balance
~ utMatnx: and sum are called local variables bec~use they are
;9 •J6 declared inside a function. Local variables are visible
and meaningful only inside the function, in which they
21-20 are declared. They are not known to other function. The
storage class has another qualities (like long or
unsigned) that can be added to a variable
.71 -20 -~ auto int count;
1'"-<
register char ch;
t.ftfdftype
What is scope of variable in 'C' meant' Ex l .
casting in detail also P am
/R.T.
static 1nt x;
OR · . .U.2015/ extern long total ;
Storage Meaning
What is meant by scope of variables in C? Auto Local variable which known only to ,.
What are tl,e different types of variables on the function in which it is declared.
tl,e basis of scope? List and explain wit!, Default is auto.
example? _ . [Raj. Univ. 2005/ Static Local variable which exist and
(b) Explain the difference between automatic retain it value even after the control
and static variable. /R.T.U. 2015/ transferred to the calling function.
Extern Global variable known to all
Ans.(a) In C the scope of variables means that in functions in the file.
functions the value of the variable would be available. Regis~er . Local variable which is stored in the
C provides a variety of storage class specifiers register.
that can be used to declare explicitly, scope and life time Type Casting or Conversion
of variables. The storage class decides the portions of Type casting means of conversion ofone data type
ilie program within which the variables are recognized. to another data type. For example, a float value can be
There are basicaily two types of variables on the basis converted into an integer value. There are two tyes of
of scope. type casting that are discussed below :
(I) GlobalVariable (a) Implicit type casting
(2) Local Variables (b) Explicit type casting
Example : int m; (a) Implicit Type Casting : In implicit type
main() casting, the conversion is done automatically by the
{ compiler. In this type ~f conversion, a smaller da~ type
inti; is converted into a larger data type. For example, a float
float balance; value can be converted into.a double value because the
size of the float value is.4 byte.and the size of the double
· value ~s 8 bytes. So, it is possible for a double variable to
function l (); take a float value. No operator is required in an implicit
PPS.44~----------------.---------1 Programming
conversion. This is done without any intervention of the {
programmer. · int a, b;
(b) Explicit Type Casting : In explicit type clrscr( );
casting, the conversion is carried out between two · printf (''\n enter two numb
incompatible types. ers·")·
scanf("%d%d", &a, &b); · '
For example, a float value can be converted into swap( &a? &b );
an interger value. This is done with the help of the (type) printf(''\n values after swap •
operator. The syntax is as follows : and b = %d", a, b); Pingarea:::,,
data_type var! = (type) var2 } ''d
For example void swap (int* x, int* y)
inti= (int) I0.23 {
In the above example, the value ( I 0.23) is int t;
converted into an . integer value ( I 0) and after that the t= *x;
resultant value ( I 0) is assigned to the variable i. Here int *x= *y;
is used as a (type) operator to convert the float value
*y =t;
into an integer value.
geich();
· Ans.(b) Difference beti¥een Automatic and Static
Variable
}.
Output : Enter two numbers :
s. Static Variable Automatic Variable
No. a=20
I. We have to specify the It is the default storage b= IO
storage class to make a class. Values after swapping are
variable static. a= 10
2. If it is not assigned any If i_t is not assigned any b=20

~fi
-. value then it will give 0 value then it wil Lgive
as output. garbage value as is the difference between· Constant and
output. Variable? What are the data types in 'C'? Explain
3. It is visible to the block It is visible to the block
witlt examples; . /R. T. U. 2014, Raj. Univ. 200~ 2001/
in which it is declared in which the variable is
OR
and also in the function declared.
where it will passed. Wltat is tlte difference between Constant lllld
4. It retains its value Variable? /R. T.U.2011/
It retains its value till
between different the control remains in
function calls. It holds the block in which the Ans. Constant
its last value. variable is declared. Constant
5. Static variable should Auto variable will + 7
be compile by compiler compile by the Integer Floating String
Character
first. . compiler after the static Constants Point Constants L~erals
variable.
Octal System
Decimal System
Q.15 Write a C language program to SWAP two
numbers using pointers and function. Hexadecimal System :,.
. the en1u•
/R.T.U. 2015} A constant does not change its value dunng .fi das
1
OR execution of the program. They can be clasSI :tion
Write a program in C language for swapping integer, floating point, character and enumer
two numbers using pointer. /R.T.U. 20JJ, 2008/ constants. . re resent
(i) Integer Constants : C++ allows t0 P 1
are octa '
Ans. #include<stdio.h> the integer constants in three forms. Th
. ey
#include<conio.h> decimal and hexadecimal. . bers are
void swap(int*, int*); (a) Octal System (Base 8) : Octal n;.mits t,eiPS
void m~in~) . specified with a leading zero, rest of the ig

I
r
for Problem Bowing
~and 7. For instance, 0175 is~an:::in:----,----~---------1
;t~ in oct.al whose base- IO (decim teger COOStant value of variable can vary during the ex:eeution of I: C
/if~ J)tcimal System (Base 10) _a;~~alue is 125. program. A variable name can be chosen by t~e I
(b 1y used sy5rem. A number · · .15 th e most programmer in a meaningful way so as to reflect 0~
,~
011
ted by using digits o. I0. For i~:~h,s sygtem i.s . function or nature in the program. Some example!
nee, 175 is an such names are :
11
canstant with base l O.
ff_ 9e1,1decimal System (Base l6) . . Average
(cl are·specified with Ox or Ox in ;hHexa~ecimal Height ..
~ ~ts that follow Ox must be numbe . e beginning. To fal
'1lt dtt," I tt . f rs in the rang.e 0•
1•· eof the e ers a- or A-F. For exam Counter -1
0 11 1 1 15
9~ r canstant specified in hexadecim e,hOxa an Rules for Comtructiog Variable Names
1 8
ff (leCimal value is 161 . Oxa 1 is the .a w ose base. (a) A variable name is any combination of to
10 ~ i.e., either a lower case or an up same as Ox.at , or alphabets, digits or underscore. Some compilers allow
· per case x can be variable names whose length could be upto 40 characters.
¢l°(i0 f1oati•~ _Point Constants (b) The first character of the variable name-must be
floating pomt constant have a decimal . an alphabet or underscore ( _ ).
~ nt sign, or ~th. pomt, or an (c) Variable name should not be a keyword.
pecimal Notation : Here the numbe . (d) No commas or blank spaces are allowed within
r 1s represented .
whole num ber, fioIlowed by a decim 1 . a vanable name.
part. It 1s
· poss1•b le to omit digitsa pomtd fteand a (e) No special symbol other-than an underscore (as
8
~onal
. 1point an a r the in aross_sat) can be used in between a variable name.
ittirna
Example of valid . floatmg
. point constant. (f) Uppercase and lowercase letters are different. ·
125.45 241. .976 -.7·l + Example : NUM, num, Num are three different
5
Exponential Notation : Exponent,·at t .· . variables.
. . · no ation 1s u i·d u
..J.ij m representmg numbers whose magn·t d .-a 1 ,-ariables
~•" 1 u es are SI . Gross_salary Average numl23
"")large.or very small. The exponential notati·o n consist .
tot_amt net bal age
ofamantissa and an exponent. The exponent is posit·
db . 1ve RESULT
iailesS preced_e Ya mmus sign. The number 231.78
Invalid Variables
canalso be written as 0.23718e3, representing the number
12num first character should be letter or
o.23178*103• Th~ sequence of digits 23178 in this case
underscore
after the decimal point is called the mantissa and 3 is
float keywo~d
called the exponent. ·
S.I. Illegal special symbols
For example, the number 75000000000 can be written
to~lamount blank space is not allowed
ll75e9or0.75el 1. Similarly, the number0.00000000045
nl#n2 Special symbol other than underscore
can be written as 0.45e-9.
(iii) Character Constants : A character constant
is not allowed
S.No. Constant Variable
~enclosed in single quotes. 1. Constant is the named Variable is the named
Example: Valid character constants: 'a' '5' '\n'. memory location memory location
Invalid character constants : 'ab' '54'. who's value can'rbe whose volume or data
(iv) String Literals · changed or fixed can be change during
during the execution the execution of the
. Astring literal is a sequence of characters enclosed of program. • lorogram.
llld~uble quotes. The characters may b~ letters, numbers, 2. Syntax : Const data Syntax : Data_type
Clcape sequence, or blank space. To make it easier, string type Constant_Name Variable_Name;
= Vaule;
:nsta.ntare concatenated at compile time. For example; 3. Constant must be Variable can be
estrings. initialized at the time initialize after its
"C++ is the best" and of declaration. declaration.
"C++ is" "the best" are the same.
.
Data Types m 'C'
1 Variables · ~ata Types: Data type is used to define.the
1.. variable·can be considered as a name given to the of vanable ·that we declare at th. e begmmng
. . oftype th
v.:atio n ·m memory where the constant is stored. The program. There are basically two types of data types. e
_ _ _ _ _ _ _ _ _ _ _ _ _ __..:.-,---::::::::~ Programming for Pr
,=-_~--- • Ob~~
_P_P_S_.48~ Primary data types discussed above h So~
I. Primary Data types xplained in the following table with their~"ea1So~
2. User Defined Data types :pace and format Specifiers. &e,~Ci), ,
A. Primary Data Types Table : Data Type l)
. The primary data types in C are follows :
J. int Data Ty e Ran g e
2. float signed char -128 to + 127
unsigned char O to 255
3. char
signed int . -32768 lo+ 32767 I
4. void unsigned int O to 65535 2
The user defined data types are : structure, array, long signed int -2147483648 to + 2147 2 ~,ci
483647
union, enum, etc. These data types are discussed later. long unsigned int O to 4294967295 4 ¾
float -3.4e38 to + 3.4e38 4 ~oli
1. int : An integer variable can store any number .
· double -J.7e308 to +l.7e308 4 ½r
in the rang; -32768 to + 32767. That is because an 8
long double . -l.7e4932 to+ l.7e4932 %Ir
integer variable always occupies two· bytes in memory IO
and in two bytes we cannot store a number bigger t~an B. User Defined Data Type : i~ f.. i '-Lr
+32767 or smaUer than - 32768. . II d
a feature m C a ows users to efine ·an idenf fi 1.1 e I01
tion
Example:
. intabc;
would repre~ent an existing data type. The
data type can later be used to declare variable fineo
us~~;thai

inti; s.
It's general f is typedef type identifier wh
C offers a variation of the integer data types that type refers to an ex1stmg data type and identifier
· will provide what are called long integer values. Long to the "new name ~iven to the data type"
t
re el'l
integers occupy double space than int, it mean long integers
e;g. typedef int marks
would occupy four bytes of memory. Long variables
which hold Jong integers are declared using the keyword typedef float percentage
long: The values of a Jong integer can vary from - Here units symbolize int and marks symboliu
2147483648 to+2147483647. float. They can be later used to declare variables as
Example: follows
Jong inti; units · batch I, batch2 and marks namel ,[50),
long int ABC; name2 [50] 1
. 2. char : char data type can store any single where batch I - and batch2 are declared· as int
character and occupy only 1 byte of memory· space. variables and name I [50] and name 2 [50t aredeclared
Declaration of char data type is as : . , as SO·element floating point array variables.
char ch;
The main advantage of the data type (typedeQ is,
3. float: Afloat occupies four bytes in memory ~e ca? create meaningful data type names for
and can range from -3.4e38 to +3.4e38. If this is mcr~asmg the readability of the programme .
insuf~cient then C offers a double data type which
These are defined data types are : arrays, ,
occupies 8 bytes in memory and has a range from· _ structures, union, enum etc. · ·
1.7e308 to +1.7e308.A variable oftypejloatand double
can be declared as -= Structures : Refer to Long Answer Q.4.
Example: Union : Refer to Long Answer Q.4.
float· marks·, Pointers : Pointers are the special variables used
double salary, amt; 0
·!
~oint other storage spaces of same kind as the name
If there is any requirement to store a value that md1cate. Empty data set is used in functions.
can not be stored in double data type variabl th . . Enumerati~n : Refer to Long Answer Q.IJ(a).
c · ·l ...1 • . e en we
an use ong uoub/e, which occupies 10 byt f
memory. . es o . . and
Q.17 Wrtte a program of add two numbers if
Example:
explain this program step by step with the ht!~,
long double average; . . flow Jchart /R.T.U. 2ou, 10/1, Raj. Univ. J()()6,
. 4. void : void is a - speciaf data type which .
store any type of constant value W
data type. ·
. ,can,n~t.
· e can say1t.a dummYs Ans. A program to read. two numbers and display we
total is as.follows :
#include <stdio.h>
g for Problem ~I
) ---r------------~ppSA7
Flowchart
I
int a,b,c; START
printft" Enter the values of
.r•<O /. d o/. d" a and b")·
scan•\ , o / o , &a, &b); , Input
c =='a+ b; . a,b
printf("'Sum= ¾d", c);
c=a+b
)
, 1111 tion of the Program
1
1)1' #i11clude<stdio.h> : Refer to Sh . Print c
11111in0 ort Answer Q. J.

{ STOP
l Fig.
ttere, main() is a function • Every •c• To read an input we use READ statement and
tlliriSat least one or more than program to print some output we use WRITE statement. As these
(1111_,; n which is compulsory that ~ne f~nctions. One
statements are input/output statements, these ~re
~nl,V0
t,r3C
es enclose the defimtton
.. 1s mam() Th
of th e fiunction
. · ese {} enclosed within Input/Output box.
;nt a, b, c ; ·
This line declares three va na • bl es a band Q. ~ ,,-Wri/e a program· to c/,eck whether the input
f
jnreeer data type. Two bytes are allocated' t co number is prime or not.
/R. T. U. 2014, 20Il, Raj. Univ. 2004/
,
,ari;bles. With this line an address . 1
. I D
° all these
is a so allocated to
tbese varrab es. ata types have been 1• .
·t chapter exp amed m detail Ans. #include<stdio.h>
~nex · #include<conio.h>
printf( "·----~ ); void main()
This
. line or printfO
. function prints th t {
"hich 1s enclosed m double quotes. int f= 0,n,i;
.scanf( "¾d ¾d", &a,&b); clrscr();
This scanf() function scans that type of values d printf("\nEnter a number");
0
umberof values specified in double quotes. Here dou~e scanf("¾d" ,&n);
iuotes contain two "¾d¾d", which indicates that here for(i=2;i<n;i-++)
~f() function scans two integer type values which are {
¢ven to variables a and b. Address of these variable is if(n¾i==O)
accessed by address operator(&). { f= I;
c= a+ b; · break;
Assignment operator(=) solves the right hand side }
expression and assign it to left hand side variable which }
if(f==O)
ischere.
printf("\nNumber is Prime");
printf("Sum= %d", c);
else
Here printf() function doing the ~ame job which is
printf("\nNumber is Not Prime");
iefined above. Here ii also prints the number of values
getch();
which are enclosed in double quotes. Here double quotes
}
contain one "¾d" so it will print one integer type value·
Output:
which is of c. Enter a number 5
Output Number is Prime
Enter the values of a and b
10 .• Q.19 Explain structure of program in C language
20 . r briefly. . /R.T.U. 20UJ
Sum= 30
,nlng for Problem Solving

~tshell,
(rt each
• function 111
· ust conta· _. - - - - - , - - - - - - - - - - - - - - - - { PP5A9
I. A fun_ ct1on heading, Whi·c in; . th
h Ans. Header Files : These are the files at are
function name. The fi . consists of th
· . unction e included at the top of any program. If we use_ ~ny
contain an optional 11·st of argu narne rni·ght fu nction inside a program, then the header filI e contammg
in paranthesis. lllents enclosed h t be
declaration or definition of that function, as 0
st
2- A li_ ~fr:~ment declarations if included. Like printf() is defined in stdio.h. So, we mu st
are me u e m the headin · ' argurnents include it (by #include in order to use printf().
3 Astatement which fonns th!· rest Library Files : These are the files which the
th
4·· parameters or argume 11 t
s that
of e function, compiler uses in order to define the functions which have
information· to be passed be . represent been used in the program and had been declared •?~• · "de
th
and oth~r parts of the progr:~n e function the header file. Like, printf() has its complete defimtt?n,
Expression statem i.e., how it will work etc. in an 1/0 library. So, the compiler
5. semicolon(;).
. ents which en d with a uses that library to get the machine cpde fior pnn · tfi'I)
'- ·
6_ Comments can be given Differences
program to explain the und:~{?'here !n
the • Header files are TEXT files while library files
program. Comment lines are t ng lo_g1: of a
delimiters /* and • C0 . p aced within the
are BINARY. This means, we can read and
modify the h~ader file but not the library file:
· mments ar ·
and may or may not be giv . e optional • Hea~er file is in Clangu~ge while the library fi!e
en m a program. is in machine language.
~
~~~a:"it:.::a:p:ro:,o:r::~,
Q20 "' e o
~~~=====~
am o print reverse 0,r
• Header file has to be included by the programmer
· using function. J a number while the compiler automatically relates the
/R.T.U. 20UJ library file(s) with the program.
~ . /*c program for reverse number using user d fi
·runct1.on- rev */ e me Q.22 (a) List aritl,metic and logical operators
#include<stdio.h> available in C
int rev(int); (b) Write a program to find sum offollowing n
int main() terms of a series. 12, z2, 32, 42, ...
{ /R.T.U. 2012/
int num,res; //res= result
printf("Enter any number: "); Ans. (a) Arithmetic Operators
scanf("%d", &num); · Arithmetic operators are used to perform numeric
res= rev(num); calculations. These can operate on any built in data type
printf("Reverse order number= %d", res); allowed in C. These operators are listed below in the
return O; · table I:
Table I : Arithmetic Operators
int rev(int n) Operator Symbol Meaning
{
+ Addition or unary plus
· int r= O;
- Subtraction or unary _minus
for(; n> 1; n=n/10)
* Multiplication
r=r* 10+n%10; I Division
return r; % Modulo division (applicable only
}
on int data type)
The output of above program would be : Logical Operators
Enter any number: 7941
Logical operators are used to combine two
Reverse order number= 1497
expressions. These operators check logical relation
between the two or more expressions. Depending upon
QJl Is there· any difference between /1eader file the true and false n~ture of the expression they assigned
and library file? Explain. /R.T.U. 20131 value l and 0. Logical operators are listed below in the
. ,
. ,. table 2.
' . '
PPS.50
~---------------ir--::-:::::~~P;ro:g~ra;m~m~in~g~Ji~or
(iii) If both age is greater than 25 an:b~
Pr, 111
So~:-
Table 2 • Logical Operators than I0000. Salary gr":-"
1
Loe-ical Ooerators I Meaninl? (iv) Only, if age is not greater than 25
&& AND not greater than I 0000 then the condition Wil~nd salary .
resu1t ~1 ,
1
II OR J. Logical Not (!) Operator
II
NOT st
! This is a unary operator. This operator ·
The logical operators && and ii are used w~e~ we true value into false and a. false value into truec nve11 a
0

want to test more than one condition and make dectSions. Table 5 : Logical Not(!) ·
-Example : z > y && x = = I0 Condition Result
An expression of this kind, which combines tw~ or · True False
more relational expression is termed as a logical False- - - - - ---1-:..:.::,:::'......_
True
expression or a compound relational expression. 'Example: ! (a> b)
1. Logical AND(&&) Operator Here, if a is greater than b then the act 1
ua res 1
Logical AND works with two or more oper~ds true, but we have used ! operator before the e utis
and.gives the result true if all the operands in the cond1t1on so the result will be fals~ And if a is not greatession
th
have true value otherwise it provides the result false. then the result will be false, but ! will convert it ~r an b
' . • into tru
Table 3: Logical AND(&&) Ans. (b) # include <std10.h> e.
Operand 1 Operand 2 Result # include <conio.h>
False False False void main ()
False True False {
True False False inti, n;
True True True long sum= O;
Example : Assume we want to compare age a~d clrscr ( );
salary of an employee printf ("Enter the value of n =");
age > 25 && salary > I 0000 , ·scanf ("%d", &n);
Here, from the above example if age of the for (i =I ; i n; i ++)
employee is greater than 25 and SajllY is greater than sum = sum + i * i;
10000 then the result wiJJ be True ( l) only, otherwise printf (" sum of series= % Id", sum);
result will be False (0). getch ();
2. Logical OR ( :: ) Operator }
Logical OR works" with two or more operands and Output
gives the result true ifone ofthe operands in the condition Enter the value of n = 5
have true value, otherwise it provides the result false. Sum of series =-55.
Table 4 : Logical OR ( :: )
1 Operand 1 f Operand 2 Result
Q, 3 iai are tlte ad.vantages and disadvantages 0!
False False C language? • /R.T.U.2011/
False
False True True
True False True Ans. Advantages of C Language ·
True True ·True (i) C is a building block for many other curreotlY
· Python for
Example : Assume that we want to compare age known languages. Take a look at
. 0 . t d High-Leve1
and salary of an employee example a fully ObJect-. ne_n e . rbaj)S
progr~ming language. It is wntten mC(peknow
age > 25 :: salary > 10000
C++too). That tel ls you ifyou ever wan~ to tber
. Here, in the above example the condition will be . what is going on under the hood_ in °,,,is
true in all the foHowing cases : . C dhow1twor,.,,
languages; understanding an
(i) If age of employee is greater than 25, salary
essential. . . reted
can be anything. . .
(ii) C is a compiled language vers~s an mte%atthe
(ii) If salary of employee is greater than 10000 language. Explained simply, this ~eanscriOfl (in
. '
now age can be anything. · code is compacted into executable mstrU
,riing for Problern Sor ,
,.ofll : - - - - - - u,ng
tl1e case of windows anYW .
''translated" on the fly at ay) ratherth·a=~n:-b--.-r-------------~PPS.51
also lends heavily to the srun time. This fea:~ng printf("Largest Number is: ·%d",max);
..) Alot of l'b · are writt Peed
t ranes . ofc programsre } //Output: Largest Number is: 96
(ill • en inc ·
. ) The roam advantages of c 1 ·-
(1V - anguage •
is not muc11 vocabulary t I ts-that there
o earn d
programmer can arrange for th ' an that the
fast. C programming langua e_program is very
. ge ts very .
Jeam. C programming langua . easier to
gets still .
and compact anguage. It com . a practical
1
_semantic. Syntax is ofC is clear r•ses a good
is very near to assembly progr:~o. la~guage
hard use of pointers for exam mi~g r.e. the
powerful mechanism. . .Pie ts a very
(v) c has features that allow th
organize programs in a clear :~rora~mer to
For example, C allows me;nin i°g1cal way.
variaples without any loss of ffig u_ names for
. a. comp Iete freedom of progr
gives e ic1ency . ' yet it
. I d' fl 'bl ammmgstyle
me u tf~flg ~bxl1 ~-ways of making decisions and
a set o ext e commands for pe c . · '
· · Iy (for, while, do). - riormmg tasks
repetitive.
(vi) C is a portable language.
Q.25 (a) WJ,at difference will cause if we use
Disadvantages of C-Language
(i) getcliO in place of getc/1e()
(i) C does not have OOPS (eature that's why C++ (ii) getc/1e() in place of getc/1()
is developed. ·
(iii) puts() in place of printf()
(n) There-is no runtime checking in C language. (iv) gets( ) -in place of scanf()
(iii) There is no strict type checking (for e.g. we can (b) Give one line C statements for performing
pass an integer value for the floating data type). tlte following :
(iv) C does not have the concept of namespace. (i) Printing Hello on tlte screen.
(v) Cdoes not have the concept of constructors and (ii) Printing a decimal ... umber.
· destructors. (iii) Printing a number in octal f ormaL
(iv) Inputting an octal number.
Q,2 raw the flow chart and write a C program to (v) Input~ing a string.
find out.largest number in a given list of 10 (vi) Cltoosing larger of two numbers.
numbers. /R.T.U. 2010, Raj. Univ. 2002/ (vii) Converting an integer to a floating point
only wl,en required.
Ans.#include<stdio.h> · (c) How constants are defined in C language?
void main( ) _ Give one example. /R.T.U. 2009/
{
i~\ list[] = {10,40,75,35,46,67,23,96,34,35}; _ Ans.(a)(i) and (ii) getch( ) : getch gets a character
int max,temp; from console but does not echo to the screen that it.reads.
max= list[0]; getche ( ) : getche gets a character from console,
for(int i = 0;i<l0;i++) and echoes to the screen and the character that we read
{ require enter key to be pressed after it.. ·
g
temp= l1st[i]; Declaration:
.jf(max<temp) int getch(void);
.max= temp;
I : J:1 'int getche(void);
} ',iu · '.-·-

You might also like