0% found this document useful (0 votes)
18 views166 pages

University Question Bank With Answer

The document is a question bank for a Programming in C course from Ultra College of Engineering and Technology, covering various topics such as operators, preprocessor directives, arrays, sorting algorithms, pointer arithmetic, storage classes, looping statements, matrix operations, function prototypes, and concepts of pass by value and pass by reference. It includes both theoretical questions and practical programming exercises with sample code and expected outputs. The content is structured into two parts, with Part A consisting of short answer questions and Part B focusing on programming tasks.

Uploaded by

su ja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views166 pages

University Question Bank With Answer

The document is a question bank for a Programming in C course from Ultra College of Engineering and Technology, covering various topics such as operators, preprocessor directives, arrays, sorting algorithms, pointer arithmetic, storage classes, looping statements, matrix operations, function prototypes, and concepts of pass by value and pass by reference. It includes both theoretical questions and practical programming exercises with sample code and expected outputs. The content is structured into two parts, with Part A consisting of short answer questions and Part B focusing on programming tasks.

Uploaded by

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

Ultra College of Engineering and Technology ,Madurai

Programming in C University Question Bank – Answers

Nov-dec 2022

PART A-(10x2 marks).

1. What are the various types of operators?

 Arithmetic Operators.
 Decrement and Increment Operators.
 Assignment Operators.
 Logical Operators.
 Conditional Operator.
 Bitwise Operators.
 Special Operators.

2 .What is the use of preprocessor directive?

Preprocessor directives, such as #define and #ifdef , are typically used to make source programs
easy to change and easy to compile in different execution environments. Directives in the source
file tell the preprocessor to take specific actions.

3. Declare a float array of size 5 and assign 5 values to it.

#include<stdio.h>

void main()

float arr[5]={10.0,20.4,30.6,40.9,50.3};

Printf(“%f”,arr[]);

}
Output

10.0 20.4 30.6 40.9 50.3

4. Sort the following elements using selection sort method 23,55,16,78,2.

5. How is pointer arithmetic done?

These operations include incrementing, decrementing, adding integers, subtracting integers, and
comparing pointers.

6. Which is better to use? Macro or function. Justify your answer.

Macro is better to use.Because

Macro Function

Macros are Preprocessed Functions are Compiled

No Type Checking is done in Macro Type Checking is Done in Function

Speed of Execution using Macro is Faster Speed of Execution using Function is Slower

7. What is meant by structure definition?

The Structure in C is a user defined data type that can be used to group the elements in different
elements.

Syntax:

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

8. Define self-referential data structure.

It is a Structure that points to the same type of structure.It contains one or more pointers that
ultimately points to tha same structure.

9. Why are files needed?

Entire data is lost when the program terminates and storing in a file will preserve your data even
if the program terminates. If you want to enter a large amount of data, normally, it takes a lot of
time to enter them all.

10. Give an example for fseek().

#include <stdio.h>

int main()

FILE* fp;

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

fseek(fp, 0, SEEK_END);

printf("%ld", ftell(fp));

return 0;

PART B-(5x1680 marks).

11. (a) Explain the storage classes in 'C' with suitable examples.
Defintion:

C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a
particular variable during the runtime of a program

The storage class are

1. Auto
2. Extern
3. Static
4. Register

1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope).

2.Extern

extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern
keyword extends the visibility of the C variables and C functions. That’s probably the reason
why it was named extern.

Syntax:

extern data_type variable_name;

Program:

#include <stdio.h>

extern int var;

int main(void)

{
var = 10;

return 0;

Output:
10

Static:

Static variables have the property of preserving their value even after they are out of their
scope! Hence, a static variable preserves its previous value in its previous scope and is not
initialized again in the new scope.

Syntax:
static data_type var_name = var_value;

#include <stdio.h>

int fun()

static int count = 0;

count++;

return count;

int main()

{
printf("%d ", fun());

printf("%d ", fun());

return 0;

Output
12

Registers

Registers are faster than memory to access, so the variables which are most frequently used in
a C program can be put in registers using the register keyword. #include <stdio.h>

int main()

int i = 10;

register int* a = &i;

printf("%d", *a);

getchar();

return 0;

Output

10

(b) Explain the looping statement in C with suitable examples.


Looping Statement

Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple
times without repetition of code.

For loop:

For loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to perform
n number of steps together in a single line.

Syntax:
for (initialize expression; Condition;Increment/Decrement)

//

// body of for loop

//

Example:

#include <stdio.h>

int main()

int i = 0;

for (i = 1; i<= 5; i++)

printf( "Hello World\n");

}
return 0;

Output:

Hello World

Hello World

Hello World

Hello World

Hello World

While Loop:

While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of
the test condition.

Syntax:

while (Condition)

// body of the while loop

program

#include <stdio.h>

int main()

int i = 0;
while(i<5)

printf( "Hello World\n");

i++;

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

do-while Loop

The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body.

Syntax

do

// body of do-while loop

} while (Condition);

Program:

#include <stdio.h>
int main()

int i = 2;

do

printf( "Hello World\n");

i++;

} while (i< 1);

return 0;

Output

Hello World

12. (a) (1) Write a C program to multiply two matrices (2) array) by getting input from the
user. (8)

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

Output:

enter the number of row=3


enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

(ii) Write a C program to find scaling of two matrices (21) array) which will be entered by
a user. (8)

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

int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter the number of rows (between 1 and 100): ");

scanf("%d", &r);

printf("Enter the number of columns (between 1 and 100): ");

scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

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

for (j = 0; j < c; ++j) {

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("Enter elements of 2nd matrix:\n");

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

for (j = 0; j < c; ++j) {

printf("Enter element b%d%d: ", i + 1, j + 1);

scanf("%d", &b[i][j]);

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

for (j = 0; j < c; ++j) {

sum[i][j] = a[i][j] + b[i][j];

}
printf("\nSum of two matrices: \n");

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

for (j = 0; j < c; ++j) {

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

if (j == c - 1) {

printf("\n\n");

return 0;

Ouput:

Enter the number of rows (between 1 and 100): 2


Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6

13.i) Classify the function prototypes with suitable examples.

Definition:

C function prototype is a statement that tells the compiler about the function’s name, its return
type, numbers and data types of its parameter.

Syntax
return_type function_name(parameter_list);
 return_type: It is the data type of the value that the function returns. It can be any data
type int, float, void, etc. If the function does not return anything, void is used as the return
type.
 function_name: It is the identifier of the function. Use appropriate names for the functions
that specify the purpose of the function.
 parameter_list: It is the list of parameters that a function expects in parentheses. A
parameter consists of its data type and name.

Program:
#include <stdio.h>
int main() {
printf("The sum is %d\n", add(2, 3));
return 0;
}
int add(int num1, int num2) {
return num1 + num2;
}

Output:

The sum is 5

13 ii) Write a C program to design the scientific calculator using built-in functions. (8)

#include <stdio.h>
int main()
{
char opt;
int n1, n2;
float res;
printf (" Choose an operator(+, -, *, /) to perform the operation in C Calculator \n ");
scanf ("%c", &opt);
if (opt == '/' )
{
printf (" You have selected: Division");
}
else if (opt == '*')
{
printf (" You have selected: Multiplication");
}

else if (opt == '-')


{
printf (" You have selected: Subtraction");
}
else if (opt == '+')
{
printf (" You have selected: Addition");
}
printf (" \n Enter the first number: ");
scanf(" %d", &n1); // take fist number
printf (" Enter the second number: ");
scanf (" %d", &n2); // take second number
switch(opt)
{
case '+':
res = n1 + n2; // add two numbers
printf (" Addition of %d and %d is: %.2f", n1, n2, res);
break;
case '-':
res = n1 - n2; // subtract two numbers
printf (" Subtraction of %d and %d is: %.2f", n1, n2, res);
break;

case '*':
res = n1 * n2; // multiply two numbers
printf (" Multiplication of %d and %d is: %.2f", n1, n2, res);
break;
case '/':
if (n2 == 0) // if n2 == 0, take another number
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &n2);
}
res = n1 / n2; // divide two numbers
printf (" Division of %d and %d is: %.2f", n1, n2, res);
break;
default: /* use default to print default message if any condition is not satisfied */
printf (" Something is wrong!! Please check the options ");
}
return 0;
}

Output:

(b) (i) Explain the concept of pass by value and pass by reference. Write a C program to a
swap the content of two variables using pass by reference. (8)

Call by value in C

 In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
 In call by value method, we can not modify the value of the actual parameter by the
formal parameter.

#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

 In call by reference, the address of the variable is passed into the function call as the
actual parameter.
 The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed

Call by reference Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
}

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

