100% found this document useful (1 vote)
2K views44 pages

CS-100-QP2-Solved-KTU Notes PDF

The document is a question paper for a Computer Programming exam containing 3 parts with multiple choice and long answer questions. Part A contains 2 long answer questions about qualifiers in C and control statements in C with examples. Part B contains 2 long answer questions on pointers, structures, and arrays. Part C contains 2 long answer questions on sorting algorithms, file handling, and storage classes. The total marks for the exam are 100 and it is divided into 3 parts with varying mark distributions for the questions.

Uploaded by

Rekha V R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views44 pages

CS-100-QP2-Solved-KTU Notes PDF

The document is a question paper for a Computer Programming exam containing 3 parts with multiple choice and long answer questions. Part A contains 2 long answer questions about qualifiers in C and control statements in C with examples. Part B contains 2 long answer questions on pointers, structures, and arrays. Part C contains 2 long answer questions on sorting algorithms, file handling, and storage classes. The total marks for the exam are 100 and it is divided into 3 parts with varying mark distributions for the questions.

Uploaded by

Rekha V R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Total Pages:

Reg No.:_______________ Name:__________________________


APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY
SECOND SEMESTER B.TECH DEGREE EXAMINATION, DECEMBER 2017
Course Code: CS100
Course Name: COMPUTER PROGRAMMING
Max. Marks: 100 Duration: 3 Hours
PART A
Answer Any Two questions, each carries 15 marks. Marks

1 a) Write notes Qualifiers in C. (5)


b) Write notes on Control statements in C. Give Examples for each. (10)
2 a) List any five string handling functions with examples (5)
b) Compare Structure and Union with help of example. (5)
c) Write a C program largest number in an Array (5)
3 a) With the help of flow chart explain compiling and execution of a C program (2.5)
b) Write a C program to largest among two numbers using conditional operator (2.5)
c) Write a C program to multiply two matrices using the concept of 2D arrays (10)
PART B
Answer Any Two questions, each carries 15 marks.
4 a) Explain the concept of Pointer in C with the help of example (5)
b)
S . I N
Write a program in C to store n elements in an array and print the elements using

E
(5)

OT
TUN
pointer
c)
K
Write a C program to store and display the following details of n students using
structure. Name, Rollno,Marks
(5)

5 a) Distinguish call by value and call by reference with the help of examples (10)
b) Explain the concept of Recursive function with the help of an example C (5)
program to find Factorial of a number.
6 a) Write a C program to sort an Array using Pointer. (10)
b) Write a C program to compute basic arithmetic operations using functions. (5)
PART C
Answer Any Two questions, each carries 20 marks.
7 a) With the help of an example C program explain Selection sort (10)
b) With the help of an example C program explain Recursive Binary Search (10)
8 a) Write notes on any ten file handling functions with syntax (10)
b) Explain the concept of Command Line Argument with the help of an example. (10)
9 a) Discuss storage classes with the help of examples. (10)
b) Write a C program to read name and marks of n number of students from user (10)
and store them in a file. If the file previously exits, add the information of n
students.
****

Downloaded from Ktunotes.in


1 a) Write notes Qualifiers in C. (5)
b) Write notes on Control statements in C. Give Examples for each. (10)

a) Qualifiers
Qualifiers are the keywords just using to alter the meaning of basic data types to yield a new data type.

Following are the important qualifiers in c.

• Size qualifiers
• Sign qualifiers
• Constant qualifiers
• Volatile qualifiers

Size Qualifiers

Size qualifiers are the keywords using to alter the size of basic data types. They are long and short. For integer
data types, there are three sizes: int, and two additional sizes called long and short, which are declared as long
int and short int. The keywords long and short are called sub-type qualifiers. The long is intended to provide
a larger size of integer, and short is intended to provide a smaller size of integer. However, not all
implementations provide distinct sizes for them. The requirement is that short and int must be at least 16
bits, long must be at least 32 bits, and that short is no longer than int, which is no longer than long. Typically, short
is 16 bits, long is 32 bits, and int is either 16 or 32 bits.
S . I N
T U N OTE
K
Eg:- long int, long float, short double etc.

Sign Qualifiers

Sign qualifiers are two signed and unsigned. signed is default one, i.e., declaring int a;
Is same as
signed int a;
both can store both +ve and –ve numbers. Declaring a variable unsigned int a;
can only store +ve values
Constant Qualifier

If you are declaring a variable as: cost int a=2;


then you can never change the value of a in the program.

Volatile Qualifiers

If you are declaring a variable as: Volatile int


a=3;
means you can change the value of variable a whenever needed. Normally all variables are by default volatile in C.
Downloaded from Ktunotes.in
b) CONTROL STATEMENTS

The statements that are used to control the flow of execution of statements are known as conditional control
statements.
Conditional statements are divided into three types:-

1. Conditional
2. Unconditional
3. Looping

Conditional Control statements:

A ‘c ’program is a set of statements which are normally executed sequentially in the order in which they appear. This
happens when no options (or) no repetitions of certain calculations are necessary .however in practice we have a
number of situations where we may have to change the order of execution of statements until certain specified
conditions are met. This involves a kind of “decision making” to see whether a particular condition has occurred (or0
not & then direct the computer to execute certain statements accordingly.

‘C’ language passes such decision making capabilities & supports the following statements known as conditional (or)
decision making statements.

1. if statements
2. switch statement
3. conditional operator statement

If statement

S . I N
N OTE
The 'if' statement is a powerful decision making statement and is used to control the flow of execution of statements.

T U
if (test expression ) K
It is basically a two way decision statement and is used in conjunction with as expression .It takes the following form:-

It allows the computer to evaluate the expression first & then depending on whether the value of the expression
(relation(or)condition) is 'true'(non-zero)or 'false'(zero),it transfer the control to a particular statement .This point of
program has two paths follow, one for true condition & the other for the false condition.

The if statement may be implemented in different forms depending on the complexity of condition to be tested

1. simple if statement
2. if …else statement
3. nested if …else statement Downloaded from Ktunotes.in
4. else if ladder

1. Simple if statement:

General form:

if (test expression)
{
Statement–block;
}
Statement –x;

The statement-block may be a single statement (or) a group of statements. if the test statement is true, the
statement-block will be executed, other wise the statement block will be stopped & the execution will be jump to the
statement –x.
Note: when the condition is true, both the statement block & the statement-x are executed in sequence.
Flowchart for simple-if:

S . I N
T U N OTE
K

Example: program to find max value of 2 numbers

main()
{
int a, b,max;
printf("Enter any 2 values");
scanf("%d%d",&a,&b);
max=a;
if(max< b)
{
max =b;
}
printf("max =%d",max);
getch();
Downloaded from Ktunotes.in
}

2)If-else statement

It is an extension of simple if statement.

Syntax:
if(test expression)
{
True block statement ;
}
else
{
false block statement;
}
Statement-x;

If test expression is true, then the true block statement, immediately following the if statement are executed ;
otherwise the false block statement () are executed . In either case , either true-block(or) false block will be executed,
not both.

S . I N
T U N OTE
K

Example:To check whether given no is even (or) odd

main()
{
int n:
clrscr();
printf("enter any number");
scanf("%d",&n);
if(n%2==0)
printf("even number is even");
else

printf("Given nmber is odd");


getch();
Downloaded from Ktunotes.in
}

3.Nested if---else statement:

When a series of decision are involved, we may to have to use more than if-----else statement in nested form as
follows:

if(test condition)
{
if(test condition)
{
Statement-1;
}
else

{
Statement-2;
}
else
{
Statement-3;
}
Statement-x;
}

S . I N
T U N OTE
If the condition 1 is false , the statement-3 will be executed otherwise it continues to perform the second test
K
. IF the condition-2 is true, the statement-1 is evaluated; otherwise statement -2 will be evaluated & then the
control is transferred to statement-x.

Downloaded from Ktunotes.in


Program to find max of 3 numbers.

#include < stdio.h>


void main( )
{
int a,b,c,max;
printf("enter any 3 numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b)

{
if(a>c)
max=a;
else
max=c;
}

else

if(b>c)
max=b;
else
max=c;
}

S . I N
OTE
printf ("max=%d",max);
}

K T U N
4.THE ELSE IF LADDER:

There is another way of putting 'if's together when multipath decisions are involved. A multipath decision is a chain
of 'if's' in which the stmt associated with each else is an if. It takes the following general form.

if(cond1)
Stmt-1;
else if(cond2)
Stmt-2;
else if(cond3)
Stmt-3;
else if(condn)
Stmt-n;
else
Default stmt;
Stmt-x;

This construction is known as else if ladder.


The conditions are evaluated from the top to bottom. As soon as true cond is found, the stmt associated with it is
executed and the control is transferred to stmt-x(skipping the rest of ladder) when all the conditions become false,
then the final else containing the default stmt will be executed.
Downloaded from Ktunotes.in
Example: Write a program to read in the marks of a student and display the grade according to the following
information using else-if ladder.

Average Marks Grade


80 to 100 A
60 to 79 B
50 to 59 C
40 to 49 D
0 to 39 F(Fail).

This grading can be done using else-if ladder as follows:

if(marks > 79)


grade= 'A';
else if(marks > 59)
grade= 'B';
else if(marks > 49)
grade= 'C';
else if(marks > 39)
grade= 'D';
else
grade='F';
printf("Grade is %c",grade);

Program to find maximum of three numbers using else-if ladder.

S . I N
OTE
main()
{
int a,b,c,max;
clrscr(); K T U N
printf("Enter values of a ,b,c");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
max=a;
else if(b>c)
max=b;
else
max=c;
printf("Maximum is %d",max);
getch();
}

Loops

The versatility of computer lies in its ability to perform as set of instructions repeatedly. This involves a repeating
some position of a program either a specified number of a time or until a particular condition is being satisfied. This
repeative operation is done through a loop control structure.
There are 3 methods by way of which Downloaded from
we can repeat a part Ktunotes.in
of a program. They are
1. Using a while statement
2. Using a do while statement
3. Using a for while statement

While loop: It is a conditional control loop statement The while is an entry controlled loop statement. In entry
controlled loop, the control conditions are tested before start of the loop execution. If the conditions are not satisfied
then the body of the loop will not be executed.
General form
While (test condition) { Body of the loop }
The condition being tested may use relational or logical operators.
Eg: program to print "n" natural numbers while using loop.

main()

int n, i=1;

clrscr ();

printf ("enter the values of n");

scanf ("%d", &n);

printf ("natural numbers from 1 to %d ", n);

while (i<=n)

printf ("%d\ t", i);

S . I N
OTE
i++;

getch ();
K T U N
}

Eg: program to display even numbers &odd numbers from 1 to n

void main ()

int n, i=1;

clrscr();

printf("enter the values of n");

