University Question Bank With Answer
University Question Bank With Answer
Nov-dec 2022
Arithmetic Operators.
Decrement and Increment Operators.
Assignment Operators.
Logical Operators.
Conditional Operator.
Bitwise Operators.
Special Operators.
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.
#include<stdio.h>
void main()
float arr[5]={10.0,20.4,30.6,40.9,50.3};
Printf(“%f”,arr[]);
}
Output
These operations include incrementing, decrementing, adding integers, subtracting integers, and
comparing pointers.
Macro Function
Speed of Execution using Macro is Faster Speed of Execution using Function is Slower
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;
....
....
};
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.
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.
#include <stdio.h>
int main()
FILE* fp;
fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
printf("%ld", ftell(fp));
return 0;
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
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:
Program:
#include <stdio.h>
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()
count++;
return count;
int main()
{
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;
printf("%d", *a);
getchar();
return 0;
Output
10
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)
//
//
Example:
#include <stdio.h>
int main()
int i = 0;
}
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)
program
#include <stdio.h>
int main()
int i = 0;
while(i<5)
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
} while (Condition);
Program:
#include <stdio.h>
int main()
int i = 2;
do
i++;
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]);
}
}
Output:
(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() {
scanf("%d", &r);
scanf("%d", &c);
scanf("%d", &a[i][j]);
scanf("%d", &b[i][j]);
}
printf("\nSum of two matrices: \n");
if (j == c - 1) {
printf("\n\n");
return 0;
Ouput:
10 8 6
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");
}
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
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.
#include <stdio.h>
int main()
return 0;
Output
Value of var1: 10 Address: 0x7fff1ac82484
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()
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.
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;
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;
return 0;
Output:
Student Records:
Name = Geeks1
Roll Number = 1
Age = 12
Name = Geeks5
Roll Number = 5
Age = 10
Name = Geeks2
Roll Number = 2
Age = 11
Roll Number = 4
Age = 12
Name = Geeks3
Roll Number = 3
Age = 13
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:
(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;
scanf("%d", &num);
if(fptr == NULL)
{
printf("Error!");
exit(1);
scanf("%s", name);
scanf("%d", &marks);
fclose(fptr);
Output:
For Student 1
Enter Marks: 98
For Student 2
Enter Marks: 88
For Student 3
(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;
if (infile == NULL) {
exit(1);
read_struct.lname, read_struct.id);
fclose(infile);
return 0;
Output
Name: Rohan Sharma
ID: 1
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
Properties:
#include <stdio.h>
if (argc == 1)
if (argc >= 2) {
"Arguments Passed----");
return 0;
Output
Program Name Is: ./a.out
(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]);
}
return 0;
}
Output
10 8 6
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
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:
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.
#include <stdio.h>
#include <string.h>
int main()
{
char* first_str = "Geeks";
strcmp(first_str, second_str));
return 0;
Output
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:
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;
....
....
};
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
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.
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
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.
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;
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
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;
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
2 || Logical OR a || b
3 ! Logical NOT !a
C program
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
}
Output
a && b : 1
a || b : 1
!a: 0
4. Bitwise Operators in C
2 | Bitwise OR a|b
Bitwise First
~ ~a
4 Complement
Bitwise
>> a >> b
6 Rightshilft
C program
#include <stdio.h>
int main()
int a = 25, b = 5;
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
Simple
= a=b
1 Assignment
4 *= Multiply and a *= b
S. No. Symbol Operator Syntax
assign
Modulus and
%= a %= b
6 assign
8 |= OR and assign a |= b
Rightshift and
>>= a >>= b
10 assign
Leftshift and
<<= a <<=
11 assign
#include <stdio.h>
int main()
int a = 25, b = 5;
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
int main()
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + r;
num /= 10;
if (original_number == reversed) {
else {
return 0;
Output:
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)
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)
else
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)
if (i < 12)
return 0;
Output
i is smaller than 15
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:
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);
return 0;
}
Output
10 8 6
b) i) What are the different types of string function? Describe with their purpose.
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()
return 0;
Output
Length of string is : 13
strcpy()
#include <stdio.h>
#include <string.h>
int main()
char str2[20];
strcpy(str2, str1);
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 ";
strcat(str1, str2);
return 0;
Output:
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()
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];
line[i] = tolower(line[i]);
++consonant;
++digit;
++space;
return 0;
Output
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;
return 0;
}
float calculateRectangleArea(float length, float width)
{
return length * width;
}
Output
The area of the rectangle is: 15.00
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.
Execution of the program begins from Execution of the program does not begin
5
the user-define function. from the library function.
#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.
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
Values of variables are passed by the Pointer variables are necessary to define to store
Simple technique. the address values of 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) 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;
};
int main()
ptr = &s;
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
scanf("%s", &ptr->name);
scanf("%s", &ptr->branch);
scanf("%d", &ptr->batch);
return 0;
Output:
Enter the Roll Number of Student
27
Kamlesh_Joshi
Computer_Science_And_Engineering
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.
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;
};
int main()
{
ptr = &s;
scanf("%d", &ptr->roll_no);
scanf("%s", &ptr->name);
scanf("%s", &ptr->branch);
scanf("%d", &ptr->batch);
return 0;
Output:
Enter the Roll Number of Student
27
Kamlesh_Joshi
2019
Roll No: 27
Name: Kamlesh_Joshi
Branch: Computer_Science_And_Engineering
Batch: 2019
Declaration
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 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];
}
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.
These are used for storing data more user These functions are not more user-
3
friendly friendly.
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.
#include <stdio.h>
#include <string.h>
int main()
strcmp(first_str, second_str));
return 0;
Output
First String: Geeks
p1=&x; p2=&p1;
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
struct point
int x;
int y;
};
struct point origin, *pp;
void main ()
pp = & origin;
Solution:
Output:
Origin is
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.
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[]) { /* ... */ }
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)
//
//
Example:
#include <stdio.h>
int main()
int i = 0;
}
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)
program
#include <stdio.h>
int main()
int i = 0;
while(i<5)
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
} while (Condition);
Program:
#include <stdio.h>
int main()
int i = 2;
do
i++;
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:
(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:
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()
count++;
return count;
int main()
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;
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:
Definition:
Procedure:
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.
Program:
#include <stdio.h>
#include <math.h>
#define PI 3.14159f
void main(){
float degree;
float radian;
float result;
int n;
printf("Enter the angle in degree: ");
scanf("%f",°ree);
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));
}
(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
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;
scanf("%d",&n);
if (ptr == NULL) {
else {
ptr[i] = i + 1;
return 0;
Output
Enter number of elements: 5
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;
if (ptr == NULL) {
exit(0);
else {
ptr[i] = i + 1;
}
return 0;
Output
#include <stdlib.h>
int main()
int n, i;
n = 5;
exit(0);
}
else {
free(ptr);
free(ptr1);
return 0;
Output
Enter number of elements: 5
#include <stdlib.h>
int main()
int* ptr;
int n, i;
n = 5;
if (ptr == NULL) {
exit(0);
else {
printf("Memory successfully allocated using calloc.\n");
ptr[i] = i + 1;
n = 10;
ptr[i] = i + 1;
free(ptr);
}
return 0;
Output
Enter number of elements: 5
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;
};
int main(){
p1 = &x;
p2 = &y;
p3 = &z;
x.b = p2;
y.b = p3;
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()
#include <stdio.h>
#include <stdlib.h>
int main()
FILE* fptr;
if (fptr == NULL) {
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;
if (fptr == NULL) {
"exit now");
exit(0);
else {
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];
if (fptr == NULL)
return 0;
puts("Enter a name");
scanf("%[^\n]%*c", str);
fprintf(fptr,"%d.%s\n", i, str);
}
fclose(fptr);
return 0;
Input: GeeksforGeeks
GeeksQuiz
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:
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);
}
Output:
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:
fseek() function:
The fseek() function is used to move the file position to a given location.
Syntax:
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.
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;
Leftover iterations are not executed after the Leftover iterations can be executed even if
break statement. the continue keyword appears in a loop.
Arithmetic Operators.
Decrement and Increment Operators.
Assignment Operators.
Logical Operators.
Conditional Operator.
Bitwise Operators.
Special Operators.
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.
Macros are helpful for small reusable codes. Functions are useful for large reusable codes.
Macros do not return values. Functions can return values.
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.
sequential,
random
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
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.
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:
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();
Scanf(“%d”, &a);
Scanf(“%d”, &b);
Sum=a+b;
getch();
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.
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;
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
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;
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Logical Operator in C
2 || Logical OR a || b
3 ! Logical NOT !a
C program
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
Output
a && b : 1
a || b : 1
!a: 0
4. Bitwise Operators in C
2 | Bitwise OR a|b
Bitwise First
~ ~a
4 Complement
Bitwise
>> a >> b
6 Rightshilft
C program
#include <stdio.h>
int main()
int a = 25, b = 5;
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
Simple
= a=b
1 Assignment
S. No. Symbol Operator Syntax
Multiply and
*= a *= b
4 assign
Modulus and
%= a %= b
6 assign
8 |= OR and assign a |= b
Rightshift and
>>= a >>= b
10 assign
Leftshift and
<<= a <<=
11 assign
#include <stdio.h>
int main()
{
int a = 25, b = 5;
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
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)
//
//
Example:
#include <stdio.h>
int main()
int i = 0;
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)
program
#include <stdio.h>
int main()
int i = 0;
while(i<5)
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
Program:
#include <stdio.h>
int main()
int i = 2;
do
i++;
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)
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)
else
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.
C program
#include <stdio.h>
int main()
int i = 10;
if (i == 10)
if (i < 15)
if (i < 12)
else
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:
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:
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];
#include <stdio.h>
int main()
int arr[5];
arr[i] = i * i - 2 * i + 1;
}
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()
printf("2D Array:\n");
printf("%d ",arr[i][j]);
printf("\n");
return 0;
}
Output
2D Array:
10 20 30
40 50 60
Need of an Array:
#include <stdio.h>
int main()
int n = 5, i, j, t = 0;
t = a[i];
a[i] = a[j];
a[j] = t;
return 0;
}
Output
100 66 45 37 22
#include <stdio.h>
int i, 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("\n");
return 0;
Output
Result matrix is
1234
1234
1234
1234
recursion.
#include <stdio.h>
if (n == 0)
return 1;
}
int main()
int num = 5;
return 0;
Output
Factorial of 5 is 120
# include <stdio.h>
if (*str)
reverse(str + 1);
printf("%c", *str);
int main()
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
// 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>
// parameters
{
// accessing arguments like pointers
*a = *b;
*b = temp;
// driver code
int main(void)
int n1 = 5;
int n2 = 10;
n2);
// arguments
swap(&n1, &n2);
n2);
return 0;
Output
Before swapping : n1 is 5 and n2 is 10
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;
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");
return 0;
Output:
Student Records:
Name = xxx
Roll Number = 1
Age = 12
Name = yyy
Roll Number = 5
Age = 10
Name = zzz
Roll Number = 2
Age = 11
Name =aaa
Roll Number = 4
Age = 12
Name = bbb
Roll Number = 3
Age = 13
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
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
argc and
argv
#include<stdio.h>
#include<stdlib.h>
n = atoi (argv[1]);
return 0;
}
Output:
10
1. fseek()
fseek() is used to move the file pointer associated with a given file to a specific position.
Syntax of fseek()
#include <stdio.h>
int main()
FILE* fp;
fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
printf("%ld", ftell(fp));
return 0;
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
#include <stdio.h>
int main()
{
char string[20];
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()
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()
#include <stdio.h>
int main()
int ch = getc(fp);
putchar(ch);
ch = getc(fp);
if (feof(fp))
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()
if (ptr == NULL) {
return 0;
char buf[100];
while (fscanf(ptr, "%*s %*s %s ", buf) == 1)
printf("%s\n", buf);
return 0;
Output
CITY
hyderabad
delhi
bangalore