(ii) Explain about pointers and write the use of pointers in arrays with suitable example. (8)

Pointer
A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.

Syntax of C Pointers
datatype * ptr;

where
 ptr is the name of the pointer.
 datatype is the type of data it is pointing to.
Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables that are references
to a memory location.

Syntax:
pointer_type *array_name [array_size];

Here,
 pointer_type: Type of data the pointer is pointing to.
 array_name: Name of the array of pointers.
 array_size: Size of the array of pointers.

C program to demonstrate the use of array of pointers

#include <stdio.h>

int main()

int var1 = 10;

int var2 = 20;

int var3 = 30;

int* ptr_arr[3] = { &var1, &var2, &var3 };

for (int i = 0; i < 3; i++) {

printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);

return 0;

Output
Value of var1: 10 Address: 0x7fff1ac82484

Value of var2: 20 Address: 0x7fff1ac82488

Value of var3: 30 Address: 0x7fff1ac8248c

Explanation:
14. (a) What is a structure? Create a structure with data members of various types and
declare two structure variables. Write a program to read data into these and print the
same. Justify the need for structured data type.

Definition:

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language.

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
#include <stdio.h>

struct employee{

char name[30];

int empId;

float salary;

};

int main()

struct employee emp;

printf("\nEnter details :\n");

printf("Name :"); gets(emp.name);

printf("ID :"); scanf("%d",&emp.empId);

printf("Salary :"); scanf("%f",&emp.salary);


printf("\nEntered detail is:");

printf("Name: %s" ,emp.name);

printf("Id: %d" ,emp.empId);

printf("Salary: %f\n",emp.salary);

return 0;

Output:

Enter details :

Name :Mike

ID :1120

Salary :76543

(b) Write a C program to create mark sheet for students using self- referential structure.

Self- referential structure:

It is a Structure that points to the same type of structure.It contains one or more pointers that
ultimately points to tha same structure.
Program:

#include <stdio.h>

struct Student {

char* name;

int roll_number;

int age;

double total_marks;

};

int main()

int i = 0, n = 5;

struct Student student[n];

student[0].roll_number = 1;

student[0].name = "Geeks1";
student[0].age = 12;

student[0].total_marks = 78.50;

student[1].roll_number = 5;

student[1].name = "Geeks5";

student[1].age = 10;

student[1].total_marks = 56.84;

student[2].roll_number = 2;

student[2].name = "Geeks2";

student[2].age = 11;

student[2].total_marks = 87.94;

student[3].roll_number = 4;

student[3].name = "Geeks4";

student[3].age = 12;

student[3].total_marks = 89.78;

student[4].roll_number = 3;

student[4].name = "Geeks3";

student[4].age = 13;

student[4].total_marks = 78.55;

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

printf("\tName = %s\n", student[i].name);

printf("\tRoll Number = %d\n", student[i].roll_number);


printf("\tAge = %d\n", student[i].age);

printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks);

return 0;

Output:

Student Records:

Name = Geeks1

Roll Number = 1

Age = 12

Total Marks = 78.50

Name = Geeks5

Roll Number = 5

Age = 10

Total Marks = 56.84

Name = Geeks2

Roll Number = 2

Age = 11

Total Marks = 87.94


Name = Geeks4

Roll Number = 4

Age = 12

Total Marks = 89.78

Name = Geeks3

Roll Number = 3

Age = 13

Total Marks = 78.55

15. (a) (i) Write a C program to get name and marks of 'n' number of students from user
and store them in a file. (8)

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr; fptr = (fopen("C:\\student.txt","w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i =0; i < num; ++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);
}
fclose(fptr);
return 0;
}

Output:

See your file directory

(ii) 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 then append the information into the existing
file. (8)

#include <stdio.h>

int main()

char name[50];

int marks,i,num;

printf("Enter number of students: ");

scanf("%d", &num);

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

if(fptr == NULL)

{
printf("Error!");

exit(1);

for(i =0; i < num; ++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);

fclose(fptr);

Output:

Enter Number of Students: 3

For Student 1

Enter Name: xxx

Enter Marks: 98

For Student 2

Enter Name: yyy

Enter Marks: 88

For Student 3

Enter Name: zzz


Enter Marks: 90

(b) Write a C program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen. (8)

#include <stdio.h>

#include <stdlib.h>

struct person {

int id;

char fname[20];

char lname[20];

};

int main()

FILE* infile;

infile = fopen("person1.dat", "wb+");

if (infile == NULL) {

fprintf(stderr, "\nError opening file\n");

exit(1);

struct person write_struct = { 1, "Rohan", "Sharma" };

fwrite(&write_struct, sizeof(write_struct), 1, infile);

struct person read_struct;


rewind(infile);

fread(&read_struct, sizeof(read_struct), 1, infile);

printf("Name: %s %s \nID: %d", read_struct.fname,

read_struct.lname, read_struct.id);

fclose(infile);

return 0;

Output
Name: Rohan Sharma

ID: 1

Describe command line arguments with example C program. (8)

The arguments passed from command line are called command line arguments. These arguments
are handled by main() function.

Syntax
int main(int argc, char *argv[]) { /* ... */ }

or

int main(int argc, char **argv) { /* ... */ }

Properties:

1. They are passed to the main() function.


2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control programs from outside instead of hard coding those values inside
the code.
Program:

#include <stdio.h>

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

printf("Program name is: %s", argv[0]);

if (argc == 1)

printf("\nNo Extra Command Line Argument Passed "

"Other Than Program Name");

if (argc >= 2) {

printf("\nNumber Of Arguments Passed: %d", argc);

printf("\n----Following Are The Command Line "

"Arguments Passed----");

for (int i = 0; i < argc; i++)

printf("\nargv[%d]: %s", i, argv[i]);

return 0;

Output
Program Name Is: ./a.out

No Extra Command Line Argument Passed Other Than Program Name

(b) (i) Write a C program to find determinant of a matrix (2D array) which will be entered
by a user.
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] *b[i][j];
}

printf("\nSum of two matrices: \n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}
Output

Enter the number of rows (between 1 and 100): 2


Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6

(ii) Write a C program for matrix transpose.

C Program:
#include<stdio.h>
int main(){
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10^5][10^5];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
12
23
34
The transposed matrix is:
123
234

April may2018

PART-A

1. What is external storage class?

extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern
keyword extends the visibility of the C variables and C functions. That’s probably the reason
why it was named extern.

Syntax:

extern data_type variable_name;


2. How does a preprocessor work?

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform your program before actual compilation. It is called a macro processor.

3. What is an array? Write the syntax for multi-dimensional array.

Array is a collection of elements in same data type.

Syntax for multi-dimensional array

data_type array_name[size1][size2]....[sizeN];
 data_type: Type of data to be stored in the array.
 array_name: Name of the array.
 size1, size2,…, sizeN: Size of each dimension.

4. Design a C program for compare any two string.

#include <stdio.h>

#include <string.h>

int main()

{
char* first_str = "Geeks";

char* second_str = "Geeks";

printf("First String: %s\n", first_str);

printf("Second String: %s\n", second_str);

printf("Return value of strcmp(): %d",

strcmp(first_str, second_str));

return 0;

Output

First String: Geeks

Second String: Geeks

Return value of strcmp(): 0

5. List the advantages of recursion.


6. When null pointer is used?

A Null pointer can be used in the following ways: When the pointer variable does not point to a
valid memory address, it is used to initialize it.

Example:

7. State the meaning of the root word struct.

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language.

Syntax:

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};

8. Specify the use of typedef.

The C typedef keyword is used to redefine the name of already existing data types.

When names of datatypes become difficult to use in programs, typedef is used with user-
defined datatypes, which behave similarly to defining an alias for commands.

C typedef Syntax

typedef existing_name alias_name;


9. How can you restore a redirected standard stream?

By using the standard C library functions named dup() and fdopen(), you can restore a standard
stream such as stdout to its original state. The dup() function duplicates a file handle. You can
use the dup() function to save the file handle corresponding to the stdout standard stream.

10. What does arg v and arg cindicate in command-line arguments?

argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program.

argv (ARGument Vector) is an array of character pointers listing all the arguments.

PART-B

11. a) i) Explain the different types of operators used in C with necessary program.

C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

S. No. Symbol Operator Syntax

1 + Plus a+b

2 – Minus a–b

3 * Multiply a*b
S. No. Symbol Operator Syntax

4 / Divide a/b

5 % Modulus a%b

Used to specify
+ Unary Plus the positive
6 values.

Flips the sign of


– Unary Minus
7 the value.

Increases the
++ Increment value of the
8 operand by 1.

Decreases the
— Decrement value of the
9 operand by 1.