scanf("%d", &n);

printf("even numbers from 1 to %d ", n);

while(i<=n)

if(i%2==0)

printf("%d \t", i);

i++;
Downloaded from Ktunotes.in
}

printf("odd numbers from 1to %d ", n);

i=1;

while(i<=n)

if(i%2==1)

printf("%d\t", i);

i++;

getch();

do while

On some occasions it might be necessary to execute the body of the loop before test is performed. Such situations
can be handled with the help of do while statement.
General form:
do
{
Body of the loop
} while (test condition);

S . I N
On reaching the do statement the program proceeds to evaluate the body of the loop first. At the end of loop, the

U OTE
test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the

N
body of loop once again. This program continues as long as the condition is true. When the condition becomes false,
T
K
the loop while be terminated and the control goes to the statement that appears immediately after while statement.
Since, the test condition is evaluated at the bottom of the loop,the do while construct provides an exit-controlled
loop and the form the body of the loop is always executed at least once.
Flow chart for exit control:

Downloaded from Ktunotes.in


Example: To print ‘n’ natural number using do while

#include < stdio.h>

#include < conio.h>

S . I N
OTE
void main()

int n,i=1;
K T U N
clrscr();

printf("enter any number");

scanf("%d",&n);

printf("natural numbers from 1 to %d",n);

do

printf("%d\t",i);

i++;

}while(i<=n);

getch();

FOR Loop

The for loop is another entry controlled loop that provides a more concise loop control structure.
The general form of for loop is
for(initialization; test condition; increment)
{ Downloaded from Ktunotes.in
Body of the loop
}
1.The initializing control variables using assignment statement such as i=1&count=0,we can initialize control
variables. The variables i & count are known as
LOOP CONTROL VARIABLES 2. The value of control is tested using the test condition. The test condition is a relational
expression, such as i<10 determine, when the loop will exit. If condition is true ,the body will executed otherwise the
execution continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to for statement after evaluating the last
statement in the loop. Now the control variable is incremented using assignment statement such as i=i+1 and the
new value of control variable is again tested to see whether the loop condition is satisfied or not.
Ex: To print 1 to 100 digits

01#include < stdio.h>

02#include < conio.h>

03void main()

04{

05 clrscr();

06 for(i=1,i<=100,i++)

07 {

08 printf("%d/t",i);

09 }

10 getch();

S . I N
OTE
11}

12

K T U N
Ex: To print multiplication table of any numbers from 1 to 20

01#include < stdio.h>

02#include < conio.h>

03void main()

04{

05 int n,i;

06 clrscr();

07 printf("enter any number");

08 scanf("%d",&n);

09 for(i=1,i<=20,i++)

10 {

11 printf("/n%d*d is %d", n,i,n*i);

12 }

13 getch();

Downloaded from Ktunotes.in


14}

UNCONDITIONAL CONTROL STATEMENTS

BREAK
It is used to terminate a switch statement.
BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to get back to the conditional test.
CONTINUE
The keywords continue allow us to take the control to the beginning of the loop, by passing the statements inside the
loop which have not yet been executed.
GOTO STATEMENT
‘c’ supports go to statement to branch unconditionally from one point to another in the program.
The GOTO General Form is

goto Label;
----------- Label:
---------- Statement
---------- -------------
Label: -----------
Statement; ------------
Forward jump goto Label:
Backward jump

The go to require a "label". In order to identify the place where the branch is to be made. A "label" is any valid
variable name, and must be followed by a "colors". The label is placed immediately before the statement where the

. I N
control is to be transferred. The label can be any where in the program either before (or) after go to label; state.
S
OTE
Ex; program to print ‘n’ natural number

01main()

K T U N
02{

03 int n,i=1;

04 clrscr();

05 printf("enternumber");

06 scanf("%d\t",i);

07 printf("natural numbers from 1to%d",n);

08 lb: printf("%d\t",i);

09 i++;

10 if(i<=n)

11 goto lb;

12 getch();

13}

SWITCH

Downloaded from Ktunotes.in


It is a multiway decision statement.The switch statement tests the value of guven variable( or expression) against a
list of "case" values and when a match is found, a block of statements associated with that case is executed.
General form of switch is

01switch(expression)

02 {

03 case value-1:

04 block-1;

05 break;

06 case value-2:

07 block-2;

08 break;

09 ---------------------

10 ---------------------

11 case value-n:

12 block-n;

13 break;

14 default:

15 default-block;

S . I N
OTE
16 break;

17 }

18statement-x; K T U N
In the above general form,
Expression:It is an integer expression (or) character.
Value-1,value-2….. :These are constants (or) constant expressions (evaluable to integer constant) and are known as
"case labels". Each of these values should be unique with switch statement.
block-1,block-2…:These are the statement lists and may contain zero (or) more statements.There is no need to put
braces around these blocks.
Note: "case labels" must end with a colon (:).
When the switch is executed, the value of the expression is successively compared against the values value-1, value-
2…….If a case is found whose value matches with the value of the expression then the block of statements of that
particular case will get executed.
Break:The break statement at the end of each block signal the end of a particular case and causes an exit from switch
statement, transferring the control to the statement-x, following the switch.
The default is an optional case. When present it will be executed if the value of expression does not match with any
of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x.

Ex: program to test all arithmetic operations using switch statement

main( )

int a,b ,opt;


Downloaded from Ktunotes.in
clrscr( );

printf("enterany2values");

scanf("%d%d",&a,&b);

