PPS Material (Vidhyadeep)
PPS Material (Vidhyadeep)
A) Computer Fundamentals
1 Draw the block diagram of computer architecture and explain each block.
Computer is made up of mainly four components,
1) Central processing unit (CPU)
2) Input section
3) Output section
4) Storage devices
ALU + CU
PRIMARY MEMORY
(RAM, ROM, etc…)
1
This memory is accessed by CPU, in random fashion
Generally currently executing programs and data are stored in primary memory
Its storage capacity is very small compared to secondary storage.
It is very fast in an operation compared to secondary storage
RAM is Random Access Memory and it is volatile in nature.
ROM is Read Only Memory and it can hold data permanently.
PROM is Programmable Read Only Memory and it can hold data permanently. Programmer
can store information only once. Modification is not allowed.
EPROM is Erasable Programmable Read Only Memory. It can hold data permanently.
Programmer can delete and write on it again and again.
2) Input Section:-
The devices used to enter data in to computer system are called input devices.
It converts human understandable input to computer controllable data.
CPU accepts information from user through input devices.
Examples: Mouse, Keyboard, Touch screen, Joystick etc…
3) Output Section:-
The devices used to send the information to the outside world from the computer is called output
devices.
It converts data stored in 1s and 0s in computer to human understandable information
Examples: Monitor, Printer, Plotter, Speakers etc…
2
same form. It works 24 hours without any problem as it does not feel tiredness.
Automation: Once the one task is created in a computer, it can be repeatedly performed again by
single click whenever we want. For example, once the software for banking application is installed in a
computer, it computes the interest by sending one command.
Limitations
Lake of intel igence: It cannot think while doing work. It does not have natural intelligence. It cannot
think about properness or effect of work it is doing. It can only execute the instructions but it cannot
think about the correctness of these instructions.
Unable to Correct Mistakes: It cannot correct the mistakes by itself. So if we have provided wrong
or incorrect data then it produces wrong results or performs wrong calculations.
3 Describe various types of computer languages and mention its advantages and disadvantages.
Computer languages may be classified in three categories,
1) Machine level language or Low level language:-
Computer directly understands this language. It is a language of 0’s and 1’s (binary). Every CPU
has its own machine language.
ADVANTAGES:
1. It is very fast in execution
2. It does not require any extra system or software to run the program.
3. Translation is not required.
4. Suitable for low volume applications.
DISADVANTAGES:
1. Programs are long and difficult to write and understand for human.
2. Debugging is very difficult task.
3. It is not portable.
4. Programmer requires detailed knowledge of architecture of microprocessor.
2) Assembly language:-
Every machine language instruction is assigned to English word MNEMONIC such that it should
describe function of instruction.
System cannot understand this language directly so we require translator that convert assembly
language to machine language. This translator is called assembler.
Example : 8086 Instruction Set
ADVANTAGES:
1. Programs are easy to understand compared to machine level language.
2. Programs are smaller in size compared to machine level language.
3. Programs can be entered quickly using alphanumeric keyboard.
DISADVANTAGES:
1. It is not portable.
2. Programmer should know structure of assembly language of microprocessor.
3. It requires assembler as a translator.
3
It is similar to natural language and mathematic l notation.
Example: C, C++, Java, etc…
ADVANTAGES:
1) Easier to learn.
2) Requires less time to write.
3) Provides better documentation.
4) Easier to maintain.
5) It is portable.
DISADVANTAGES:
1) It requires compiler or interpreter to convert higher level language to machine language.
2) Programmers need to learn structure of high level language.
3) It is bit slow compared to low level and medium level language.
4
2) Special purpose software: It is used by limited people for some specific task like accounting software,
tax calculation software, ticket booking software, banking software etc… It is designed as per user’s
special requirement.
5
B) Flowchart & Algorithm
1 What is Algorithm? What is Flowchart? Write down the advantages and disadvantages. Compare
them.
Flowchart
Flowchart is a pictorial or graphical representation of a process. Each step in the process is represented by a
different symbol and contains a short description of the process step. The flow chart symbols are linked
together with arrows showing the process flow direction. This pictorial representation can give step-by-step
solution of the given problem.
Advantages
Easy to draw.
Easy to understand logic.
Easy to identify mistakes by non computer person.
Easy to show branching and looping.
Disadvantages
Time consumin .
Difficult to modify.
Very difficult to draw flowchart for big or complex problems.
Algorithm
An Algorithm is a finite sequence of well defined steps for solving a problem in systematic manner. It is written
in the natural languages like English.
Advantages
Easy to write.
Human readable techniques to understand logic.
Algorithms for big problems can be written with moderate efforts.
Disadvantages
Difficult to debug.
Difficult to show branching and looping.
Jumping (goto) makes it hard to trace some problems.
Comparison:
Flowchart Algorithm
Solution is shown in graphical format. Solution is shown in non computer language like English.
Easy to show branching and looping. Difficult to show branching and looping.
Flowchart for big problem is impractical Algorithm can be written for any problem
2 Explain various symbol used in flowchart.
Start / Stop
Input / Output
(Read / Print)
Process
Decision making
Subroutine
Arrows
Flowchart:-
Read No
Yes No
Is No mod 2=0?
stop
4 To enter number still user wants and at the end it should display count of total number of positive,
negative and zero entered.
Algorithm:-
Flowchart:-
start
pos0,neg0,zero0
Read no
Yes No
Is no>0?
Yes Is no<0? No
pospos+1
negneg+1 zerozero+1
No
stop
5 To print maximum number from a given 3 numbers.
Algorithm:-
Step 1 : Read a ,b, c
Step 2 : If a>b, goto 5
Step 3 : If b>c, goto 8
Step 4 : Print c is maximum goto 9
Step 5 : If a>c, goto 7.
Step 6 : Print c is maximum, goto 9
Step 7 : Print a is maximum, goto 9
Step 8 : Print b is maximum
Step 9 : Stop.
Flowchart:-
start
Read a, b, c
Yes No
Is
a > b?
Yes No Yes No
Is Is
stop
6 To find the factorial of a given number.
Algorithm:-
Flowchart:-
start
Read no
count1,fact1
count count + 1
Yes Is
No
Print fact
stop
7 To solve series 1!+2!+3!+4!+ ............ +n!
Algorithm:
Flowchart:
start
Read no
count1,fact1,sum0
factfact * count
sumsum + fact
countcount + 1
Is
Yes
Print su
stop
Computer Programming and Utilization (CPU) – 110003
C) C Fundamentals
1
The string f rmat consists of two types of items - characters that will be printed on the screen, and
format commands that define how the other arguments to printf() are displayed.
printf() retu ns the number of characters printed.
Data Type in C
b. char
char data type can store single character of alphabet or digit or special symbol. Each character is
assigned some integer value which is known as ASCII values.
signed Unsigned
Size (bits) Range Size (bits) Range
char 8 -128 to 127 8 0 to 255
c. float
float data type can store floating point number which represents a real number with decimal
point and fractional part. When the accuracy of the floating point number is insufficient, we can
2
use the double to define the number. The double is same as float but with longer precision. To
extend the precision further we can use long double which consumes 80 bits of memory space.
Size (bits) Precision Digits Range
float 32 6 3.4E-38 to 3.4E+38
double 64 14 1.7E-308 to 1.7E+308
long float 80 3.4E-4932 to 1.1E+4932
d. void
The void type has no value therefore we cannot declare it as variable as we did in case of int or
float or char. The void data type is used to indicate that function is not returning anything.
Constants
Integer const ant Real constant Single character constant String constant
3
Integer constant:-
Integer constant is a number without decimal point and fractional part
There are three types of integers constant.
o Decimal integer
Decimal integer consist of a set of digits, 0 to 9 having optional – or + sign. No other
characters are allowed like space, commas, and non-digit charcters.
Ex: 123, -321, 0, +78
o Octal integer
Octal integer consists of any combination of digits from the set 0 to 7. Octal numbers are
always preceded by 0.
Ex: 037, 0, 0551
o Hexadecimal integer
Hexadecimal integer consists of any combination of digits from the set 0 to 9 and A to F
alphabets. It always starts with 0x or 0X. A represents 10, B represents 11… F represents 15.
Ex: 0X2A, 0x95, 0xA47C.
Real constant:-
The number containing the fractional part is called real number. Ex: 0.0083, -0.75, +247.0, -0.75.
A real number may also be expressed in exponential notation.
The general form is: mantissa e exponent, ex: 215.65 can be written as 2.1565e2.
In exponential form, e2 means multiply by 102.
String constant:-
A string constant is a sequence of characters enclosed within a double inverted comma.
The characters may be le ter, number, special character, blank space, etc…
Ex: “DIET”, “1988”, “?A.B,!”, “5+3”, etc…
‘A’ is charac er but “A” is string.
4
The tokens are the basic building blocks which can be put together to construct programs.
There are six classes of tokens in C: identifier, keywords, constants, string literals, operators and
other separators
Identifier:
An identifier is a sequence of letters and digits.
The words which are defined by programmer in a program are known as identifier.
Identifier refers to the name of variables, functions and arrays.
Keyword:
Keywords are reserved words whose meaning is fixed and they are used for some special purpose by
the compiler.
They cannot be used by programmer for other purpose.
void - data type:
void is a primary data type. void means nothing, no value.
It is generally used to show that function is not returning anything.
5
= Assigns value of right side to left side
+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1
5. Increment and Decrement Operators
These are special operators in C which are generally not found in other languages.
++ Increments value by 1.
a++ is postfix, the expression is evaluated first and then the value is incremented.
Ex. a=10; b=a++; after this statement, a= 11, b = 10.
++a is prefix, the value is incremented first and then the expression is evaluated.
Ex. a=10; b=++a; after this statement, a= 11, b = 11.
-- Decrements value by 1.
a-- is postfix, the expression is evaluated first and then the value is decremented.
Ex. a=10; b=a--; after this statement, a= 9, b = 10.
--a is prefix, the value is decremented first and then the expression is evaluated.
Ex. a=10; b=--a; after this statement, a= 9, b = 9.
6. Conditional Operator
A ternary operator is known as Conditional Operator.
exp1?exp2:exp3 if exp1 is true then execute exp2 otherwise exp3
Ex: x = (a>b)?a:b; which is same as
if(a>b)
x=a;
else
x=b;
7. Bitwise Operators
Bitwise operators are used to perform operation bit by bit. Bitwise operators may not be applied to float
or double.
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left ( shift left means multiply by 2)
>> shift right ( shift right means divide by 2)
8. Special Operators
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection perator, used in structure.
-> member selection perator, used in pointer to structure.
8 Explain conditional operator (ternary operator) with example.
C provides special conditional operator ( ? : ) to evaluate conditional expression in single line.
6
It is also known as ternary operator because this is the only operator in C which requires three operands
or expressions.
Syntax: expr1? expr2 : expr3
First of all expr1 is evaluated, if it is nonzero (true) then the expression expr2 is evaluated otherwise
expr3 is evaluated. Only one of expr2 and expr3 is evaluated.
Example: c = a>b? a : b; // If a is greater than b then a is assigned to c otherwise b.
9 What is type conversion? Explain implicit and explicit type conversion with example.
When an operator has operands of different types, they are converted to a common type, this is known
as type casting or type conversion.
Typecasting is making a variable of one data type to act like another data type such as an int to float.
Implicit Type Casting:
C automatically converts any intermediate values to the proper type so that the expression can be
evaluated without losing ny significance.
This automatic conversion is known as implicit type conversion.
The lower type is automatically converted to the higher type before the operation proceeds. The
result is higher type.
Example:
o If one operand is int and other is float then int will be converted to float.
o If one operand is float and other is long double then float will be converted to long double.
Thus conversion happens from low data type to high data type so that information is not lost. The
conversion hierarchy is shown below.
longdouble
double
float
Conversion
Hierarchy unsigned long int
long int
unsigned int
int
short char
7
void main()
{
int sum=47, n=10;
float avg;
avg=sum / n; // implicit type casting
printf(“Result of Implicit Type Casting: %f”, avg); // This will print 4
avg=(float)sum / (float)n; // explicit type casting
printf(“Result of Explicit Type Casting: %f”, avg); // This will print 4.7
}
10 Explain operator precedence and associativity.
Precedence of an operator is its priority in an expression for evaluation.
Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2), giving 11, and not as
(5 + 3) * 2, giving 16.
We say that the multiplication operator (*) has higher "precedence" or "priority" than the addition
operator (+), so the multiplic tion must be performed first.
Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the
same precedence.
Operator associativity is why he expression 8 - 3 - 2 is calculated as (8 - 3) - 2, giving 3, and and not as
8 - (3 - 2), giving 7.
We say that the subtraction operator (-) is "left associative", so the left subtraction must be performed
first. When we can't decide by operator precedence alone in which order to calculate an expression, we
must use associativity.
Following table provides a complete list of operator, their precedence level, and their rule of association.
Ra k 1 indicates highest precedance level and 15 is the lowest.
Precedence Associativity Operator Description
1 Left to Right () Function Call
[] Array Element Reference
2 Right to Left +, - Unary Plus, Unary Minus
++, -- Increment, Decrement
! Logical Negation
~ Ones Complement
* Pointer Reference (Indirection)
& Address
sizeof Size of an object
(type) Type Cast (Conversion)
3 Left to Right * Multiplication
/ Division
% Modulus
4 Left to Right + Addition
- Subtraction
5 Left to Right << Left Shift
>> Right Shift
6 Left to Right < Less than
8
<= Less than or equal to
> Greater than
>= Greater than or equal to
7 Left to Right == Equality
!= Inequality
8 Left to Right & Bitwise AND
9 Left to Right ^ Bitwise XOR
10 Left to Right | Bitwise OR
11 Left to Right && Logical AND
12 Left to Right || Logical OR
13 Right to Left ?: Conditional Expression
14 Right to Left ==, *=, /=, Assignment Operators
%=, +=, -=,
&=, ^=, |=,
<<=, >>=
15 Left to Right , Comma Operator
11 Explain backslash and trigraph characters.
Backslash character:
Back slash constants are a special type of character constant which are consists of two characters. This is
known as escape sequence. Escape sequence starts with backslash ‘\’ character.
Escape sequence Meaning
‘\0’ End of string – NULL.
‘\n’ End of line – takes the control to next line.
‘\r’ Carriage return – takes the control to the next paragraph.
‘\f’ Form feed- takes control to the next page.
‘\t’ Horizontal tab
‘\b’ Back space
‘\\’ Prints backslash character \
‘\a’ Alert – provide edible alert.
Trigraph character:-
C introduces concept of “trigraph” sequence to provide a way to enter certain characters which are not
available in some keyboard of non English language. Each trigraph character consists of a three characters.
Trigraph sequence Translation
??= # number sign
??( [ left bracket
??) ] right bracket
??< { left bracket
??< } right bracket
??! | vertical bar
??/ \ backslash
9
D) Decision Control Structure (if, if else, if else if, switch, …)
if (test expression)
{
statement-block
}
statement-x
If the test expression is true, the statement-block will be executed; otherwise the statement-
block will be skipped and the execution will jump to the statement-x.
Flowchart:
Entry
Test True
False Statement-block
Statement-x
Next-statement
Example:
#include<stdio.h>
void main()
{
int no;
printf("Enter the number:");
scanf("%d", &no);
if(no%2==0)
printf("no is even");
if(no%2!=0)
printf("no is odd");
}
1
2 Explain if…else… with example and draw flowchart.
if(test-expression)
{
True-block statement.
}
else
{
False-block statement
}
statement-x;
False True
Test
Statement-x
Next statement
2
3 Explain if…else...if ladder with example and draw flowchart.
When multipath decisions are involved, we may use if…else…if ladder, which takes the following general form.
if(condition-1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-N)
statement-N;
else
default—statement;
statement-x
First condition-1 is checked and if it is true, then statement-1 will be executed and control goes to
statement-x.
If condition-1 is false, then condition-2 is checked and if it is true then statement-2 will be executed
and control goes to statement-x.
Flowchart: Entry
Test
Condition
True 1 F alse
Test
Condition
Statement-1 True 2 False
Statement-2 Test
Condition
True 3 False
Test
Statement-3 Condition
True N
False
Statement-N
Default
stateme nt
Statement-x
3
Example: Find the class of student based on average marks.
#include<stdio.h>
void main()
{
int m1,m2,m3,m4,m5;
float avg;
printf("Enter m1,m2,m3,m4,m5:");
scanf("%d%d%d%d%d", &m1, &m2, &m3, &m4, &m5);
avg=(m1+m2+m3+m4+m5)/5;
if(avg>=70)
printf(“Distinct”);
else if(avg>=60)
printf("First class");
else if(avg>=50)
printf("Second class");
else if(avg>=40)
printf("Pass class");
else
printf("fail");
}
When a series of decisions are involved, we may have to use more than one if…else statement in nested form
as shown below.
if(test-condition-1)
{
if(test-condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-x
If test-condition-1 is true then test-condition-2 is evaluated. If it is true then Statement-1 will be executed,
if it is false then Statement-2 will be executed.
If test-condition-1 is false then Statement-3 will be executed.
4
Entry
Flowchart:
Test
Condition 2?
Statement-3 False
True
Statement-1 Statement-2
Statement-x
Next statement
5
5 Explain switch-case statement with example.
Example:
switch (grade)
{
case 1:
printf("Fall (F)\n");
break;
case 2:
printf("Bad (D)\n");
break;
case 3:
printf("Good (C)\n");
break;
case 4:
printf("Very Good (B)\n");
break;
case 5:
printf("Excellent (A)\n");
break;
default:
printf("You have inputted alse grade\n");
break; // break isn’ necessary here
}
6
Rules for switch statement
The switch expression must be integral type. Float or other data types are not allowed.
Case labels must be constant or constant expression.
Case labels must be unique.
Case labels must end with colons.
The break statement is optional.
The default case statement is optional.
Nesting of switch statement is allowed.
if-else switch
If statement is used to select among two The switch statement is used to select among
alternatives. multiple alternatives.
If can have values based on constraints. Switch can have values based on user choice.
Float, double, char, int and other data types can Only int and char data types can be used in switch
be used in if condition. block.
#include<stdio.h>
void main()
{
int no;
printf("enter no:");
scanf("%d",&no);
if(no%2==0)
printf("no is even");
else
printf("no is odd");
}
#include<stdio.h>
void main()
{
int a,b,c;
printf("enter a,b,c:");
scanf("%d%d%d",&a,&b,&c);
7
if(a>b&&a>c)
printf("a is maximum");
else if(b>c)
printf("b is maximum");
else
printf("c is maximum");
}
3 which asks day number and prints corresponding day name using switch-case.
#include<stdio.h>
void main()
{
int day;
printf("enter day number (1-7) \n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("sunday");
break;
case 2:
printf("monday");
break;
case 3:
printf("tuesday");
break;
case 4:
printf("wednesday");
break;
case 5:
printf("thursday");
break;
case 6:
printf("friday");
break;
case 7:
printf("saturday");
break;
default:
printf("wrong input");
}
}
8
E) Loop Control Structure (for, while, do…while)
1
do…while loop
In contrast to while loop, the body of the do…while loop is executed first and then the loop condition is
checked.
The body of the loop is executed at least once because do…while loop tests condition at the bottom of
the loop after executing the body.
do…while loop is also known as exit control loop because first body statements are executed and then
control-statement is executed, thus condition checking happens at exit point.
The general format of the do…while statement is:
initialization;
do
{
statement;
increment or decrement;
}
while(test-condition);
for Loop
for loop provides a more concise loop control structure.
The general form of the for loop is:
for (initialization; test condition; increment)
{
body of the loop;
}
When the control enters for loop, the variables used in for loop is initialized with the starting value such
as i=0, count=0. Initialization part will be executed exactly one time.
Then it is checked with the given test condition. If the given condition is satisfied, the control enters into
the body of the loop. If condition is not satisfied then it will exit the loop.
After the completion of the execution of the loop, the control is transferred back to the increment part of
the loop. The control variable is incremented using an assignment statement such as i++
If new value of the control variable satisfies the loop condition then the body of the loop is again
executed. This process goes on till the control variable fails to satisfy the condition.
For loop is also entry control loop because first control-statement is executed and if it is true then only
body of the loop will be executed.
2
Example: // The following is an example that finds the sum of the first ten positive
integer numbers
void main()
{
int i; //declare variable
int sum=0;
for(i=1; i < = 10; i++) // for loop
{
sum = sum + i ; // add the value of i and store it to sum
}
printf(“%d”, sum);
}
We can include multiple expressions in any of the fields of for loop provided that we separate such
expressions by commas. For example: for( i = 0; j = 100; i < 10 && j>50; i++, j=j-10)
2 State the difference between entry control loop and exit control loop.
3
float sum=0,average;
printf(“Input the marks, -1 to end\n”);
while(1)
{
scanf(“%d”,&i);
if(i==-1)
break;
sum+=i;
}
printf(“%d”, sum);
}
continue;
The continue statement can be used to skip the rest of the body of an iterative loop.
The continue statement tells the compiler, “SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH
THE NEXT ITERATION”.
Example: Find sum of 5 positive integers. If a negative number is entered then skip it.
void main()
{
int i=1, num, sum=0;
for (i = 0; i < 5; i++)
{
scanf(“%d”, &num);
if(num < 0)
continue; // starts with the beginning of the loop
sum+=num;
}
printf(“The sum of positive numbers entered = %d”,sum);
}
goto:
The goto statement is a jump statement which jumps from one point to another point within a function.
The goto statement is marked by label statement. Label statement can be used anywhere in the function
above or below the goto statement.
Generally goto should be avoided because its usage results in less efficient code, complicated logic and
difficult to debug.
4
F) Array and String
1 What is an array? Explain with Example. What are the advantages of using an array?
Th e data_type specifies the type of the elements that can be stored i n an array, like int, float or char.
Th e size indicates the maxim um number of elements that can be stored inside the array.
In the example, data type of an array is int and maximum elements that can be st ored in an array are 5.
Advantages:
You can use one name to store many values with different indexes.
An array is very useful when you are working with sequences of the same kind of data.
An array makes program easier to read, write and debug.
Example:
#include<stdio.h>
void main()
{
int a[5] = {5,12,20,54,68}, i;
for(i=0;i<5;i++)
{
printf(“%d”, a[i]);
}
}
Types of an array:
1) Single dimensional array
2) Two dimensional array
3) Multi dimensional array
1
2 Explain initialization and working of single and multi-dimensional array with example.
An individual array element can be used anywhere like a normal variable with a statement such as
g = marks [60];
More generally if i is declared to be an inte g er variable, then the statement g=marks[i];
will take the value contained at i th
position in an array a nd assigns it to g.
We can store value into array element by specifying the array element on the left hand side of the equals
sign like marks[60]=95; The value 95 is stored at 60th position in an array.
The ability to represent a collection of related data items by a single array enables us to develop concise
and efficient programs.
For example we can very easily sequence through the elements in the array by v arying the value of the
variable that is used as a sub cript into the array.
for(i=0; i<66; i++);
sum = sum + marks[i];
Above for loop will sequence through the first 66 elements of the marks array (elements 0 to 65) and will
add the values of each marks into sum. When for loop is finished, the variable sum will then contain the
total of first 66 values of the marks.
Th e declaration int values[5]; would r eserve enough space for a n array called values that could hold
up to 5 integers. Refer to the below given p
icture to conceptualize the reserved storage space.
values[0]
values[1]
values[2]
values[3]
values[4]
2
Two dimensional arrays:
Two dimensional arrays are also called table or matrix.
Two dimensional arrays have two subscripts.
First subscript d enotes the number of rows and second subscript denotes the number of columns.
Here m is declared as a matrix having 10 rows (numbered from 0 to 9) and 20 columns (numbered 0
through 19). The first element of the matrix is m[0][0] and the last r ow last column is m[9][19]
A two dimensional array marks[4][3] is shown below. The first element is given by marks[0][0] contains
35.5 & second element is marks[0][1] and contains 40.5 and so on.
C has several inbuilt functions to operate on string. These functions are known as string handling functions.
For Example: char s []=”Their”, s2[]=”There”;
Function Meaning
strlen(s1) Returns length of the string.
l = strlen(s1); it returns 5
strcmp(s1,s2) Compares two strings.
It returns negative value if s1<s2, positive if s1>s2 and zero if s1=s2.
3
printf(“%d”, strcmp(s1, 2));
Output : -9
strcpy(s1,s2) Copies 2nd string to 1st string.
strcpy(s1,s2) copies the string s2 in to string s1 so s1 is now “There”.
s2 remains unchanged.
d
strcat(s1,s2) Appends 2 string at the end of 1st string.
strcat(s1,s2); a copy of string s2 is appended at the end of string s1. Now s1
becomes “TheirThere”
strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf(“%s”,strchr(s1,’i’));
Output : ir
strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf(“%s”,strstr(s1,”he”));
Output : heir
strrev(s1) Reverses given string.
strrev(s1); makes string s1 to “riehT”
strlwr(s1) Converts string s1 to lower case.
printf(“%s”, strlwr(s1)); Output : their
strupr(s1) Converts string s1 to upper case.
printf(“%s”, strupr(s1)); Output : THEIR
strncpy(s1,s2,n) Copies first n character of string s2 to string s1
s1=””; s2=”There”;
strncpy(s1,s2,2);
printf(“%s”,s1);
Output : Th
strncat(s1,s2,n) Appends first n character of string s2 at the end of string s1.
strncat(s1,s2,2);
printf(“%s”, s1);
Output : TheirTh
strncmp(s1,s2,n) Compares first n character of string s1 and s2 and returns similar result as
strcmp() function.
printf(“%d”, strcmp(s1, 2,3));
Output : 0
strrchr(s1,c) Returns the last occurrence of a given character in a string s1.
printf(“%s”,strrchr(s2,’e’));
Output : ere
4
G) Functions
1 What is user defined function? Explain with example. Define the syntax of function in C.
2. Function Definition
Function Definition is also called function implementation.
It has mainly two parts.
Function header : It is same as function declaration but with argument name.
Function body : It is actual logic or coding of the function
. Function call
Function is invoked from main function or other function that is known as function call.
Function can be called by simply using a function name followed by a list of actual argument
enclosed in parentheses.
1
Syntax or general tructure of a Function
<return type> FunctionName (Argument1, Argument2, Argument3……)
{
Statement1;
Statement2;
Statement3;
}
An example of function
#include<stdio.h>
int sum(int, int); \\ Function Declaration or Signature
void main()
{
int a, b, ans;
scanf(“%d%d”, &a, &b);
ans = sum(a, b); \\ Function Calling
printf(“Answer = %d”, ans);
}
int sum (int x, int y) \\ Function Definition
{
int result;
result = x + y;
return (result);
}
Functions can be classified in one of the following categor based on whether arguments are present or not,
whether a value is returned or not.
1. Functions with no arguments and no return value \\ void printline(void)
2. Functions with no arguments and return a value \\ int printline(void)
3. Functions with arguments and no return value \\ void printline(int a)
4. Functions with arguments and one return value \\ int printline(int a)
5. Functions that return multiple values using pointer \\ void printline(int a)
2
Exam le:
#include<stdio.h>
void printline(void); // No argument – No return value
void main()
{
clrscr();
printline();
void main() No void Fun1()
printf("\n GTU \n");
{ Input {
} …………… ……………
…………… ……………
void printline(void)
Fun1() ……………
{ …………… ……………
…………… }
int i;
} No
for(i=0;i<10;i++)
Output
{
printf("-");
}
}
2. Function with no arguments and return a value
When a function has no argument, it does not receive data from calling function.
When a function has return value, the calling function receives one data from the called function.
Exam le:
#include<stdio.h>
int get_number(void); // No argument
void main()
{
int m;
void main() No int Fun1()
m=get_number(); Input {
{
printf("%d",m); …………… ……………
…………… ……………
} ……………
a = Fun1()
int get_number(void) …………… return no;
…………… }
{ Function
}
int number; result
printf("enter number:");
scanf("%d",&number);
return number; // Return value
}
3. Function with arguments and no return values
When a function has argument, it receives data from calling function.
When it does not return a value, the calling function does not receive any data from the called
function.
Example:
3
#include<stdio.h>
#include<conio.h>
void sum(int,int); // Argument
void main()
{
int no1,no2;
printf("enter no1,no2:"); void main() Value of void Fun1(int a)
{ argument {
scanf("%d%d",&no1,&no2); ……………
……………
sum(no1,no2); …………… ……………
Fun1(a) ……………
} ……………
……………
void sum(int no1,int no2) …………… }
{ } No return
value
if(no1>no2)
printf("\n no1 is gretest");
else
printf("\n no2 is gretest");
} // No return value
{
int add=0,i;
while(no>0)
{
i=no%10;
4
add=add+i;
no=no/10;
}
return add; // Return value
}
5. Function that returns a multiple value
Function can return either one value or zero value. It cannot return more than one value
To receive more than one value from function, we have to use pointer.
So function should be called with reference not with value
Exam le:
#include<stdio.h>
void mathoperation(int x, int y, int *s, int *d);
void main()
{
int x=20,y=10,s,d;
mathoperation(x,y,&s,&d);
printf("s=%d \nd=%d", s,d);
}
void mathoperation(int a, int b, int *sum, int *diff)
{
*sum = a + b;
*diff = a - b;
}
Arguments passed to the function during function calling are called actual arguments or parameters.
Arguments received in the definition of a function are called formal arguments or parameters.
Exam le:
#include<stdio.h>
int max(int , int ) // Function Declaration.
void main()
{
int a=5,b=3, ans;
ans=max(a, b); //a and b are actual arguments.
printf("max=%d", ans);
}
int max(int x, int y) // x and y are formal arguments.
{
if(x>y)
return x;
5
else
return y;
}
4 Explain call by value (pass by value) and call by reference (pass by reference) with example.
Exam le:
#inc ude<stdio.h>
void swap(int, int);
void main()
{
int x, y;
printf("Enter the value of X & Y:");
scanf("%d%d", &x, &y);
swap(x, y);
printf(“\n Values inside the main function”);
printf(“\n x=%d, y=%d”, x, y);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(“\n Values inside the swap function”);
printf("\n x=%d y=%d", x, y);
}
Output:
Enter the value of X & Y: 3 5
Values inside the swap function
X=5 y=3
6
Values inside the main function
X=3 y=5
Call by Reference
I call by reference, the address of the actual parameters is passed as an argument to the called
function.
So the original content of the calling function can be changed.
Call by reference is used whenever we want to change the value of local variables through function.
Example:
#include<stdio.h>
void swap(int *, int *);
void main()
{
int x,y;
printf("Enter the value of X & Y:
scanf("%d%d", &x, &y);
swap(&x, &y);
printf(“\n Value inside the main function”);
printf("\n x=%d y=%d", x, y);
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf(“\n Value inside the swap function”);
printf("\n x=%d y=%d", x, y);
}
Output:
Enter the value of X & Y: 3 5
Value inside the swap function
X=5 y=3
Value inside the main function
X=5 y=3
7
Recursive function is a function that calls itself.
If a function calls itself then it is known as recursion.
Recursion is thus the process of defining something in terms of itself.
Suppose we want to calculate the factorial of a given number then in terms of recursion we can
write it as n! = n * (n-1)!. First we have to find (n-1)! and then multiply it by n. the (n-1)! is
computed as (n-1)! = (n-1) * (n-2)!. This process end when finally we need to calculate
1!.which is 1.
Ex: 4! =4*3!
=4*3*2!
=4*3*2*1!
=4*3*2*1
Terminating condition must be there which can terminates the chain of process, otherwise it will lead
to infinite number of process.
Pictorial presentation of recursion.
fact(4)
f=1;
if(…..)
……..;
f=4*fact(3)
return 2
4;
fact(3)
f=1;
if(…..)
……..;
return 6;
fact(2)
f=1;
if(…..)
……..;
return 2;
fact(1)
f=1;
if(…..)
……..
return 1;
8
Example: Find factorial of a given number using recursion.
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int f,n;
printf("enter number:");
scanf("%d",&n);
f=fact(n);
printf("\n factorial=%d",f);
}
int fact(int n)
{
int f=1;
if(n==1)
{
return 1;
}
else
{
f=n*fact(n-1);
return f;
}
}
Advantages
Easy solution for recursively defined solution.
Complex programs can be easily written with less code.
Disadvantages
Recursive code is difficult to understand and debug.
Terminating condition is must; otherwise it will go in an infinite loop.
Execution speed decreases because of function call and return activity many times.
Scope
The scope of variable can be defined as that a part of a program where the particular variable is
accessible
In what part of the program the variable is accessible is depends on where the variable is declared.
Local variables which are declared inside the body of function cannot be accessed outside the body
of function.
9
Global variables which are declared outside any function definition can be accessible by all the
function in a program.
Lifetime
Lifetime is a time limit during the program execution until which a variable exist in a memory.
It is also referred to the longevity of variable.
Visibility
Visibility is the ability of the program to access a variable from the memory.
If variable is redeclared within its scope of variable, the variable losses the visibility in the scope of
variable which is redeclared.
10
Pointers
void main()
{
int a=10, *p;
p = &a; \\ Assign memory address of a to pointer variable p
printf(“%d %d %d”, a, *p, p);
}
Output: 10 10 5000
p is integer pointer variable
& is address of or referencing operator which returns memory address of variable
* is indirection or dereferencing operator which returns value stored at that memory address
& operator is the inverse of * operator ( x = a is same as x = *(&a))
10 5000
5000 5048
Declaration of pointer,
Syntax: data_type *pt_name;
Example: int *p, float *q, char *c;
1) The asterisk (*) tells that the variable pt_name is a pointer variable
2) pt_name needs a memory location to store address of another variable
3) pt_name points to a variable of type data_type
1
2 How pointer is different from array?
Array Pointer
Array is a constant pointer. Pointer variable can be changed.
Array name is constant pointer so a is constant pointer and it always points to the first element of
an array.
a[0] is same as *(a+0), a[2] is same as *(a+2), a[i] is same as *(a+i)
So every program written using array can always be written using pointer.
. .
. .
. .
. .
. .
. .
. .
As we have an array of char, int, float etc…, same way we can have an array of pointers, individual
elements of an array will store the address values. So, array of pointers is a collection of pointers of same
type known by single name.
2
Syntax :
data_type *name[size];
Example :
int *ptr[5]; \\Declares an array of integer pointer of size 5
int mat[5][3]; \\Declares a two dimensional array of 5 by 2
Now, the array of pointers ptr can be used to point to different rows of matrix as follow
for(i=0;i<5;i++)
{
ptr[i]=&m t[i][0]; \\ Can be re-written as ptr[i]=mat[i];
}
ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
By using dynamic memory allocation, we do not require to declare two-dimensional array, it can be created
dynamically using array of pointers.
#include<stdio.h>
void swap(int *,int *);
void main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d%d", &a, &b);
swap(&a, &b);
printf("a=%d b=%d", a, b);
getch();
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
3
6 Write a C program to calculate sum of 10 elements of an array using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int *p, a[10], sum=0, i;
p=a;
printf("Enter elements:");
for(i=0; i<10; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<10; i++)
{
sum=sum+*p;
p++;
}
printf("sum=%d", sum);
getch();
}
4
Structure, Union
Structure s a collection of logically related data items of different data types grouped together
under a single name.
Structure s a user defined data type.
Structure helps to organize complex data in a more meaningful way.
Syntax of Structure:
struct structure_name
{
data_type member1;
data_type member2;
………….
};
struct is a keyword.
structure_name is a tag name of a structure.
member1, member2 are members of structure.
Example:
#include< tdio.h>
#include< onio.h>
struct book
{
ch r title[100];
ch r author[50];
int pages;
float price;
};
void main()
{
struct book book1;
printf("enter title, author name, pages and price of book");
scanf(“%s”,book1.title);
scanf(“%s”, book1.author);
scanf("%d",&book1.pages);
scanf("%f",&book1.price);
printf("\n detail of the book");
printf(“%s”,book1.title);
printf(“%s”,book1.author);
1
printf("%d",book1.pages);
printf("%f",book1.price);
getch();
}
book is structure whose members are title, author, pages and price.
book1 is a structure variable.
Declaration of structure:
A structure variable declaration is similar to the declaration of variables of any other data type. It includes
the following elements:
1) The keyword struct
2) The structure tag name
3) List of variable names separated by commas
4) A terminating semicolon
For example:
struct book
{
ch r title[100];
ch r author[50];
int pages;
float price;
} book1;
struct book book2;
We can declare structure variable in two ways
1) Just after the structure body like book1
2) With struct keyword and structure tag name like book2
Accessing structure members:
The following synt x is used to access the member of structure.
structure_variable.member_name
structure_variable is a variable of structure and member_name is the name of variable which is a
member of a structure.
The “.”(dot) operator o ‘period operator’ connects the member name to structure name.
for ex:
book1.price represents price of book1
We can assign values to the member of the structure variable book1 as below,
strcpy(book1.title,”ANSI C”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=120.50;
2
We can also use scanf function to assign value through a keyboard.
scanf(“%s”,book1.title);
scanf(“%d”,&book1.pages);
3 What is Union?
Structure Union
Each member is assigned its own unique All members share the same storage area.
storage area.
Total memory required by all members is Maximum memory required by the member is
allocated. allocated.
All members are active at a time. Only one member is active a time.
All members can be initialized. Only the first member can be initialized.
Requires more memory. Requires less memory.
Example: Exa ple:
struct SS union UU
{ {
int a; int a;
float b; float b;
char c; char c;
}; };
1 byte for c 4 bytes for c,b,a a c
2 bytes for a b
4 bytes for b
Total bytes = 1 + 2 + 4 = 7 bytes. 4 bytes are there between a,b and c because
largest memory o cupies by float which is 4 bytes.
3
5 Explain nested structure with example
A structure that contains another structure as a member variable is known as nested structure or
structure within a structure.
Structure which is part of other structure must be declared before the structure in which it is used.
Example:
#include<stdio.h>
#include<conio.h>
struct address
{
char add1[50];
char add2[50];
char city[25];
};
struct employee
{
char name[100];
struct address a;
int salary;
};
void main()
{
struct employee e;
printf("enter name,address,city,salary");
scanf(“%s”,e.name);
scanf(“%s”,e.a.add1);
scanf(“%s”,e.a.add2);
scanf(“%s”,e.a.city);
scanf("%d",&e.salary);
printf("detail of employaee:");
printf("%s”,e.name);
printf("%s”,e.a.add1);
printf("%s”,e.a.add2);
printf("%s”,e.a.city);
printf("%d",e.salary);
getch();
}
4
6 Explain Array of Structure with Example?
As we hav an array of basic data types, same way we can have an array variable of structure.
It is better to use array of size 66 instead of 66 variables to store result of 66 student.
5
J) File Handling
File Management
In real life, we want to store data permanently so that later on we can retrieve it and reuse it.
A file is a collection of bytes stored on a secondary storage device like hard disk, pen drive, and tape.
There are two kinds of files that programmers deal with text files and binary files.
Text file are human readable and it is a stream of plain English characters.
Binary files are not human readable. It is a stream of processed characters and Ascii symbols.
Same modes are also supported for binary files by just adding b, e.g. rb, wb, ab, r+b, w+b, a+b
Example: fp = fopen(“Prog.c”,”r”); // File name is prog.c and it is opened for reading only.
fclose() (Close file)
Opened files must be closed when operations are over.
The function fclose is used to close the file i.e. indicate that we are finished processing this file.
To close a file, we have to supply file pointer to fclose function.
If file is closed successfully then it returns 0 else EOF.
Example: fclose(fp);
fprintf() (Write formatted output to file)
The fprintf function prints information in the file according to the specified format.
fprintf() works just like printf(), only difference is we have to pass file pointer to the function.
It returns the number of characters outputted, or a negative number if an error occurs.
fscanf() (Read formatted data from file)
The function fscanf() reads data from the given file.
It works in a manner exactly like scanf(), only difference is we have to pass file pointer to the function.
If reading is succeeded then it returns the number of variables that are actually assigned values, or EOF if any
error occurred.
Example: fseek(fp,9,SEEK_SET); // Moves file position indicator to 9th position from begging.
For binary streams, the value returned corresponds to the number of bytes from the beginning of the file.
Example: ch = getc(fp);
Example: i = getw(fp);
Write a program to count the number of lines, tabs, characters and words in a file.
#include <stdio.h>
void main()
{
FILE *fp;
int lines=0, tabs=0, characters=0, words = 0;
char ch, filename[100] ;
printf(“Enter file name: “);
gets( filename ); // You can also use scanf(“%s”,filename);
fp = fopen( filename, “r” );
if ( fp == NULL ) // File is not opened successfully then it returns NULL.
{
printf(“Cannot open %s for reading \n”, filename );
exit(1); /* terminate program */
}
ch = getc( fp ) ;
while ( ch != EOF )
{
if ( ch == ‘\n’ )
lines++ ;
else if ( ch == ‘\t’ )
tabs ++ ;
else if ( ch == ‘ ’ )
words ++ ;
else
characters++;
c = getc ( fp );
}
fclose( fp );
printf(“Lines=%d Tabs=%d Wods=%d Characters=%d”, lines, tabs, words,
characters);
K) Dynamic Memory Allocation, Storage Classes
realloc( )
realloc() reallocates a memory block with a specific new size. If you call realloc(), the size of the memory
block pointed to by the pointer is changed to the given size in bytes. This way you are able to expand and
reduce the amount of memory you want to use.
It is possible that the function moves the memory block to a new location; then the function returns
address of new location. Old memory block is copied to new memory and old memory is released
automatically.
The content will remain unchanged means it is copied to new location.
If the pointer is NULL then the realloc() will behave exactly like the malloc(). It will assign a new block of a
size in bytes and will return a pointer to it.
Syntax: ptr_var=* realloc ( void * ptr, size_t size );
Exampl :
#include<stdio.h>
int main()
{
int *p ;
p = (int *)malloc(sizeof(int));
*p =25;
p = (int *)realloc(p, 2 * sizeof(int));
printf(“%d”,*p);
free(P);
}
free( )
When the memory is not needed anymore, you must release it calling the function free.
Just pass the pointer of the allocated memory to free function and memory is released.
Syntax: void free(void *pointer);
Exampl : free(p);
Storage Class
Storage class decides the scope, lifetime and memory allocation of variable.
Scope of a variable is the boundary within which a variable can be used.
Four storage classes are available in C,
o Automatic (auto)
o Register (register)
o External (extern)
o Static (static)
automatic:
Variables which are declared in function are of automatic storage class.
Automatic variables are allocated storage in the main memory of the computer.
Memory is allocated automatically upon entry to a function and freed automatically upon exit from the
function.
The scope of automatic variable is local to the function in which it is declared.
It is not required to use the keyword auto because by default storage class within a block is auto.
Example:
int a;
auto int a;
register:
Automatic variables are allocated storage in the main memory of the computer; However, for most
computers, accessing data in memory is considerably slower than processing directly in the CPU.
Register variables are stored in registers within the CPU where data can be stored and accessed quickly.
Variables which are used repeatedly or whose access time should be fast may be declared to be of
storage class register.
Variables can be declared as a register: register int var;
external:
Automatic and register variables have limited scope and limited lifetimes in which they are declared.
Sometimes we need global variables which are accessible throughout the program.
extern keyword defines a global variable that is visible to ALL functions.
extern is also used when our program is stored in multiple files instead of single file.
Memory for such variables is allocated when the program begins execution, and remains allocated until
the program terminates. Memory allocated for an external variable is initialized to zero.
Declaration for external variable is as follows: extern int var;
static:
static keyword defines a global variable that is visible to ALL functions in same file.
Memory allocated for static variable is initialized to zero.
Static storage class can be specified for automatic as well as external variables such as:
static extern int varx; //static external
static int var; // static automatic
Static automatic variables continue to exist even after the function terminates.
The scope of static automatic variables is identical to that of automatic variables.
Explain Input / Output functions.
C language provides a set of standard built‐in functions which will do the work of reading or displaying
data or information on the I/O devices during program execution.
Such I/O functions establish an interactive communication between the program and user.
printf( )
It is used to display all types of data and messages.
It can display multiple data at a time by multiple format specifier in one printf( ).
Exampl : printf(“a=%d b=%d”, a, b);
puts()
It is used to display a string at a time.
Exampl :
char str[]=”Hello”;
puts(str );
putchar()
It is used to display single character at a time.
Exampl :
putchar(ch);