C program

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a + b = %d\n", a + b);

printf("a - b = %d\n", a - b);

printf("a * b = %d\n", a * b);


printf("a / b = %d\n", a / b);

printf("a % b = %d\n", a % b);

printf("+a = %d\n", +a);

printf("-a = %d\n", -a);

printf("a++ = %d\n", a++);

printf("a-- = %d\n", a--);

return 0;

Output
a + b = 30

a - b = 20

a * b = 125

a/b=5

a%b=0

+a = 25

-a = -25

a++ = 25

a-- = 26

Relational Operators in C

S. No. Symbol Operator Syntax

1 < Less than a<b

2 > Greater than a>b


S. No. Symbol Operator Syntax

Less than or
<= a <= b
3 equal to

Greater than or
>= a >= b
4 equal to

5 == Equal to a == b

6 != Not equal to a != b

C program

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a < b : %d\n", a < b);

printf("a > b : %d\n", a > b);

printf("a <= b: %d\n", a <= b);

printf("a >= b: %d\n", a >= b);

printf("a == b: %d\n", a == b);

printf("a != b : %d\n", a != b);

return 0;

Output
a<b :0

a>b :1

a <= b: 0

a >= b: 1

a == b: 0

a != b : 1

Logical Operator in C

S. No. Symbol Operator Syntax

1 && Logical AND a && b

2 || Logical OR a || b

3 ! Logical NOT !a

C program

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a && b : %d\n", a && b);

printf("a || b : %d\n", a || b);

printf("!a: %d\n", !a);

return 0;
}

Output
a && b : 1

a || b : 1

!a: 0

4. Bitwise Operators in C

S. No. Symbol Operator Syntax

1 & Bitwise AND a&b

2 | Bitwise OR a|b

3 ^ Bitwise XOR a^b

Bitwise First
~ ~a
4 Complement

5 << Bitwise Leftshift a << b

Bitwise
>> a >> b
6 Rightshilft

C program

#include <stdio.h>

int main()

int a = 25, b = 5;
printf("a & b: %d\n", a & b);

printf("a | b: %d\n", a | b);

printf("a ^ b: %d\n", a ^ b);

printf("~a: %d\n", ~a);

printf("a >> b: %d\n", a >> b);

printf("a << b: %d\n", a << b);

return 0;

} Output

a & b: 1

a | b: 29

a ^ b: 28

~a: -26

a >> b: 0

a << b: 800

5. Assignment Operators in C

S. No. Symbol Operator Syntax

Simple
= a=b
1 Assignment

2 += Plus and assign a += b

3 -= Minus and assign a -= b

4 *= Multiply and a *= b
S. No. Symbol Operator Syntax

assign

5 /= Divide and assign a /= b

Modulus and
%= a %= b
6 assign

7 &= AND and assign a &= b

8 |= OR and assign a |= b

9 ^= XOR and assign a ^= b

Rightshift and
>>= a >>= b
10 assign

Leftshift and
<<= a <<=
11 assign

// C program to illustrate the arithmatic operators

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a = b: %d\n", a = b);

printf("a += b: %d\n", a += b);


printf("a -= b: %d\n", a -= b);

printf("a *= b: %d\n", a *= b);

printf("a /= b: %d\n", a /= b);

printf("a %= b: %d\n", a %= b);

printf("a &= b: %d\n", a &= b);

printf("a |= b: %d\n)", a |= b);

printf("a >>= b: %d\n", a >> b);

printf("a <<= b: %d\n", a << b);

return 0;

} Output

a = b: 5

a += b: 10

a -= b: 5

a *= b: 25

a /= b: 5

a %= b: 0

a &= b: 0

a |= b: 5

)a >>= b: 0

a <<= b: 160

ii) Write a C program to check the integer is Palindrome or not.


#include <stdio.h>

int main()

int original_number = 12321;

int reversed = 0;

int num = original_number;

while (num != 0) {

int r = num % 10;

reversed = reversed * 10 + r;

num /= 10;

if (original_number == reversed) {

printf(" Given number %d is a palindrome number", original_number);

else {

printf( " Given number %d is not a palindrome number", original_number);

return 0;

Output:

Given number 12321 is a palindrome number


b) Describe the decision making statements and looping statements in C with an example.

Decision Making:

They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not.

if in C

The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not

Syntax of if Statement
if(condition)
{
// Statements
}
C program

#include <stdio.h>

int main()

int i = 10;

if (i < 15)

printf("15 is greater than i");

Output
I am Not in if

if-else in C

The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t.

Syntax of if else in C
if (condition)
{
// condition is true
}
else
{
// condition is false
}
C program

#include <stdio.h>

int main()

int i = 20;

if (i < 15)

printf("i is smaller than 15");

else

printf("i is greater than 15");

return 0;

Output
i is greater than 15

Nested if-else in C
A nested if in C is an if statement that is the target of another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

C program

#include <stdio.h>

int main()

int i = 10;

if (i == 10)

if (i < 15)

printf("i is smaller than 15\n");

if (i < 12)

printf("i is smaller than 12 too\n");


else

printf("i is greater than 15");

return 0;

Output
i is smaller than 15

i is smaller than 12 too

switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be used to execute
the conditional code based on the value of the variable specified in the switch statement.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
C Program

#include <stdio.h>

int main()
{

int var = 2;

switch (var) {

case 1:

printf("Case 1 is executed");

break;

case 2:

printf("Case 2 is executed");

break;

default:

printf("Default Case is executed");

break;

return 0;

} Output

Case 2 is executed

12. a) Write the C program to multiply two matrices (two-dimensional array) which will be
entered by a user. The user will enter the order of a matrix and then its elements and
similarly input the second matrix. If the entered orders of two matrices are such that they
can't be multiplied by each other, then an error message is displayed on the screen. (13)

#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] *b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}
Output

Enter the number of rows (between 1 and 100): 2


Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6
b) i) What are the different types of string function? Describe with their purpose.

A String in C programming is a sequence of characters terminated with a null character ‘\0’.


The C String is stored as an array of characters.

C String Length
The length of the string is the number of characters present in the string except for the NULL
character.
#include <stdio.h>

#include <string.h>

int main()

char str[] = "GeeksforGeeks";

int length = strlen(str);

printf("Length of string is : %d", length);

return 0;

Output
Length of string is : 13

strcpy()

It is a standard library function in C and is used to copy one string to another.

#include <stdio.h>

#include <string.h>

int main()

char str1[20] = "Hello";

char str2[20];

strcpy(str2, str1);

printf("str1: %s\n", str1);

printf("str2: %s\n", str2);

return 0;

Output
str1: Hello

str2: Hello

strcat() in C
The strcat function in C is a built-in function that is used to concatenate two strings.

#include <stdio.h>

#include <string.h>