printf("1.addition\n2.subraction\n3.multiplication\4.division\n6.modular\n");

printf("\nenteryouroption");

scanf("%d",&opt);

switch(opt)

case 1:

printf("aditionof%d&%dis%d",a,b,a+b);

break;

case 2:

printf("subof%d&%dis%d",a,b,a-b");

break;

case 3:

printf("multipleof%d&%dis%d",a,b,a*b);

break;

case 4:

S . I N
printf("divof%d&%dis%d",a,b,a/b);

T U N OTE
break;

case 5:
K
printf("modularof%d&%dis%d",a,b,a/b);

break;

default:

printf ("\n invalid option");

getch();

2a) List any five string handling functions with examples

1. strcpy(s1, s2);
• Copies string s2 into string s1.

C String function – strcpy


char *strcpy( char *str1, char *str2)

It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

Example of strcpy:

#include <stdio.h> Downloaded from Ktunotes.in


#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}

Output:

String s1 is: string 2: I’m gonna copied into s1

2. strcat(s1, s2);

• Concatenates string s2 onto the end of string s1.

C String function – strcat


char *strcat(char *str1, char *str2)

It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";

S . I N
OTE
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);

}
return 0;

K T U N
Output:

Output string after concatenation: HelloWorld

3. strlen(s1);

• Returns the length of string s1.

C String function – strlen

Syntax:

size_t strlen(const char *str)

size_t represents unsigned short


It returns the length of the string without including end character (terminating char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Downloaded from Ktunotes.in
Output:

Length of string str1: 13

4. strcmp(s1, s2);

• Returns 0 if s1 and s2 are the same;

• less than 0 if s1<s2;

• greater than 0 if s1>s2.

C String function – strcmp


int strcmp(const char *str1, const char *str2)

It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would
return 0 otherwise it may return a negative or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2
then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";

N
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
S . I
OTE
{
printf("string 1 and string 2 are equal");
}else
{
K T
printf("string 1 and 2 are different");
U N
}
return 0;
}

Output:

string 1 and 2 are different

5. strrev()

• strrev( ) function reverses a given string in C language.

#include<stdio.h>

#include<string.h>

int main()

char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));


Downloaded from Ktunotes.in
C Union
C Structure

Union allocates one common storage space for all its


Structure allocates storage space for all its members members.
separately. Union finds that which of its member needs high storage
space over other members and allocates that much space

Structure occupies higher memory space. Union occupies lower memory space over structure.

We can access all members of structure at a time. We can access only one member of union at a time.

Structure example: Union example:


struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double
. I N
average; double

E S
average;
};
OT };

return 0;
K TUN
}

b) Compare Structure and Union with help of example. (5)

c) Write a C program largest number in an Array (5)


#include <stdio.h>

int main()

{ int array[50], size, i, largest;

Downloaded from Ktunotes.in


printf("\n Enter the size of the array: ");
scanf("%d", &size);

printf("\n Enter %d elements of the array: ", size);

for (i = 0; i < size; i++) {

scanf("%d", &array[i]);}

largest = array[0];

for (i = 1; i < size; i++) {

if (largest < array[i])

largest = array[i];

printf("\n largest element present in the given array is : %d", largest);

return 0;

a) With the help of flow chart explain compiling and execution of a C program (2.5)

S . I N
T U N OTE
K

Downloaded from Ktunotes.in


S . I N
T U N OTE
K
Compile & Execute C Program:

Lets look at how to save the source code in a file, and how to compile and run it. Following are the simple steps:
2. Open a text editor and add the above-mentioned code.
3. Save the file as hello.c
4. Open a command prompt and go to the directory where you saved the file.
5. Type gcc hello.c and press enter to compile your code.
6. If there are no errors in your code the command prompt will take you to the next line and would generate
a.out executable file.

7. Now, type a.out to execute your program.


8. You will be able to see "Hello World" printed on the screen.

b) Write a C program to largest among two numbers using conditional operator


/* Write a program to find Greatest Number among two numbers using Conditional Operators */

#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,big;
Downloaded from Ktunotes.in
clrscr();
printf("\n Enter TwoNumbers”);
scanf("%d%d",&n1,&n2);
big = ((n1>n2)?n1:n2);
printf("\n The Greater Number is %d",big);
getch();

Output
Enter Two numbers
5
11
The Greater Number is 11

b) Write a C program to multiply two matrices using the concept of 2D arrays. (10)
#include <stdio.h>

int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;

printf("Enter rows and column for first matrix: ");


scanf("%d %d", &r1, &c1);

printf("Enter rows and column for second matrix: ");

S . I N
OTE
scanf("%d %d",&r2, &c2);

while (c1 != r2)


{
K U N
// Column of first matrix should be equal to column of second matrix and

T
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}

// Storing elements of first matrix.


printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

// Storing elements of second matrix.


printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}

// Initializing all elements of result matrix to 0


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}
Downloaded from Ktunotes.in
// Multiplying matrices a and b and
// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}

// Displaying the result


printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}

Output

Enter rows and column for first matrix: 3


2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:

S . I N
OTE
Enter elements a11: 3
Enter elements a12: -2
Enter
Enter
Enter
Enter
elements
elements
elements
elements
a13: 5
a21: 3
a22: 0
a23: 4 K T U N
Enter elements of matrix 2:
Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29

6 25
PART B
4
a) Explain the concept of Pointer in C with the help of example (5)
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointer may appear little confusing and complicated in the
beginning, but trust me its a powerful tool and handy to use once its mastered.