int main() {
char str1[20] = "Hello ";

char str2[20] = "world!";

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

return 0;

Output:

Concatenated string: Hello World!

strtok()

The strtok() function is used to split the string into small tokens based on a set of delimiter
characters.

#include <stdio.h>

#include <string.h>

int main()

char str[] = "Geeks,for.Geeks";

const char delimiters[] = ",.";

char* token = strtok(str, delimiters);

while (token != NULL) {


printf("Token: %s\n", token);

token = strtok(NULL, delimiters);

return 0;

Output
Token: Geeks

Token: for

Token: Geeks

ii) Write the C program to find the number of Vowels, Consonants, Digits and white space
in a string.

#include <stdio.h>

int main() {

char line[150];

int vowels, consonant, digit, space;

vowels = consonant = digit = space = 0;

printf("Enter a line of string: ");

fgets(line, sizeof(line), stdin);

for (int i = 0; line[i] != '\0'; ++i) {

line[i] = tolower(line[i]);

if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||

line[i] == 'o' || line[i] == 'u') {


++vowels;

else if ((line[i] >= 'a' && line[i] <= 'z')) {

++consonant;

else if (line[i] >= '0' && line[i] <= '9') {

++digit;

else if (line[i] == ' ') {

++space;

printf("Vowels: %d", vowels);

printf("\nConsonants: %d", consonant);

printf("\nDigits: %d", digit);

printf("\nWhite spaces: %d", space);

return 0;

Output

Enter a line of string: C++ 20 is the latest version of C++ yet.


Vowels: 9
Consonants: 16
Digits: 2
White spaces: 8

13. a) i) Explain the purpose of a function prototype. And specify the difference between
user defined function and built-in functions.

The C function prototype is a statement that tells the compiler about the function’s name, its
return type, numbers and data types of its parameters.

Syntax
return_type function_name(parameter_list);
// C program to illustrate the function prototye
#include <stdio.h>
float calculateRectangleArea(float length, float width);

int main()
{
float length = 5.0;
float width = 3.0;

float area = calculateRectangleArea(length, width);

printf("The area of the rectangle is: %.2f\n", area);

return 0;
}
float calculateRectangleArea(float length, float width)
{
return length * width;
}

Output
The area of the rectangle is: 15.00

The Function prototype is necessary to serve the following purposes:


1. Function prototype tells the return type of the data that the function will return.
2. Function prototype tells the number of arguments passed to the function.
3. Function prototype tells the data types of each of the passed arguments.
4. Also, the function prototype tells the order in which the arguments are passed to the
function.

User-Defined Functions Library Functions


S.No.

These functions are not predefined in


the Compiler. These functions are predefined in the
1
compiler of C language.

These functions are created by users as These functions are not created by users as
2
per their own requirements. their own.

User-defined functions are not stored in Library Functions are stored in a special
3
library files. library file.

If the user wants to use a particular library


There is no such kind of requirement to function then the user has to add the
add a particular library. particular library of that function in the
4
header file of the program.

Execution of the program begins from Execution of the program does not begin
5
the user-define function. from the library function.

6 Example: sum(), fact(),…etc. Example: printf(), scanf(), sqrt(),…etc.


ii) Write the C program to find the value of sin(x) using the series up to the given accuracy
(without using user defined function) also print sin(x) using library function. (OR)

#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int n, x1;
float acc, term, den, x, sinx=0, sinval;
clrscr();
printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);
x1 = x;
x = x*(3.142/180.0);
sinval = sin(x);
printf("Enter the accuary for the result\n");
scanf("%f", &acc);
term = x;
sinx = term;
n = 1;
do
{
den = 2*n*(2*n+1);
term = -term * x * x / den;
sinx = sinx + term;
n = n + 1;
} while(acc <= fabs(sinval - sinx));
printf("Sum of the sine series = %f\n", sinx);
printf("Using Library function sin(%d) = %f\n", x1,sin(x));
getch();
}
Output
Enter the value of x (in degrees)
30
Enter the accuary for the result
0.000001
Sum of the sine series = 0.500059
Using Library function sin(30) = 0.500059

b) What is difference between pass by value and pass by reference? Write the C coding for
swapping two numbers using pass by reference.

Call By Value Call By Reference

While calling a function, instead of passing the


While calling a function, we pass the
values of variables, we pass the address of
values of variables to it. Such functions
variables(location of variables) to the function
are known as “Call By Values”.
known as “Call By References.

In this method, the value of each variable


In this method, the address of actual variables in
in the calling function is copied into
the calling function is copied into the dummy
corresponding dummy variables of the
variables of the called function.
called function.

With this method, the changes made to the


With this method, using addresses we would
dummy variables in the called function
have access to the actual variables and hence we
have no effect on the values of actual
would be able to manipulate them.
variables in the calling function.

In call-by-values, we cannot alter the In call by reference, we can alter the values of
values of actual variables through function
Call By Value Call By Reference

calls. variables through function calls.

Values of variables are passed by the Pointer variables are necessary to define to store
Simple technique. the address values of variables.

This method is preferred when we have to


This method is preferred when we have to pass a
pass some small values that should not
large amount of data to the function.
change.

Call by value is considered safer as Call by reference is risky as it allows direct


original data is preserved modification in original data

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
}

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

14. a) Define structure in C. Also specify the pointer and structure with example. (13) (OR)

Definition:

The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language.

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
// C Program to demonstrate Structure pointer

#include <stdio.h>

#include <string.h>

struct Student {

int roll_no;

char name[30];

char branch[40];

int batch;

};

struct Student s, *ptr;

int main()

ptr = &s;
printf("Enter the Roll Number of Student\n");

scanf("%d", &ptr->roll_no);

printf("Enter Name of Student\n");

scanf("%s", &ptr->name);

printf("Enter Branch of Student\n");

scanf("%s", &ptr->branch);

printf("Enter batch of Student\n");

scanf("%d", &ptr->batch);

printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);

printf("Name: %s\n", ptr->name);

printf("Branch: %s\n", ptr->branch);

printf("Batch: %d\n", ptr->batch);

return 0;

Output:
Enter the Roll Number of Student

27

Enter Name of Student

Kamlesh_Joshi

Enter Branch of Student

Computer_Science_And_Engineering

Enter batch of Student


2019

Student details are:

Roll No: 27

Name: Kamlesh_Joshi

Branch: Computer_Science_And_Engineering

Batch: 2019

b) i) Write a C program for accessing structure member through pointer using dynamic
memory allocation.

Pointer to structure holds the add of the entire structure.

It is used to create complex data structures such as linked lists, trees, graphs and so on.

The members of the structure can be accessed using a special operator called as an arrow
operator ( -> ).

#include <stdio.h>

#include <string.h>

struct Student {

int roll_no;

char name[30];

char branch[40];

int batch;

};

struct Student s, *ptr;

int main()
{

ptr = &s;

printf("Enter the Roll Number of Student\n");

scanf("%d", &ptr->roll_no);

printf("Enter Name of Student\n");

scanf("%s", &ptr->name);

printf("Enter Branch of Student\n");

scanf("%s", &ptr->branch);

printf("Enter batch of Student\n");

scanf("%d", &ptr->batch);

printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);

printf("Name: %s\n", ptr->name);

printf("Branch: %s\n", ptr->branch);

printf("Batch: %d\n", ptr->batch);

return 0;

Output:
Enter the Roll Number of Student

27

Enter Name of Student

Kamlesh_Joshi

Enter Branch of Student


Computer_Science_And_Engineering

Enter batch of Student

2019

Student details are:

Roll No: 27

Name: Kamlesh_Joshi

Branch: Computer_Science_And_Engineering

Batch: 2019

Declaration

Following is the declaration for pointers to structures in C programming −

struct tagname *ptr;

For example: struct student *s;

ii) Write a short note on singly linked list and specify how the node are created in singly
linked list.

Defition:

A singly linked list is a special type of linked list in which each node has only one link that
points to the next node in the linked list.
class Node{

int data;
Node next;
}

1. Insertion

Insertion in a singly linked list can be performed in the following ways,

 Insertion at the start Insertion of a new node at the start of a singly linked list is carried
out in the following manner.
o Make the new node point to HEAD.
o Make the HEAD point to the new node.
void insertAtStart(Node newNode, Node head){
newNode.data = 10;
newNode.next = head;
head.next = newNode;
}

 Insertion after some Node Insertion of a new node after some node in a singly linked
list is carried out in the following manner,
o Reach the desired node after which the new node is to be inserted.
o Make the new node point to the next element of the current node.
o Make the current node point to the new node. Inserting a new node after some
node is an O(N) operation.
void insertAfterTargetNode(Node newNode, Node head, int target){
newNode.data = 10;
Node temp = head;
while(temp.data != target){
temp = temp.next;
}
newNode.next = temp.next;
temp.next = newNode;
}

 Insertion at the end Insertion of a new node at the end of a singly linked list isperformed
in te followin way,
o Taverse the list from start and reach the last node.
o Make the last node point to the new node.
o Make the new node point to null, marking the end of the list. Inserting a new node
at the end is an O(N) operation.
void insertAtEnd(Node newNode, Node head){
newNode.data = 10;
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = newNode;
newNode.next = null;
}

b) Write the C coding for finding the average of number stored in sequential access file.

#include<stdio.h>
int main()
{
int num1, num2, num3, num4, sum, gsize;
FILE *inFile;
char fname[30];

printf("Enter a file name: ");


gets(fname);
inFile = fopen(fname, "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}

while (fscanf(inFile, "%d %d %d %d %d %d",&gsize, &num1, &num2, &num3, &num4) !=


EOF)
{
printf("Group Size = %d\n num1 = %-12d num2 = %-18d num3 = %-24d num4 = %-30d
%d\n", gsize, num1, num2, num3, num4, sum);

}
fclose(inFile);

}
Output:
Enter an input file name: numbers.dat
Group Size = 2
i = 1 number = 1 Sum = 1
i = 2 number = 2 Sum = 3
Average = 1.50

Group Size = 3
i = 1 number = 1 Sum = 1
i = 2 number = 2 Sum = 3
i = 3 number = 3 Sum = 6
Average = 2.00
Group Size = 4
i = 1 number = 1 Sum = 1
i = 2 number = 2 Sum = 3
i = 3 number = 3 Sum = 6
i = 4 number = 4 Sum = 10
Average = 2.50

This is my input:

212
3123
41234
April May 2019

1.Differentiate between formatted and unformatted input statements. Give one example for
each.

S Formatted I/O functions Unformatted I/O functions


No.

These functions allow us to take input or


These functions do not allow to take input
1 display output in the user’s desired
or display output in user desired format.
format.

These functions support format These functions do not support format


2
specifiers. specifiers.

These are used for storing data more user These functions are not more user-
3
friendly friendly.

Here, we can use only character and string


4 Here, we can use all data types.
data types.
printf(), scanf, sprintf() and sscanf() are getch(), getche(), gets() and puts(), are
5
examples of these functions. some examples of these functions.

2.What is the use of preprocessor directive?

Preprocessor directives, such as #define and #ifdef , are typically used to make source programs
easy to change and easy to compile in different execution environments. Directives in the source
file tell the preprocessor to take specific actions.

3. Define an array.

Array is defined as the collection of the elements in same data type.

data_type array_name [size];

4. Write a C function to compare two strings.

#include <stdio.h>

#include <string.h>

int main()

char* first_str = "Geeks";

char* second_str = "Geeks";

printf("First String: %s\n", first_str);


printf("Second String: %s\n", second_str);

printf("Return value of strcmp(): %d",

strcmp(first_str, second_str));

return 0;

Output
First String: Geeks

Second String: Geeks

Return value of strcmp(): 0

5. What is the need for functions?

In C, functions allow developers

 To break down complex tasks into smaller


 Manageable components,
 Promoting code reusability
 Maintainability

6. What is the output of the following code fragment?

int x=456, "p1, p2;

p1=&x; p2=&p1;

printf ("Value of x is: %d\n", s);

printf("Value of "p1 is: %d\n", "p1);

printf ("Value of "p2 is: %d\n", *p2);

Solution:

The program is Pointer.Pointer is used to hold the address of the variables.Its output is

Value of x is:456
Value of p1 is:456

Value of p2 is:456

6. Compare and contrast a structure with an array.

8. What is the output of the following code fragment?

struct point

int x;

int y;

};
struct point origin, *pp;

void main ()

pp = & origin;

printf (" origin is (%d% d)\n", (*pp).x.pp→ y);

Solution:

Output:

Origin is

9. Why files are needed?

Entire data is lost when the program terminates and storing in a file will preserve your data even
if the program terminates. If you want to enter a large amount of data, normally, it takes a lot of
time to enter them all.

10. What is the use of command line argument?

command-line arguments are used to pass values or files to it.

Command-line arguments are the values given after the name of the program in the
command-line shell of Operating Systems.

Syntax
int main(int argc, char *argv[]) { /* ... */ }

PART B-(5x16 = 80 marks)

11. (a) (i) What is the purpose of a looping statement? Explain in detail the operation of
various looping statements in C with suitable examples. (12)
Looping Statement

Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple
times without repetition of code.

For loop:

For loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to perform
n number of steps together in a single line.

Syntax:
for (initialize expression; Condition;Increment/Decrement)

//

// body of for loop

//

Example:

#include <stdio.h>

int main()

int i = 0;

for (i = 1; i<= 5; i++)

printf( "Hello World\n");

}
return 0;

Output:

Hello World

Hello World

Hello World

Hello World

Hello World

While Loop:

While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of
the test condition.

Syntax:

while (Condition)

// body of the while loop

program

#include <stdio.h>

int main()

int i = 0;
while(i<5)

printf( "Hello World\n");

i++;

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

do-while Loop

The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body.

Syntax

do

// body of do-while loop

} while (Condition);

Program:

#include <stdio.h>
int main()

int i = 2;

do

printf( "Hello World\n");

i++;

} while (i< 1);

return 0;

Output

Hello World

(ii) Write a C program to find the sum of 10 non-negative numbers entered by the user. (4)

#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum = %d", sum);
return 0;
}

Output:

Enter a positive integer: 100


Sum = 5050

(b) What is a storage class? Explain the various storage classes in C along with suitable
example.

Definition:

C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a
particular variable during the runtime of a program

1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope).

2.Extern

extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern
keyword extends the visibility of the C variables and C functions. That’s probably the reason
why it was named extern.

Syntax:

extern data_type variable_name;

Program:

#include <stdio.h>
extern int var;

int main(void)

var = 10;

return 0;

Output:
10

Static:

Static variables have the property of preserving their value even after they are out of their
scope! Hence, a static variable preserves its previous value in its previous scope and is not
initialized again in the new scope.

Syntax:
static data_type var_name = var_value;

#include <stdio.h>

int fun()

static int count = 0;

count++;
return count;

int main()

printf("%d ", fun());

printf("%d ", fun());

return 0;

Output
12

Registers

Registers are faster than memory to access, so the variables which are most frequently used in
a C program can be put in registers using the register keyword. #include <stdio.h>

int main()

int i = 10;

register int* a = &i;

printf("%d", *a);

getchar();

return 0;

}
Output

10

(ii) Write a C program to find the largest among 3 numbers entered by the user. (4)

#include <stdio.h>

int main()
{
int a, b, c;
printf("Enter three numbers: \na: ");
scanf("%d", &a);
printf("b: ");
scanf("%d", &b);
printf("c: ");
scanf("%d", &c);
if (a > b && a > c)
printf("Biggest number is %d", a);
if (b > a && b > c)
printf("Biggest number is %d", b);
if (c > a && c > b)
printf("Biggest number is %d", c);
return 0;
}

Ouput:

Enter three numbers:


a: 10
b: 99
c: 87
Biggest number is 99
(a) Explain binary search procedure. Write a C program to perform binary search and
explain. (16)

Definition:

Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly


dividing the search interval in half.

Procedure:

To understand the working of binary search, consider the following illustration:


Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
First Step: Calculate the mid and compare the mid element with the key. If the key is less
than mid element, move to left and if it is greater than the mid then move search space to the
right.
 Key (i.e., 23) is greater than current mid element (i.e., 16). The search space moves to the
right.

 Key is less than the current mid 56. The search space moves to the left.
Second Step: If the key matches the value of the mid element, the element is found and
stop search.

Program:

#include <stdio.h>
int binary_search(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int index = binary_search(arr, 0, n - 1, target);
if (index == -1) {
printf("Target not found\n");
} else {
printf("Target found at index %d\n", index);
}
return 0;
}
Output:
Target found at index 2

b) Discuss how you can evaluate the mean, median, mode for an array of numbers. Write
the C program to evaluate the mean, median and mode for an array of numbers and
explain. (16)

#include<stdio.h>
int main()
{
int a[2500], n, i, t, j, max=0, c=0, mode=0;
float s=0, mean, median;
printf(“Enter how many data you want to input: “);
scanf(“%d”,&n);
printf(“Enter %d Data:\n”, n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
s+=a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
mean = s/(float)n;
printf(“mean or average is: %.1f\n”,mean);
if(n%2==0)
median=( (a[(n-1)/2] + a[(n-1)/2+1] ) / 2.0);
else
median=( (a[(n-1)/2]) / 2.0);
printf(“median is: %.1f\n”, median);
for(i=0; i<n; i++)
{
t=a[i];
c=0;
for(j=0; j<n; j++) { if(t==a[j]) c++; if(c>max)
{
max=c;
mode=t;
}
}
}
printf(“mode is %d”,mode);
return 0;
}

Output:

13. (a) What is recursion? Explain the procedure to compute sin(x) using recursive
functions. Write the C code for the same. (16)

Recursion:

Recursion is the process of a function calling itself repeatedly till the given condition is
satisfied. A function that calls itself directly or indirectly is called a recursive function and
such kind of function calls are called recursive calls.

The basic syntax structure of the recursive functions is:


type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

Program:
#include <stdio.h>
#include <math.h>
#define PI 3.14159f

int factorial(int n);


float sine(float , int);
int i;

void main(){
float degree;
float radian;
float result;
int n;
printf("Enter the angle in degree: ");
scanf("%f",&degree);
printf("Enter the iteration: ");
scanf("%d",&n);
radian = degree * PI / 180;
result = sine(radian,n);
printf("%d",factorial(n));
printf("\n");
printf("sin%.2f = %.3f",degree,result);
}

int factorial(int n)
{
if(n==0)
return 1;
else if (n==1)
return 1;
else
return (n*factorial(n-1));
}

float sine(float an, int n)


{
if (an==0)
return 0;
else if(n>=0)
if(n%2==1)
return (sine(an,n-2) - pow(an,n)/factorial(n)) * pow(-1,n);
else
return (sine(an,2*n-1) - pow(an,2*n+1)/factorial(2*n+1)) *-1 ;
}

(b) What is pass by reference? Explain swapping of 2 values using pass by reference in 'C.

Pass by reference in C

 In pass by reference, the address of the variable is passed into the function call as the
actual parameter.
 The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed

Pass by reference Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
}

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