Benefit of using pointers

Pointers are more efficient in handling Array and Structure.


Pointer allows references to function and thereby helps in passing of function as
Downloaded
arguments to other function. from Ktunotes.in
We can access the value 10 by either using the variable name a or the address 80F. Since the memory
addresses are simply numbers they can be assigned to some other variable. The variable that holds
memory address are called pointer variables. A pointer variable is therefore nothing but a variable
that contains an address, which is a location of another variable. Value of pointer variable will be
stored in another memory location.
General syntax of pointer declaration is,
data-type *pointer_name;
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer
initialization or,
int *ptr = &a ; //initialization and declaration together
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int
a,*p; a
= 10;
p = &a;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value

of a. printf("%u",&a); //this will print the address

S . I N
OTE
of a. printf("%u",p); //this will also print the

T U N
address of a. printf("%u",&p); //this will also

print the address of p. K


b) Write a program in C to store n elements in an array and print the elements using pointer
#include <stdio.h>
int main()
{
int arr1[25], i,n;
printf("\n\n Pointer : Store and retrieve elements from an array :\n");
printf("------------------------------------------------------------\n");
printf(" Input the number of elements to store in the array :");
scanf("%d",&n);

printf(" Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf(" element - %d : ",i);
scanf("%d",arr1+i);
}
printf(" The elements you entered are : \n");
for(i=0;i<n;i++)
{
printf(" element - %d : %d \n",i,*(arr1+i));
}
return 0;
}

Sample Output:

Pointer : Store and retrieve elements from an array :


------------------------------------------------------------
Input the number of elements to store in the array :5
Downloaded from Ktunotes.in
Input 5 number of elements in the array :
element - 0 : 5
element - 1 : 7
element - 2 : 2
element - 3 : 9
element - 4 : 8
The elements you entered are :
element - 0 : 5

c) Write a C program to store and display the following details of n students using structure.
Name, Rollno,Marks

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];

int main()
{
int i;

printf("Enter information of students:\n");

// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;

printf("\nFor roll number%d,\n",s[i].roll);

printf("Enter name: ");


scanf("%s",s[i].name);
S . I N
T U N
printf("Enter marks: ");
scanf("%f",&s[i].marks); OTE
}
printf("\n"); K
printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}

Output

Enter information of students:

For roll number1,


Enter name: Tom
Enter marks: 98

For roll number2,


Enter name: Jerry
Enter marks: 89
.
.
.
Displaying Information: Downloaded from Ktunotes.in
Roll number: 1
Name: Tom
Marks: 98

5 a) Distinguish call by value and call by reference with the help of examples (10)

Function Call By Value And Call By Reference.


Function Call By Value
For example if we define a function to return the square of a number:

int squared (int i)


/* Squares i */
{
i= i*i;
return
i;
}

then we can test it with this code:

#include

<stdio.h> int

main()
{
int i= 2;
printf ("i squared is

S . I N
OTE
%d\n",squared(i)); printf ("i is
%d\n",i);

}
return 0;
K T U N
which will print:

i squared is 4 i is 2

it will NOT print:

i squared is 4 i is 4

The reason for this is that functions only have a local copy of the values sent to them. In C this is
known as pass by value or Call by value. Variables passed by value to a function.

Using a function you can create an addition to the C language which takes a number of arguments
and may return a single value.

Call By Reference
void swap(int a, int b)
{
a = a+b;
b=a-b;
a=a-b;
}
int main()
{
int a,b; Downloaded from Ktunotes.in
a=10;
b=5;
printf(“a= %d and b= %d”, a,b);
swap(a,b);
printf(“a= %d and b= %d”, a,b);
}
the output will be : a=10 and
b=5
a=10 and b=5

Take the following example :

void swap(int *a, int *b)


{
*a = *a+*b;
*b=*a-*b;
*a=*a-*b;
}
int main()
{
int a,b;
a=10;
b=5;
printf(“a= %d and b= %d”, a,b);
swap(&a,&b);
printf(“a= %d and b= %d”, a,b);
}
the output will be : a=10 and
b=5

S . I N
OTE
a=5 and b=10
In the second function, the numbers are swaped because the function is called by reference and the values are

T U N
exchanged. The Address of variables are passed to the function. So whatever change we do in the function is done

K
in the value inside the address. The fig.depicts the same.

Downloaded from Ktunotes.in


b)Explain the concept of Recursive function with the help of an example C program to find Factorial of a
number.

Recursive functions.
Recursion is a special property of the function. When a function calls itself then it is called recursion.
In the function with name recfun the function definition contains the function call to itself.
The execution is as follows :

The recfun() is called with arguement 5. inside the function it prints 5 and the recfun with arguement 4 is called in
which 4 is printed and recfun(3) called and so on upto recfun(0). The function recfun(0) returns without calling other

. I N
function and then recfun(1) returns and so on upto recfun(5) returns to the called function main.

S
Factorial of a Number using recurssion

T U N OTE
#include <stdio.h>
long int multiplyNumbers(int n); K
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Output

Enter a positive integer: 6


Factorial of 6 = 720
6 a Write a C program to sort an Array using Pointer.

Sorting an array using Pointer


#include <stdio.h>
#include <conio.h>
void sorting(int *x,
int y); void main()
{
Downloaded from Ktunotes.in
int
a[5],b,
c;
clrscr()
;
printf("enter 5 nos");
for(b=0; b<5; b++)
{
scanf("%d",&a[b]);
}
sorting(a, 5);
getch();
}