14. (a) What is dynamic memory allocation? Explain various C functions that are used for
the same with examples. (16)

Definition:

Dynamic memory allocation is the process of assigning the memory space during the
execution time or the run time.

Types:

1. malloc()
2. calloc()
3. free()
4. realloc()
1.C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size.

Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)

Program:

#include <stdio.h>

#include <stdlib.h>

int main()

int* ptr;

int n, i;

printf("Enter number of elements:");

scanf("%d",&n);

printf("Entered number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");


exit(0);

else {

printf("Memory successfully allocated using malloc.\n");

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

ptr[i] = i + 1;

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

return 0;

Output
Enter number of elements: 5

Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5,

2.C calloc() method

“calloc” or “contiguous allocation” method in C is used to dynamically allocate the


specified number of blocks of memory of the specified type.

Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
#include <stdio.h>

#include <stdlib.h>

int main()

int* ptr;

int n, i;

n = 5;

printf("Enter number of elements: %d\n", n);

ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {

printf("Memory successfully allocated using calloc.\n");

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

ptr[i] = i + 1;
}

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

return 0;

Output

Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

3.C free() method

“free” method in C is used to dynamically de-allocate the memory.


Syntax of free() in C
free(ptr);
#include <stdio.h>

#include <stdlib.h>

int main()

int *ptr, *ptr1;

int n, i;

n = 5;

printf("Enter number of elements: %d\n", n);

ptr = (int*)malloc(n * sizeof(int));

ptr1 = (int*)calloc(n, sizeof(int));

if (ptr == NULL || ptr1 == NULL) {

printf("Memory not allocated.\n");

exit(0);

}
else {

printf("Memory successfully allocated using malloc.\n");

free(ptr);

printf("Malloc Memory successfully freed.\n");

printf("\nMemory successfully allocated using calloc.\n");

free(ptr1);

printf("Calloc Memory successfully freed.\n");

return 0;

Output
Enter number of elements: 5

Memory successfully allocated using malloc.

Malloc Memory successfully freed.

Memory successfully allocated using calloc.

Calloc Memory successfully freed.

4.C realloc() method


“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory.
#include <stdio.h>

#include <stdlib.h>

int main()

int* ptr;

int n, i;

n = 5;

printf("Enter number of elements: %d\n", n);

ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

exit(0);

else {
printf("Memory successfully allocated using calloc.\n");

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

ptr[i] = i + 1;

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

n = 10;

printf("\n\nEnter the new size of the array: %d\n", n);

ptr = (int*)realloc(ptr, n * sizeof(int));

printf("Memory successfully re-allocated using realloc.\n");

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

ptr[i] = i + 1;

printf("The elements of the array are: ");

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

printf("%d, ", ptr[i]);

free(ptr);

}
return 0;

Output
Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

Enter the new size of the array: 10

Memory successfully re-allocated using realloc.

The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

What is a self-referential structures? Explain with suitable examples. (16)

Definition:

Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.
Example:

#include <stdio.h>

struct mystruct{

int a;

struct mystruct *b;

};

int main(){

struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL};

struct mystruct * p1, *p2, *p3;

p1 = &x;

p2 = &y;

p3 = &z;

x.b = p2;

y.b = p3;

printf("Address of x: %d a: %d Address of next: %d\n", p1, x.a, x.b);

printf("Address of y: %d a: %d Address of next: %d\n", p2, y.a, y.b);

printf("Address of z: %d a: %d Address of next: %d\n", p3, z.a, z.b);

return 0;

Output:
Address of x: 659042000 a: 10 Address of next: 659042016
Address of y: 659042016 a: 20 Address of next: 659042032
Address of z: 659042032 a: 30 Address of next: 0
15. (a) Explain in detail various operations that can be done on file giving suitable
examples. (16)

File handing in C is the process in which we create, open, read, write, and close operations on
a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(),
fprintf(), etc. to perform input, output, and many different C file operations in our program.

C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()

File opening modes in C


File opening modes or access modes specify the allowed operations on the file to be opened.

#include <stdio.h>

#include <stdlib.h>

int main()

FILE* fptr;

fptr = fopen("filename.txt", "r");

if (fptr == NULL) {

printf("The file is not opened. The program will ""now exit.");


exit(0);

return 0;

Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already.
#include <stdio.h>

#include <stdlib.h>

int main()

FILE* fptr;

fptr = fopen("file.txt", "w");

if (fptr == NULL) {

printf("The file is not opened. The program will "

"exit now");

exit(0);

else {

printf("The file is created Successfully.");

return 0;

}
Output
The file is created Successfully.

Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations

#include<stdio.h>

int main()

int i, n=2;

char str[50];

FILE *fptr = fopen("sample.txt", "w");

if (fptr == NULL)

printf("Could not open file");

return 0;

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

puts("Enter a name");

scanf("%[^\n]%*c", str);

fprintf(fptr,"%d.%s\n", i, str);

}
fclose(fptr);

return 0;

Input: GeeksforGeeks

GeeksQuiz

Output: sample.txt file now having output as

0. GeeksforGeeks

1. GeeksQuiz

Or

(b) Explain in detail random access in files along with the functions used for the same in C.
Give suitable examples. (16)

Random Access

A random access file in C is a kind of file that enables us to write or read any data in the disk
file without having to read or write each section of data before it.

Functions:

o ftell()

o rewind()

o fseek()

1.ftell()

The file pointer's position is relative to the file's beginning and can be determined using
the ftell() function.
Syntax:

It has the following syntax:

ftell(FILE *fp)

Program:

#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("Jtp.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n") ;
return 0;
}
printf("Position pointer in the beginning : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}

printf("\nSize of file in bytes is : %ld\n",ftell(fp));


fclose(fp);
return 0;
}

Output:

Position pointer in the beginning : 0


Jtp is best.
Size of file in bytes is : 9
2.Rewind()

The file pointer can be moved to the file's beginning using the rewind() function. When a file
needs to be updated, it is useful.

Syntax:

rewind(FILE *fp);

Program:

#include<stdio.h>

int main()
{
FILE *fp;
fp = fopen("Jtp.txt","r");
if(!fp)
{
printf("Error in opening file\n");
return 0;
}
printf("Position of the pointer : %ld\n",ftell(fp));

char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
printf("Position of the pointer : %ld\n",ftell(fp));
rewind(fp);
printf("Position of the pointer : %ld\n",ftell(fp));
fclose(fp);
return 0;
}

1. Output:

2. Position of the pointer : 0


3. Jtp is best.
4. Position of the pointer : 9
5. Position of the pointer : 0

fseek() function:

The fseek() function is used to move the file position to a given location.

Syntax:

int fseek(FILE *fp, long displacement, int origin);

Program:
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("jtp.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n");
return 0;
}
fseek(fp, 3, 0);
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
fclose(fp);
return 0;
}

Output:

Is best.

1.Differentiate break and continue statement in C programming language.

Break Statement Continue Statement

The Break statement is used to exit from the The continue statement is not used to exit
loop constructs. from the loop constructs.

The break statement is usually used with the The continue statement is not used with the
switch statement, and it can also use it within switch statement, but it can be used within
Break Statement Continue Statement

the while loop, do-while loop, or the for-loop. the while loop, do-while loop, or for-loop.

When a break statement is encountered then When the continue statement is encountered
the control is exited from the loop construct then the control automatically passed from
immediately. the beginning of the loop statement.

Syntax: Syntax:
break; continue;

Break statements uses switch and label


It does not use switch and label statements.
statements.

Leftover iterations are not executed after the Leftover iterations can be executed even if
break statement. the continue keyword appears in a loop.

2. List the various types of C operators.

 Arithmetic Operators.
 Decrement and Increment Operators.
 Assignment Operators.
 Logical Operators.
 Conditional Operator.
 Bitwise Operators.
 Special Operators.

3. Name any two library functions used for string handling.

 strlen(): Calculates the length of a string.


 strnlen(): Returns the size of the string provided that the size is lesser than maxlen.
 strcpy(): Copies a string to another string.
 strncpy(): Copies first n characters of a string to another string.

4. Given an array int a [10] = {101, 012, 103, 104, 105, 106, 107, 108, 109, 110). Show the
memory representation and calculate its length.

5. What are the steps in writing a function in a program?

1. Understand the purpose of the function.


2. Define the data that comes into the function from the caller (in the form of parameters)!
3. Define what data variables are needed inside the function to accomplish its goal.
4. Decide on the set of steps that the program will use to accomplish this goal.

6. Is it better to use a macro or a function?

Macros are helpful for small reusable codes. Functions are useful for large reusable codes.
Macros do not return values. Functions can return values.

7. What is register storage in storage class?