void sorting(int *x, int y)


{
int i,j,temp;
for(i=1; i<=y-1; i++)
{
for(j=0; j*(x+j+1))
{
temp=*(x+j);
*(x+j)=*(x+j
+1);
*(x+j+1)=tem
p;
}
}
}
for(i=0; i<5; i++)
{
Printf(“\n Sorted elements are:”);
printf("\t%d",*(x+i));

S . I N
OTE
}
}
output
enter 5 nos;
K T U N
2 5 6 7 11
Sorted elements are: 11 7 6 5 2
b)Write a C program to compute basic arithmetic functions using functions.

b)
#include<stdio.h>
void main()
{
int a,b,c,d,e,f;
clrscr();
printf("Enter Two Values :");
scanf("%d%d",&a,&b);
sum(a,b);
mult(a,b);
div(a,b);
getch();
}
sum(int x,int y)
{
int z;
z=x+y;
printf("Addtion : %d\n",z);
return 0;
}
mult(int x,int y)
{
Downloaded from Ktunotes.in
int z;
z=x*y;
printf("Multiply : %d\n",z);
return 0;
}
div(int x,int y)
{
int z;
z=x/y;
printf("Div : %d\n",z);
return 0;
}

PART C
7 a) With the help of an example C program explain Selection sort

Selection Sort
Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially. The first position where
14 is stored presently, we search the whole list and find that 10 is the lowest value.

S . I N
U N OTE
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,

T
K
appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.

We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.

After two iterations, two least values are positioned at the beginning in a sorted manner.

The same process is applied to the rest of the items in the array. Following is a pictorial depiction

of the entire sorting process −


Downloaded from Ktunotes.in
Selection sort

1. Start with the result as the first element of the input.

2. Loop over the input until it is empty, "removing" the first remaining (leftmost)
element.

3. Compare the removed element against the current result, starting


from the highest (rightmost) element, and working left towards the
lowest element.

4. If the removed input element is lower than the current result


element, copy that value into the following element to make room
for the new element below, and repeat with the next lowest result
element.

5. Otherwise, the new element is in the correct location; save it in the


cell left by copying the last examined result up, and start again from
(2) with the next input element.

Algorithm :

Step 1 − Set MIN to location 0


Step 2 − Search the
S . I N
OTE
minimum element in the list
Step 3 − Swap with value at
location MIN
K T U N
Step 4 − Increment MIN to
point to next element Step 5 −
Repeat until list is sorted

/*
* C Program to Implement Selection Sort
*/
#include <stdio.h>
void selectionSort(int arr[], int size)
{
int i, j;
for (i = 0 ; i < size;i++)
{
for (j = i ; j < size; j++)
{
if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);

}
}
}
//fucntion to swap to variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;

Downloaded from Ktunotes.in


}
int main()
{
int array[10], i, size;
printf("How many numbers you want to sort: ");
scanf("%d", &size);
printf("\nEnter %d number", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
selectionSort(array, size);
printf("\nSorted array is ");

for (i = 0; i < size;i++)


printf(" %d ", array[i]);
return 0;

}
output

How many numbers you want to sort: 5

Enter 5 numbers : 34 13 204 355 333

Sorted array is : 13 34 204 333 355

b) With the help of an example C program explain Recursive Binary Search

S . I N
The idea of binary search is to use the information that the array is sorted and

OTE
reduce the time complexity to O(Logn).

T U N
We basically ignore half of the elements just after one comparison.

K
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right
half subarray after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
Recursive implementation of Binary Search

#include<stdio.h>
int main(){

int a[10],i,n,m,c,l,u;

printf("Enter the size of an array: ");


scanf("%d",&n);

printf("Enter the elements of the array: " );


for(i=0;i<n;i++){
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");


scanf("%d",&m);

l=0,u=n-1;

Downloaded from Ktunotes.in


c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not found.");
else
printf("Number is found.");

return 0;
}

int binary(int a[],int n,int m,int l,int u){

int mid,c=0;

if(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
}
else if(m<a[mid]){
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}

Sample output:

S . I N
OTE
Enter the size of an array: 5

N
Enter the elements of the array: 8 9 10 11 12

T U
Enter the number to be search: 8
Number is found.
K
8 a) Write notes on any ten file handling functions with syntax (10)

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the
purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
mode description
r opens a text file in reading mode
w opens or create a
text file in writing mode. a
opens a text file in
append mode
r+ opens a text file in both reading
and writing mode w+ opens a text
file in both reading and writing

Downloaded from Ktunotes.in


mode a+ opens a text file in both
reading and writing mode rb opens
a binary file in reading mode
wb opens or create a
binary file in writing mode ab
opens a binary file in
append mode
rb+ opens a binary file in both reading
and writing mode wb+ opens a binary
file in both reading and writing mode
ab+ opens a binary file in both
reading and writing mode

Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF if
there is an error in closing the file. This EOF is a constant defined in the
header file stdio.h.

S . I N
Input/Output operation on File

T U N OTE
K
In the above table we have discussed about various file I/O functions to perform
reading and writing on file. getc() and putc() are simplest functions used to
read and write individual characters to a file.
#include<stdio.h>

#
i
n
c
l
u
d
e
<
c
o
n
i
o
.
h
>

m
a
i

Downloaded from Ktunotes.in


n
(
)

F
I
L
E

*
f
p
;

c
h
a
r

c
h
;

f
p

S . I N
OTE
f
o
p
e K T U N
n
(
"
o
n
e
.
t
x
t
"
,

"
w
"
)
;

p
r
i
n
t

Downloaded from Ktunotes.in


f
(
"
E
n
t
e
r

d
a
t
a
"
)
;

while( (ch = getchar()) != EOF) {

p
u
t
c
(
c
h
,
f
p

S . I N
OTE
)
;

K T U N
}

fclose(fp);

fp = fopen("one.txt", "r");

w
h
il
e
(
(
c
h

g
e
t
c
(
f
p

Downloaded from Ktunotes.in


)
!
=

E
O
F
)
p
r
i
n
t
f
(
"
%
c
"
,
c
h
)
;

fclose(fp);

N
}

S . I
T U N
Reading and Writing in a Binary File OTE
K
A Binary file is similar to the text file, but it contains only large numerical
data. The Opening modes are mentioned in the table for opening modes
above.
fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data-element-to-be-
written,
size_of_elements
,
number_of_elem
ents, pointer-to-
file);