This storage class declares register variables that have the same functionality as that of the
auto variables. The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available.

8. Write the syntax for pointers to structure.


A structure pointer is defined as the pointer which points to the address of the memory block
that stores a structure known as the structure pointer.

syntax: struct myStruct *ptr;

9. What are two main ways a file can be organized?

 sequential,
 random

10. List the File Operations in C paradigm.

1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()

PART-B

11. a) i) Describe the structure of a C program with an example.

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program.

Sections of the C Program

There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:

1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation

This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:

// description, name of the program, programmer name, date, time etc.

2. Preprocessor Section

All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>

#include<math.h>

3. Definition

Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.

Example:
#define long longll
4. Global Declaration

The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.

Example:
int num = 18;

5. Main() Function

Every C program must have a main function. The main() function of the program is written in
this section. Operations like declaration and execution are performed inside the curly braces of
the main program. The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int main() tells the
compiler that the program will return an integer value.

Example:
void main()

or
int main()

6. Sub Programs

User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.

Example:
int sum(int x, int y)

return x+y;

}
Example:
#include<stdio.h>

#include<conio.h>

Void main()

Int a,b,sum;

Clrscr();

Printf(“Enter the first value:”);

Scanf(“%d”, &a);

Printf(“Enter the second value:”);

Scanf(“%d”, &b);

Sum=a+b;

Printf(“The sum of given two numbers %d”,sum);

getch();

ii) Explain the various operators used in C.

C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
7. Arithmetic Operators
8. Relational Operators
9. Logical Operators
10. Bitwise Operators
11. Assignment Operators
12. Other Operators
S. No. Symbol Operator Syntax

1 + Plus a+b

2 – Minus a–b

3 * Multiply a*b

4 / Divide a/b

5 % Modulus a%b

Used to specify
+ Unary Plus the positive
6 values.

Flips the sign of


– Unary Minus
7 the value.

Increases the
++ Increment value of the
8 operand by 1.

Decreases the
— Decrement value of the
9 operand by 1.

C program

#include <stdio.h>

int main()
{

int a = 25, b = 5;

printf("a + b = %d\n", a + b);

printf("a - b = %d\n", a - b);

printf("a * b = %d\n", a * b);

printf("a / b = %d\n", a / b);

printf("a % b = %d\n", a % b);

printf("+a = %d\n", +a);

printf("-a = %d\n", -a);

printf("a++ = %d\n", a++);

printf("a-- = %d\n", a--);

return 0;

Output
a + b = 30

a - b = 20

a * b = 125

a/b=5

a%b=0

+a = 25

-a = -25

a++ = 25

a-- = 26
Relational Operators in C

S. No. Symbol Operator Syntax

1 < Less than a<b

2 > Greater than a>b

Less than or
<= a <= b
3 equal to

Greater than or
>= a >= b
4 equal to

5 == Equal to a == b

6 != Not equal to a != b

C program

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a < b : %d\n", a < b);

printf("a > b : %d\n", a > b);

printf("a <= b: %d\n", a <= b);

printf("a >= b: %d\n", a >= b);

printf("a == b: %d\n", a == b);

printf("a != b : %d\n", a != b);


return 0;

Output
a<b :0

a>b :1

a <= b: 0

a >= b: 1

a == b: 0

a != b : 1

Logical Operator in C

S. No. Symbol Operator Syntax

1 && Logical AND a && b

2 || Logical OR a || b

3 ! Logical NOT !a

C program

#include <stdio.h>

int main()

int a = 25, b = 5;

printf("a && b : %d\n", a && b);


printf("a || b : %d\n", a || b);

printf("!a: %d\n", !a);

return 0;

Output
a && b : 1

a || b : 1

!a: 0

4. Bitwise Operators in C

S. No. Symbol Operator Syntax

1 & Bitwise AND a&b

2 | Bitwise OR a|b

3 ^ Bitwise XOR a^b

Bitwise First
~ ~a
4 Complement

5 << Bitwise Leftshift a << b

Bitwise
>> a >> b
6 Rightshilft

C program

#include <stdio.h>
int main()

int a = 25, b = 5;

printf("a & b: %d\n", a & b);

printf("a | b: %d\n", a | b);

printf("a ^ b: %d\n", a ^ b);

printf("~a: %d\n", ~a);

printf("a >> b: %d\n", a >> b);

printf("a << b: %d\n", a << b);

return 0;

} Output

a & b: 1

a | b: 29

a ^ b: 28

~a: -26

a >> b: 0

a << b: 800

5. Assignment Operators in C

S. No. Symbol Operator Syntax

Simple
= a=b
1 Assignment
S. No. Symbol Operator Syntax

2 += Plus and assign a += b

3 -= Minus and assign a -= b

Multiply and
*= a *= b
4 assign

5 /= Divide and assign a /= b

Modulus and
%= a %= b
6 assign

7 &= AND and assign a &= b

8 |= OR and assign a |= b

9 ^= XOR and assign a ^= b

Rightshift and
>>= a >>= b
10 assign

Leftshift and
<<= a <<=
11 assign

// C program to illustrate the arithmatic operators

#include <stdio.h>

int main()

{
int a = 25, b = 5;

printf("a = b: %d\n", a = b);

printf("a += b: %d\n", a += b);

printf("a -= b: %d\n", a -= b);

printf("a *= b: %d\n", a *= b);

printf("a /= b: %d\n", a /= b);

printf("a %= b: %d\n", a %= b);

printf("a &= b: %d\n", a &= b);

printf("a |= b: %d\n)", a |= b);

printf("a >>= b: %d\n", a >> b);

printf("a <<= b: %d\n", a << b);

return 0;

} Output

a = b: 5

a += b: 10

a -= b: 5

a *= b: 25

a /= b: 5

a %= b: 0

a &= b: 0

a |= b: 5

)a >>= b: 0

a <<= b: 160
b) Explain about the various decision making and branching statements in C programming

Branching Statement(or) Looping Statement:

Looping Statement

Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple
times without repetition of code.

For loop:

For loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to perform
n number of steps together in a single line.

Syntax:
for (initialize expression; Condition;Increment/Decrement)

//

// body of for loop

//

Example:

#include <stdio.h>

int main()

int i = 0;

for (i = 1; i<= 5; i++)


{

printf( "Hello World\n");

return 0;

Output:

Hello World

Hello World

Hello World

Hello World

Hello World

While Loop:

While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of
the test condition.

Syntax:

while (Condition)

// body of the while loop

program

#include <stdio.h>
int main()

int i = 0;

while(i<5)

printf( "Hello World\n");

i++;

return 0;

Output

Hello World

Hello World

Hello World

Hello World

Hello World

do-while Loop

The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body.

Syntax

do

// body of do-while loop


} while (Condition);

Program:

#include <stdio.h>

int main()

int i = 2;

do

printf( "Hello World\n");

i++;

} while (i< 1);

return 0;

Output

Hello World

Conditional Statement:

Decision Making:

They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not.
if in C

The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not

Syntax of if Statement
if(condition)
{
// Statements
}

C program

#include <stdio.h>

int main()

int i = 10;
if (i < 15)

printf("15 is greater than i");

Output
I am Not in if

if-else in C

The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t.

Syntax of if else in C
if (condition)
{
// condition is true
}
else
{
// condition is false
}

C program

#include <stdio.h>

int main()

{
int i = 20;

if (i < 15)

printf("i is smaller than 15");

else

printf("i is greater than 15");

return 0;

Output
i is greater than 15

Nested if-else in C
A nested if in C is an if statement that is the target of another if statement.

Syntax of Nested if-else


if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

C program

#include <stdio.h>

int main()

int i = 10;

if (i == 10)

if (i < 15)

printf("i is smaller than 15\n");

if (i < 12)

printf("i is smaller than 12 too\n");

else

printf("i is greater than 15");

return 0;

Output
i is smaller than 15
i is smaller than 12 too

switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be used to execute
the conditional code based on the value of the variable specified in the switch statement.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
C Program

#include <stdio.h>

int main()

int var = 2;

switch (var) {

case 1:

printf("Case 1 is executed");

break;
case 2:

printf("Case 2 is executed");

break;

default:

printf("Default Case is executed");

break;

return 0;

} Output

Case 2 is executed

12. a) i) Describe the following with respect to arrays:- need of an array, declaration of
array and accessing an array element. (8)

Array:

Array is defined as the collection of elements in same data type.

Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.
Syntax of 1D Array in C
array_name [size];

// C Program to illustrate the use of 1D array

#include <stdio.h>

int main()

int arr[5];

for (int i = 0; i < 5; i++) {

arr[i] = i * i - 2 * i + 1;
}

printf("Elements of Array: ");