fread() is also used in the same way, with the same arguments like fwrite()
function. Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown
fox jumps over the lazy dog"; FILE *bfp=
fopen("test.txt", "wb");

if (bfp) {

fwrite(mytext,
sizeof(char),

Downloaded from Ktunotes.in


strlen(mytext), bfp) ;
fclose(bfp) ;

fseek(), ftell() and rewind() functions

• fseek() - It is used to move the reading control to different positions using


fseek function.
• ftell() - It tells the byte location of current position of cursor in file pointer.
• rewind() - It moves the control to beginning of the file.

We will be using fseek() and ftell() functions to find the size of the
file. There are others ways to find the file size, like looping on the whole
content of file and finding out the size, but using File Handling functions
makes it easier.
#include<stdio.h>

#include<conio.h>

void main()

F
I
L
E

S . I N
OTE
*
f
p
;
K T U N
c
h
a
r

c
h
;

int size = 0;

fp
=
fo
pe
n(
"
M
yF
ile
.tx
t",
"r

Downloaded from Ktunotes.in


");
if
(f
p
==
N
UL
L)

printf("\nFile unable to open ");

else

printf("\nFile opened ");

fseek(fp, 0, 2); /* file pointer at the end of file */

size = ftell(fp); /* take a position of file


pointer un size variable */ printf("The
size of given file is : %d\n", size);

fclose(fp);

S . I N
T U N OTE
b)
K
Explain the concept of Command Line Argument with the help of an example.

Command Line Argument


Command line argument is a parameter supplied to the program when it is
invoked. Command line argument is an important concept in C programming. It
is mostly used when you need to control your program from outside. command
line arguments are passed to main() method.
Syntax :
int main( int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ]
is a pointer array which holds pointers of type char which points to the
arguments passed to the program.

Example for Command Line Argument


#include <stdio.h>

#include <conio.h>

int main( int argc, char *argv[] )

Downloaded from Ktunotes.in


int i;

if( argc >= 2 )

printf("The
arguments
supplied are:\n");
for(i=1;i< argc;i++)

printf("%s\t",argv[i]);

else

printf("argument list is empty.\n");

} getch();

Return (0);

I N
Remember that argv[0] holds the name of the program and argv[1] points to the

S .
OTE
first command line argument and argv[n] gives the last argument. If no argument
is supplied, argc will be one.

9 a)
K T U N
Discuss storage classes with the help of examples.
Scope rules Storage classes.

Storage class in C decides the part of storage to allocate memory for a


variable, it also determines the scope of a variable. All variables defined in a
C program get some physical location in memory where variable's value is
stored. Memory and CPU registers are types of memory locations where a
variable's value can be stored. The storage class of a variable in C
determines the life time of the variable if this is 'global' or 'local'. Along with
the life time of a variable, storage class also determines variable's storage
location (memory or registers), the scope (visibility level) of the variable,
and the initial value of the variable. There are four storage classes in C those
are automatic, register, static, and external.

Storage Class Specifiers


There are four storage class specifiers in C as follows, typedef specifier
does not reserve storage and is called a storage class specifier only for
syntactic convenience. It is not a storage class specifier in the common
meaning.
• auto
• register
• extern

Downloaded from Ktunotes.in


• static
• typedef
These specifiers tell the compiler how to store the subsequent variable. The
general form of a variable declaration that uses a storage class is shown
here:
storage_class_specifier data_type variable_name;

At most one storage class specifier may be given in a declaration. If no


storage class specifier is specified then following rules are used:
1. Variables declared inside a function are taken to be auto.
2. Functions declared within a function are taken to be extern.
3. Variables and functions declared outside a function are taken to
be static, with external linkage.

Variables and functions having external linkage are available to all files
that constitute a program. File scope variables and functions declared as
static (described shortly) have internal linkage. These are known only
within the file in which they are declared. Local variables have no linkage
and are therefore known only within their own block.

Types of Storage Classes


There are four storage classes in C they are as follows:
1. Automatic Storage Class
S . I N
2.
3.
Register Storage Class

T U N
Static Storage Class OTE
4.
K
External Storage Class
Now, let us discuss these storage classes one by one.

1. Automatic Storage Class


A variable defined within a function or block with auto specifier belongs to
automatic storage class. All variables defined within a function or block by
default belong to automatic storage class if no storage class is mentioned.
Variables having automatic storage class are local to the block which they are
defined in, and get destroyed on exit from the block.
The following C program demonstrates the visibility level of auto variables.
#include<stdio.h>
Main()
{
auto int i = 1;
{
auto int i = 2;
{
Auto int
i=3;
printf ( "\n %d
",i);
}
printf ( "%d ", i);
}
printf( "%d\n ", i);
}

Downloaded from Ktunotes.in


OUTPUT
3

In above example program you see three definitions for variable i. Here, you
may be thinking if there could be more than one variable with the same name.
Yes, there could be if these variables are defined in different blocks. So, there
will be no error here and the program will compile and execute successfully.
The printf in the inner most block will print 3 and the variable i defined
in the inner most block gets destroyed as soon as control exits from the block.
Now control comes to the second outer block and prints 2 then comes to the
outer block and prints 1. Here, note that automatic variables must always be
initialized properly, otherwise you are likely to get unexpected results
because automatic variables are not given any initial value by the compiler.

2. Register Storage Class


The register specifier declares a variable of register storage class.
Variables belonging to register storage class are local to the block which they
are defined in, and get destroyed on exit from
the block. A register declaration is equivalent to an auto declaration,
but hints that the declared variable will be accessed frequently; therefore they
are placed in CPU registers, not in memory. Only a few variables are actually
placed into registers, and only certain types are eligible; the restrictions are
implementation-dependent. However, if a variable is declared register, the
unary & (address of) operator may not be applied to it, explicitly or

. I N
implicitly. Register variables are also given no initial value by the compiler.
S
OTE
The following piece of code is trying to get the address of variable i into

K T U N
pointer variable p but it won't succeed because i is declared register;
therefore following piece of code won't compile and exit with error "error:
address of register variable requested".

#include <stdio.h>

int main()

register int i = 10;

int *p = &i; //error: address of register variable requested

printf("Val
ue of i:
%d", *p);
printf("Add
ress of
i: %u",
p);

3. Static Storage Class

Downloaded from Ktunotes.in


The static specifier gives the declared variable static storage class. Static
variables can be used within function or file.Unlike global variables, static
variables are not visible outside their function or file, but they maintain their
values between calls. The static specifier has different effects upon
local and global variables. See the following flavours of static specifier.
• When static specifier is applied to a local variable inside a
function or block, the compiler creates permanent storage for it,
much as it creates storage for a global variable but static local
variable remains visible only to the function or block in which it is
defined. In simple terms, a static local variable is a local variable
that retains its value between function calls. For example, the
following program code defines static variable i at two places
in two blocks inside function staticDemo(). Function
staticDemo() is called twice within from main function.
During second call static variables retain their old values and they
are not initialized again in second call of staticDemo().
#include <stdio.h>

• When static specifier is applied to a global variable or a


function then compiler makes that variable or function known
only to the file in which it is defined. A static global variable has
internal linkage that means even though the variable is global;
routines in other files have no knowledge of it and cannot access
and alter its contents directly. The following C program defines
one static global variable gInt and a static function
staticDemo(), for the variable and function are defined static

staticdemo.c..
S . N
they cannot be used outside the file (translation unit)
I
/* staticdemo.c */

T U N OTE
K
#include <stdio.h>

static int gInt = 1;

static void staticDemo()

Static in i;

printf("%d ", i);

i++;

printf("%d\n", gInt);

gInt++;

int main()

Static Demo();

Static Demo();

Output

Downloaded from Ktunotes.in


0 1
1 2

Static variables have default initial value zero and initialized only once in their
lifetime.

1. External Storage Class


The extern specifier gives the declared variable external storage class. The
principal use of extern is to specify that a variable is declared with external
linkage elsewhere in the program. To understand why this is important, it is
necessary to understand the difference between a declaration and a definition.
A declaration declares the name and type of a variable or function. A
definition causes storage to be allocated for the variable or the body of the
function to be defined. The same variable or function may have many
declarations, but there can be only one definition for that variable or function.
When extern specifier is used with a variable declaration then no
storage is allocated to that variable and it is assumed that the variable has
already been defined elsewhere in the program. When we use extern
specifier the variable cannot be initialized because with extern specifier
variable is declared, not defined.
In the following sample C program if you remove extern int x; you
will get an error "Undeclared identifier 'x'" because variable x is defined

I N
later than it has been used in printf. In this example, the extern

S .
OTE
specifier tells the compiler that variable x has already been defined and it is
declared here for compiler's information.

int main()
K T U N
#include <stdio.h> extern int x;

{
printf("x: %d\n ", x);
}

int x = 10;

Also, if you change the statement extern int x; to extern int x =


50; you will again get an error "Redefinition of 'x'" because with extern
specifier the variable cannot be initialized, if it is defined elsewhere. If not
then extern declaration becomes a definition.
Note that extern can also be applied to a function declaration, but doing so
is redundant because all function declarations are implicitly extern.

b) Write a C program to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.

#include <stdio.h>

int main() {

char name[50];

Downloaded from Ktunotes.in


int marks,i,n;

printf("Enter number of students: ");

scanf("%d",&n);

FILE *fptr;

fptr=(fopen("C:\\student.txt","a"));

if(fptr==NULL) {

printf("Error!");

exit(1);

for (i=0;i<n;++i) {

printf("For student%d\nEnter name: ",i+1);

scanf("%s",name);

printf("Enter marks: ");

scanf("%d",&marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);

S . I N
OTE
fclose(fptr);

}
return 0;

K T U N

Downloaded from Ktunotes.in

You might also like