for (int i = 0; i < 5; i++) {

printf("%d ", arr[i]);

return 0;

Output
Elements of Array: 1 0 1 4 9

Two-Dimensional Array in C

A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They
can be visualized in the form of rows and columns organized in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
 size1: Size of the first dimension.
 size2: Size of the second dimension.
Example of 2D Array in C

#include <stdio.h>

int main()

int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 3; j++) {

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

printf("\n");

return 0;
}
Output
2D Array:

10 20 30

40 50 60

Need of an Array:

 Efficient access to elements


 Memory efficiency
 Versatility
 Easy to implement
 Compatibility with hardware

ii) Explain in algorithm and write a C program to re-order a one-dimensional array of


numbers in descending order.

#include <stdio.h>

int main()

int a[5] = { 45, 22, 100, 66, 37 };

int n = 5, i, j, t = 0;

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

for (j = i + 1; j < n; j++) {

if (a[i] < a[j]) {

t = a[i];

a[i] = a[j];

a[j] = t;

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

printf("%d ", a[i]);

return 0;

}
Output
100 66 45 37 22

b) Write a C program to find the transpose of a matrix.

#include <stdio.h>

void transpose(int A[][N], int B[][N])

int i, j;

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

for (j = 0; j < N; j++)

B[i][j] = A[j][i];

int main()

int A[N][N] = { { 1, 1, 1, 1 },

{ 2, 2, 2, 2 },

{ 3, 3, 3, 3 },

{ 4, 4, 4, 4 } };

int B[N][N], i, j;

transpose(A, B);

printf("Result matrix is \n");


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

for (j = 0; j < N; j++)

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

printf("\n");

return 0;

Output
Result matrix is

1234

1234

1234

1234

13. a) i) Discuss on recursive function. Write a C program to find factorial of n using

recursion.

#include <stdio.h>

unsigned int factorial(unsigned int n)

if (n == 0)

return 1;

return n * factorial(n - 1);

}
int main()

int num = 5;

printf("Factorial of %d is %d", num, factorial(num));

return 0;

Output
Factorial of 5 is 120

ii) Write a C program to reverse a string using recursion. (OR)

# include <stdio.h>

void reverse(char *str)

if (*str)

reverse(str + 1);

printf("%c", *str);

int main()

char a[] = "Mano";


reverse(a);

return 0;

Output:

oanM

b) Explain the concept of pass by value and pass by reference with suitable example in C
programming language.

Pass by value:

Pass by value is termed as the values which are sent as arguments in C programming language.

#include<stdio.h>
void main(){
void swap(int,int);
int a,b;
printf("enter 2 numbers");
scanf("%d%d",&a,&b);
printf("Before swapping a=%d b=%d",a,b);
swap(a,b);
printf("after swapping a=%d, b=%d",a,b);
}
void swap(int a,int b){
int t; // all these statements is equivalent to
t=a; // a = (a+b) – (b =a);
a=b; // or
b=t; // a = a + b;
} // b = a – b;
//a = a – b;

Output
When the above program is executed, it produces the following result −

enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=10 b=20

Pass By Reference in C
In this method, the address of an argument is passed to the function instead of the argument
itself during the function call.

Syntax

The code will look like this in the pass-by-reference method:

// function definion
return_type functionName (arg_type *arg1, arg_type *arg1, ......) {
// function body
}

.
.
// function call
functionName (&arg1, &arg2, ....);
// C program to swap two numbers

#include <stdio.h>

// function definition with relevant pointers to recieve the

// parameters

void swap(int* a, int* b)

{
// accessing arguments like pointers

int temp = *a;

*a = *b;

*b = temp;

// driver code

int main(void)

int n1 = 5;

int n2 = 10;

// value before swapping

printf(" Before swapping : n1 is %d and n2 is %d\n", n1,

n2);

// calling the function by passing the address of the

// arguments

swap(&n1, &n2);

// value after swapping

printf(" After swapping : n1 is %d and n2 is %d\n", n1,

n2);
return 0;

Output
Before swapping : n1 is 5 and n2 is 10

After swapping : n1 is 10 and n2 is 5

14. a) Write a C program using structures to prepare the students mark statement. The
number of records is created based on the user input.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Student {

char* name;

int roll_number;

int age;

double total_marks;

};

int main()

int i = 0, n = 5;

struct Student student[n];

student[0].roll_number = 1;
student[0].name = "xxx";

student[0].age = 12;

student[0].total_marks = 78.50;

student[1].roll_number = 5;

student[1].name = "yyy";

student[1].age = 10;

student[1].total_marks = 56.84;

student[2].roll_number = 2;

student[2].name = "zzz";

student[2].age = 11;

student[2].total_marks = 87.94;

student[3].roll_number = 4;

student[3].name = "aaa";

student[3].age = 12;

student[3].total_marks = 89.78;

student[4].roll_number = 3;

student[4].name = "bbb";

student[4].age = 13;

student[4].total_marks = 78.55;
// Print the Students information

printf("Student Records:\n\n");

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

printf("\tName = %s\n", student[i].name);

printf("\tRoll Number = %d\n", student[i].roll_number);

printf("\tAge = %d\n", student[i].age);

printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks);

return 0;

Output:
Student Records:

Name = xxx

Roll Number = 1

Age = 12

Total Marks = 78.50

Name = yyy

Roll Number = 5
Age = 10

Total Marks = 56.84

Name = zzz

Roll Number = 2

Age = 11

Total Marks = 87.94

Name =aaa

Roll Number = 4

Age = 12

Total Marks = 89.78

Name = bbb

Roll Number = 3

Age = 13

Total Marks = 78.55

b) Write a C program using structures to prepare the employee pay roll of a company. The
number of records is created based on the user input.

#include <stdio.h>
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
struct employee emp;
printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);
printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}

Output

Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000

15. a) Explain in detail about command line arguments with an example of generating
Fibonacci series of a number in C programming language. (OR)
Command-line arguments in C are typically responsible for passing arguments to a C program
when it is executed from the terminal or the command line

It consists of two important parameters, namely,

 argc and
 argv

#include<stdio.h>
#include<stdlib.h>

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


{

int n, first = 0, second = 1, next, c;

n = atoi (argv[1]);

printf ("These are %d values in Fibonacci series are by atnyla:-\n",n);

for (c = 0; c < n; c++)


{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}

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


}

return 0;
}
Output:
10

These are 10 values in Fibonacci series are by atnyla:-


0
1
1
2
3
5
8
13
21
34

b) i) Write short notes on File functions in C,

1. fseek()

fseek() is used to move the file pointer associated with a given file to a specific position.

Syntax of fseek()

The fseek() syntax is:

int fseek(FILE *pointer, long int offset, int position);

#include <stdio.h>
int main()

FILE* fp;

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

fseek(fp, 0, SEEK_END);

printf("%ld", ftell(fp));

return 0;

"Someone over there is calling you.

we are going for work.

take care of yourself."

Output
81

2. ftell()

ftell() in C is used to find out the position of the file pointer in the file with respect to starting
of the file.

Syntax

The syntax of ftell() is:

long ftell(FILE *stream);

#include <stdio.h>

int main()
{

FILE* fp = fopen("g4g.txt", "r");

char string[20];

fscanf(fp, "%s", string);

printf("%ld", ftell(fp));

return 0;

g4g.txt
Someone over there is calling you. We are going for work. Take care of yourself.

Output
7

3. rewind()

rewind() is used to move the file pointer to the beginning of the file stream.

Syntax
void rewind(FILE *stream);

Program:

#include<stdio.h>

int main()

FILE* fp = fopen("test.txt", "r");

if (fp == NULL) {
}

rewind(fp);

return 0;

4. feof()

The feof() function is used to check whether the file pointer to a stream is pointing to the end
of the file or not.

Syntax of feof()

int feof(FILE* stream);

#include <stdio.h>

int main()

FILE* fp = fopen("test.txt", "r");

int ch = getc(fp);

while (ch != EOF) {

putchar(ch);

ch = getc(fp);

if (feof(fp))

printf("\n End of file reached.");


else

printf("\n Something went wrong.");

fclose(fp);

getchar();

return 0;

Output
End of file reached.

5. fscanf().

This function is used to read the formatted input from the given stream in the C language.
Syntax:
int fscanf(FILE *ptr, const char *format, ...)

#include <stdio.h>

int main()

FILE* ptr = fopen("abc.txt", "r");

if (ptr == NULL) {

printf("no such file.");

return 0;

char buf[100];
while (fscanf(ptr, "%*s %*s %s ", buf) == 1)

printf("%s\n", buf);

return 0;

Output
CITY
hyderabad
delhi
bangalore

You might also like