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

C Program All Model Question Solved

The document discusses the structure of a C program, detailing its six sections: Documentation, Link, Definition, Global Declaration, main() Function, and Subprogram Sections. It also explains different types of if statements (if, if-else, else-if, nested if-else) and compares if statements with switch statements. Additionally, it covers structures in C, algorithms, type conversion, and increment/decrement operators with examples.

Uploaded by

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

C Program All Model Question Solved

The document discusses the structure of a C program, detailing its six sections: Documentation, Link, Definition, Global Declaration, main() Function, and Subprogram Sections. It also explains different types of if statements (if, if-else, else-if, nested if-else) and compares if statements with switch statements. Additionally, it covers structures in C, algorithms, type conversion, and increment/decrement operators with examples.

Uploaded by

Scribd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Discuss structure of a C Program with suitable example.

2074
Solution

Any C program is consists of 6 sections. Below you will find brief explanation of each of them.

Basic Structure of C Program

Documentation Section

Link Section

Definition Section

Global Declaration Section

main() Function section

Declaration Part 1

Execution Part

Subprogram Sections

Function 1

Function 2

Function n

1. Documentation Section

Here we can see two types of comments in the above program. Comments are the explanation or
description of source code that does not a ect your program logic in any way. Comments are neglected
by compilers or interpreters.
// This is single line comments

/*

* This

* is

* the multiple line comment.

*/

2. Link Section

This part of the code is used to declare all the header files that will be used in the program. This leads to
the compiler being told to link the header files to the system libraries.

#include<stdio.h>

3. Definition Section

In this section, we define di erent constants. The keyword define is used in this part.

#define PI 3.14

4. Global Declaration Section

This part of the code is the part where the global variables are declared. All the global variable used are
declared in this part. The user-defined functions are also declared in this part of the code.

float area(float r);

int a=7;

5. Main Function Section

Every C-programs needs to have the main function. Each main function contains 2 parts. A declaration
part and an Execution part. The declaration part is the part where all the variables are declared. The
execution part begins with the curly brackets and ends with the curly close bracket. Both the declaration
and execution part are inside the curly braces.

int main()

//statements

6. Sub Program Section

All the user-defined functions are defined in this section of the program.

float area(float r)
{

return PI * r * r;

#Sample Program

The C program here will find the area of a circle using a user-defined function and a global variable pi
holding the value of pi

//a program to calculate area of circle

/** link section */

#include<stdio.h>

/** defination section */

#define PI 3.142

/** Global Declaration */

float area(float r);

/** main function */

int main(){

float r;

printf("Enter the radius: ");

scanf("%f", &r);

printf("Area of Circle = %f ", area(r));

return 0;

/** sub program */

float area(float r) {

return PI * r * r;

2. Discuss di erent types of if statements with example of each. Di erentiate if


statement with switch statement.
Solution

There are 4 di erent types of if statements in C programming.

 if statement

 if….else statement

 else…..if statement

 nested if….else statement

1. IF Statement

If the statement is a powerful decision-making statement and is used to control the flow of execution of
statements. It basically a two-way decision statement and is used together with an expression, i.e. test
condition. The if statement evaluates the expression first and then, if the value the expression is true, it
executes the statement within the block. Otherwise, it skips the statements within its block and
continues from the first statement outside the if block. It takes the form,

Syntax:

if(condition)

statement-block;

statement-x;

Example

#include <stdio.h>

int main(){

int num = 10;

if(num % 2 == 0){

printf("Number is Even\n");

return 0;

The output of above program is

Number is Even
2. IF…ELSE Statement

The if…else statement is an extension of the simple ifstatement. It is used when there are two possible
actions – one when a condition is true, and the other when it is false. The general form is

if(condition)

true_block statement;

else

false_block statement;

statement-x;

Example:

#include <stdio.h>

int main(){

int num = 10;

if(num % 2 == 0)

printf("Number is Even\n");

else

printf("Number is Odd\n");

return 0;

The output of above program is

Number is Even

3. ELSE…IF Statement
The else if the statement is used when there are more than two possible actions depending upon the
outcome of the test. When an action is taken, no others can be executed or taken. In such a situation,
the if…else if…else if….else statement is used. This structure takes the form,

if(condition-1)

statement-1;

else if(condition-2)

statement-2;

else if(condition-3)

statement-3;

else

default-statement;

Example:

#include <stdio.h>

int main(){

int num = 15;

if(num % 2 == 0)

printf("Number is Even\n");

else if(num % 3 == 0)

{
printf("Number is Odd\n");

else

printf("Invalid Number\n");

return 0;

The output of above program is

Number is Odd

4. Nested IF…ELSE Statement

Nested IF…ELSE statement means there is an IF condition inside the if condition. The syntax looks like
this.

if(condition)

if(condition-2)

statement-1;

else

statement-2;

else

statement-3;

Let’s look at examples to make clear concepts on nested if…else condition.


#include < stdio.h>

int main(){

int num = 15;

if(num % 2 == 0)

if(num > 5 == 0)

printf("Number is greater than 5 and Even\n");

}else{

printf("Number is lessa than 5 andEven\n");

else

printf("Number is Odd\n");

return 0;

The output of above program is

Number is greater than 5 and Even

Source: [Link]

The Di erence between if and switch statement

Basis If-else switch

Depending on the condition in


The user will decide which statement is to be
Definition the ‘if’ statement, ‘if’ and ‘else’
executed.
blocks are executed.
It contains either logical or It contains a single expression which can be
Expression
equality expression. either a character or integer variable.

It evaluates all types of data,


Evaluation such as integer, floating-point, It evaluates either an integer, or character.
character or Boolean.

First, the condition is checked. If


It executes one case after another till the
Sequence of the condition is true then ‘if’
break keyword is not found, or the default
execution block is executed otherwise
statement is executed.
‘else’ block

If the condition is not true, then If the value does not match with any case,
Default
by default, else block will be then by default, default statement is
execution
executed. executed.

Cases in a switch statement are easy to


Editing is not easy in the ‘if-else’ maintain and modify. Therefore, we can say
Editing
statement. that the removal or editing of any case will
not interrupt the execution of other cases.

If there are multiple choices If we have multiple choices then the switch
implemented through ‘if-else’, statement is the best option as the speed of
Speed
then the speed of the execution the execution will be much higher than ‘if-
will be slow. else’.

3. What is structure? How is it di erent from array? Create a structure student having
data members name, roll-number and percentage. Complete the program to display
the name of student having percentage greater than or equal to 60.

Solution
A structure is a collection of variables under a single name. These variables can be of di erent types, and
each has a name that is used to select it from the structure. The variables are called members of the
structure. A structure is a convenient way of grouping general pieces of the related information together.

A structure can be defined as a new named type or user-defined data type, thus extending the number of
available types. It can be our other structures, arrays, or pointers as some of its members.

The syntax of structure is

struct structure_name

data_type member_variables1;

data_type member_variables2;

...... .......

data_type member_variablesn;

Once structure_name is declared as a new data type, the variable of that can be declared as

struct structure_name structure_variable;

The major di erence between array and structure are

ARRAY STRUCTURE

Array refers to a collection consisting of elements Structure refers to a collection consisting of


of homogeneous data type. elements of heterogeneous data type.

Array uses subscripts or “[ ]” (square bracket) for Structure uses “.” (Dot operator) for element
element access access

Array is pointer as it points to the first element of


Structure is not a pointer
the collection.

Instantiation of Array objects is not possible. Instantiation of Structure objects is possible.

Array size is fixed and is basically the number of Structure size is not fixed as each element of
elements multiplied by the size of an element. Structure can be of di erent type and size.
ARRAY STRUCTURE

Bit filed is not possible in an Array. Bit filed is possible in an Structure.

Array declaration is done simply using [] and not Structure declaration is done with the help of
any keyword. “struct” keyword.

Arrays is a non-primitive datatype Structure is a user-defined datatype.

Structure traversal and searching is complex


Array traversal and searching is easy and fast.
and slow.

struct sruct_name{ data_type1 ele1;


data_type array_name[size];
data_type2 ele2; };

Array elements are stored in continuous memory Structure elements may or may not be stored
locations. in a continuous memory location.

Array elements are accessed by their index number Structure elements are accessed by their
using subscripts. names using dot operator.

Program Part:

#include<stdio.h>

struct Student{

char name[20];

int roll;

int percentage;

};

void main(){

struct Student s[100];

int n, i;

printf("Enter number of students: ");

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

printf("Enter %d Student Name, Roll No and Percentage: \n", i + 1);

scanf("%s%d%d", &s[i].name, &s[i].roll, &s[i].percentage);

printf("Students which have percenatge greater than 60 are : \n");

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

if( s[i].percentage >= 60 ){

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

4. What is algorithm? How is it di erent from flow chart?

Solution

An algorithm is a finite sequence of well-defined instructions, typically used to solve a class of specific
problems or to perform a computation.

The following are the features of a good algorithm;

Precision: a good algorithm must have a certain outlined steps. The steps should be exact enough, and
not varying.

 Uniqueness: each step taken in the algorithm should give a definite result as stated by the writer
of the algorithm. The results should not fluctuate by any means.

 Feasibility: the algorithm should be possible and practicable in real life. It should not be abstract
or imaginary.

 Input: a good algorithm must be able to accept a set of defined input.

 Output: a good algorithm should be able to produce results as output, preferably solutions.

 Finiteness: the algorithm should have a stop after a certain number of instructions.

 Generality: the algorithm must apply to a set of defined inputs.


The di erence between algorithm and flowchart is

SN Algorithm Flowchart

Algorithm is step by step procedure Flowchart is a diagram created by di erent


1.
to solve the problem. shapes to show the flow of data.

Algorithm is complex to
2. Flowchart is easy to understand.
understand.

3. In algorithm plain text are used. In flowchart, symbols/shapes are used.

4. Algorithm is easy to debug. Flowchart it is hard to debug.

5. Algorithm is di icult to construct. Flowchart is simple to construct.

6. Algorithm does not follow any rules. Flowchart follows rules to be constructed.

Algorithm is the pseudo code for the Flowchart is just graphical representation of
7.
program. that logic.

5. What is type conversion? Discuss type casting with suitable example.

Solution

Type conversion is converting one type of data type to another type. It is also known as Type casting. Type
conversion in C can be classified as

1. Implicit Type Conversion

2. Explicit Type Conversion

1. Implicit Type Conversion

When the type conversion is performed automatically by the compiler without programmer’s
intervention, such type of conversion is known as implicit type conversion or type promotion.
int x;

for(x = 97; x <= 122; x++){

//Implicit casting from int to char

printf("%c", x);

b. Explicit Type Conversion

Th type conversion performed by the programmer by using posing the data type of the expression of the
specific type is known as explicit type conversion. The explicit type conversion is also knowns type
casting. Type casting in c is done in following form:

(data_type) expression;

Where, data_type is any valid C data type and expression may be constant, variable or expression.

For Example

int x = 7, y = 5;

float z;

z = (float) x / (float) y;

6. Discuss increment and decrement operators with example.

Solution

C has two special unary operators called increment (++) and decrement (--) operators. These operators
increment and decrement value of a variable by 1.

++x is same as x = x + 1 or x += 1
--x is same as x = x - 1 or x -= 1

Increment and decrement operators can be used only with variables. They can’t be used with constants
or expressions.

Increment/Decrement operators are of two types:

1. Prefix increment/decrement operator.

2. Postfix increment/decrement operator.

1. Prefix increment/decrement operator


The prefix increment/decrement operator immediately increases or decreases the current value of the
variable. This value is then used in the expression. Let’s take an example:

y = ++x;

Here first, the current value of x is incremented by 1. The new value of x is then assigned to y. Similarly, in
the statement:

y = --x;

The following program demonstrates prefix increment/decrement operator in action:

#include<stdio.h>

int main()

int x = 12, y = 1;

printf("Initial value of x = %d\n", x); // print the initial value of x

printf("Initial value of y = %d\n\n", y); // print the initial value of y

y = ++x; // increment the value of x by 1 then assign this new value to y

printf("After incrementing by 1: x = %d\n", x);

printf("y = %d\n\n", y);

y = --x; // decrement the value of x by 1 then assign this new value to y

printf("After decrementing by 1: x = %d\n", x);

printf("y = %d\n\n", y);

// Signal to operating system everything works fine

return 0;

The output of above program is

Initial value of x = 12

Initial value of y = 1

After incrementing by 1: x = 13

y = 13

After decrementing by 1: x = 12

y = 12
2. Postfix Increment/Decrement operator

The postfix increment/decrement operator causes the current value of the variable to be used in the
expression, then the value is incremented or decremented. For example:

y = x++;

Here first, the current value of x is assigned to y then x is incremented.

Similarly, in the statement:

y = x--;

the current value of x is assigned to y then x is decremented.

The following program demonstrates postfix increment/decrement operator in action:

#include<stdio.h>

int main()

int x = 12, y = 1;

printf("Initial value of x = %d\n", x); // print the initial value of x

printf("Initial value of y = %d\n\n", y); // print the initial value of y

y = x++; // use the current value of x then increment it by 1

printf("After incrementing by 1: x = %d\n", x);

printf("y = %d\n\n", y);

y = x--; // use the current value of x then decrement it by 1

printf("After decrementing by 1: x = %d\n", x);

printf("y = %d\n\n", y);

// Signal to operating system everything works fine

return 0;

The output of above program is

Initial value of x = 12

Initial value of y = 1

After incrementing by 1: x = 13

y = 12
After decrementing by 1: x = 12

y = 13

7. Write a program that computes the sum of digits of a given integer number

Solution

#include <stdio.h>

int main()

int num, sum=0;

/* Input a number from user */

printf("Enter any number to find sum of its digit: ");

scanf("%d", &num);

/* Repeat till num becomes 0 */

while(num!=0)

/* Find last digit of num and add to sum */

sum += num % 10;

/* Remove last digit from num */

num = num / 10;

printf("Sum of digits = %d", sum);

return 0;

The output above program is

Enter any number to find sum of its digit: 1234

Sum of digits = 10
8. What is function? Discuss the benefits of using function.

Solution

Function is a logically grouped set of statements that perform a specific task. In C program, a function is
created to achieve something. Every C program has at least one function i.e. main() where the execution
of the program starts. It is a mandatory function in C.

There are type of functions

1. Standard Library Functions

2. User Defined Functions

The advantages of using functions are:

 Avoid repetition of codes.

 Increases program readability.

 Divide a complex problem into simpler ones.

 Reduces chances of error.

 Modifying a program becomes easier by using function.

9. Write a program to find sum and average of 10 integer numbers stored in an array.

Solution

#include <stdio.h>

int main()

int array[50], i, n, sum = 0;

float avg;

printf("How namy numbers? ");

scanf("%d", &n);

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


{

printf("Enter the %d numbers: ", i + 1);

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

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

sum = sum + array[i];

printf("The sum of 10 numbers you entered is=%d\n", sum);

avg = (float)sum / n;

printf("The avg of the 10 numbers you entered is=%.2f\n", avg);

return 0;

The output of above program is

How namy numbers? 5

Enter the 1 numbers: 1

Enter the 2 numbers: 2

Enter the 3 numbers: 3

Enter the 4 numbers: 4

Enter the 5 numbers: 5

The sum of 10 numbers you entered is=15

The avg of the 10 numbers you entered is=3.00


10. Define pointer. Discuss the relationship between pointer and one-dimensional array

Solution

A pointer is a variable that contains a memory address of data or another variable. Normally, a pointer
variable is declared to some type, like any other variables, so that it will work only with data of given type.

The syntax of pointer is

data_type *pointer;

Relationship between pointer and one-dimensional array

An array is a block of sequential data. Let’s write a program to print addresses of array elements.

#include <stdio.h>

int main() {

int x[4];

int i;

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

printf("&x[%d] = %p\n", i, &x[i]);

printf("Address of array x: %p", x);

return 0;

The output of above program si

&x[0] = 1450734448

&x[1] = 1450734452

&x[2] = 1450734456

&x[3] = 1450734460

Address of array x: 1450734448

There is a di erence of 4 bytes between two consecutive elements of array x. It is because the size
of int is 4 bytes (on our compiler).

Notice that, the address of &x[0] and x is the same. It’s because the variable name x points to the first
element of the array.
From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent to *x.

Similarly,

 &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).

 &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).

 …

 Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

11. Write a program to read and print data stored in a file [Link].

Solution

#include <stdio.h>

int main()

char ch;

FILE *fp;

fp = fopen("[Link]", "r");

if (fp == NULL)

printf("Error while opening the file.\n");

exit(0);

printf("The contents of %s file are:\n", file_name);

while((ch = fgetc(fp)) != EOF)

printf("%c", ch);

fclose(fp);
return 0;

Why do we need graphics functions? Write a program to draw a circle.

Solution

Graphics programming in C used to drawing various geometrical shapes(rectangle, circle eclipse


etc), use of mathematical function in drawing curves, coloring an object with di erent colors and
patterns and simple animation programs like jumping ball and moving cars.

C graphics using graphics. h functions or WinBGIM (Windows 7) can be used to draw di erent shapes,
display text in di erent fonts, change colors and many more. Using functions of graphics. You can draw
circles, lines, rectangles, bars and many other geometrical figures.

Common used graphics functions are:

1. Arc()

2. circle()

3. closegraph()

4. ellipse()

5. getcolor()

6. getmaxx()

7. getmaxy()

8. getpixel()

9. getx()

10. gety()

11. line()

12. putpixel()

13. rectangle()

14. setcolor()

Program Part:

#include<stdio.h>

#include <graphics.h>

int main()
{

int gd = DETECT, gm;

initgraph(&gd, &gm, "");

circle(250, 200, 50);

closegraph();

return 0;

2075

1. What is looping statement? Discuss di erent looping statements with suitable example of
each.

Solution

Loop may be defined as a block of the statement which is repeatedly executed for a certain number of
times or until a particular condition is satisfied. When an identical task is to be performed for a number of
times, then the loop is used.

For example, When we have to print the numbers from 1 to 100. We can use a loop to print the number
from 1 to 100.

We have three types of loop.

 For Loop

 While Loop

 do While Loop

1. For Loop

For loop is useful to execute a statement for a number of times. The syntax of using for loop is

for(counter initialization, test condition, increment or decrement)

statement; or block of loop

Flowchat
Example:

#include <stdio.h>

int main(){

for(int i=1; i<=10; i++){

// This statement would be executed repeatedly until the condition i<=10 returns false.

printf("The value of i = %d\n", i);

return 0;

The output of above program is

The value of i = 1

The value of i = 2

The value of i = 3

The value of i = 4

The value of i = 5

The value of i = 6

The value of i = 7

The value of i = 8

The value of i = 9

The value of i = 10

2. While Loop

The syntax of while loop is:

while(test condition)

//body of loop

The test condition is evaluated and if the condition is true, then the body of the loop is executed. After
execution of the body once, the test-condition is again evaluated and if it is true, the body is executed
once again. This process of repeated execution of the body continues until the test-condition finally
becomes false and the control is transferred out of the loop. On exit, the program continues with the
statement immediately after the body of the loop.

Example:

#include <stdio.h>

int main(){

int i=1;

// The loop would continue to print the value of i until the given condition i<=10 returns false

while(i<=10){

printf("The value of i = i", i);

i++;

The output of the above program is:

The value of i = 1

The value of i = 2

The value of i = 3

The value of i = 4

The value of i = 5

The value of i = 6

The value of i = 7

The value of i = 8

The value of i = 9

The value of i = 10

3. Do While Loop

The syntax of do while loop is:

do

statement;
}while(test condition);

In the do while loop, the body of the loop is executed first without testing condition. At the end of the
loop, the test condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop is terminated, and the control goes to the statement
that appears immediately after the while statement.

Example:

#include <stdio.h>

int main(){

int i=1;

do{

printf("The value of i = i", i);

num++;

}while(i<=10);

return 0;

The output of the above program is:

The value of i = 1

The value of i = 2

The value of i = 3

The value of i = 4

The value of i = 5

The value of i = 6

The value of i = 7

The value of i = 8

The value of i = 9

The value of i = 10
2. Define array? What are the benefits of using array? Write a program to add two matrices
using array.

Solution

An array is a group of related data items that share a common name. In the other words, an array is a
data structure that stores a number of data items as a single entity (object). The individual data items
are called elements and all of them have some data types. An array is used when multiple data items that
have common characteristics are required.

The benefit of using arrays are given below

1. In array, We can access the data very easily using index number

2. We can apply searching process in array easily

3. We can represent 2D arrays as matrices

4. We can used to implement other data structure like linked lists, stack, queue, trees, graph etc.

Program to add two matrices using matrix

#include <stdio.h>

int main()

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

printf("Enter the number of rows: ");

scanf("%d", &r);

printf("Enter the number of columns: ");

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;

The output of above program is

Enter the number of rows: 2


Enter the number of columns: 3

Enter elements of 1st matrix:

Enter element a11: 1

Enter element a12: 2

Enter element a13: 3

Enter element a21: 4

Enter element a22: 5

Enter element a23: 6

Enter elements of 2nd matrix:

Enter element b11: 7

Enter element b12: 8

Enter element b13: 9

Enter element b21: 1

Enter element b22: 2

Enter element b23: 3

Sum of two matrices:

8 10 12

579

3. Why do we need data files? What are the di erent file opening modes? Write a program
that reads data from a file “[Link]” and writes to “[Link]” file.

Solution

A data file is a computer file which stores data to be used by a computer application or system, including
input and output data. A data file usually does not contain or code to be executed (that is, a computer
program). Need of data files are listed below:

 When a program is terminated, the entire data is lost. Storing in a file will preserve your data even
if the program terminates.

 If we have to enter a large number of data, it will take a lot of time to enter them all.
 However, if we have a file containing all the data, we can easily access the contents of the file
using a few commands in C.

 We can easily move our data from one computer to another without changes.

Openings Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file

If the file does not exist,


R Open for reading
fopen() returns NULL

Open for reading in binary If the file does not exist,


Rb
mode fopen() returns NULL

If the file exists, its contents


W Open for reading are overwritten. If the file does
not exist, it will created

If the file exists, its contents


Open for writing in binary
Wb are overwritten. If the file does
mode
not exist, it will created

Open for append. Data is If the file does not exist, if will
A
added to the end of the file. be created.

Open for append in binary


If the file does not exist, it will
Ab mode. Data is added to the
be created
end of the file.

Open for both reading and If the file does not exist,
r+
writing. fopen() returns NULL.

Open for both reading and If the file does not exist,
rb+
writing in binary mode. fopen() returns NULL.
If the file exists, its contents
Open for both reading and
w+ are overwritten. If the file does
writing
not exist, it will be created.

If the file exists, its contents


Open for both reading and
wb+ are overwritten. If the file does
writing in binary mode.
not exist, it will be created.

Open for both reading and If the file does not exist, it will
a+
appending. be created.

Open for both reading and If the file does not exist, it will
ab+
appending in binary mode. be created.

Program Part

#include <stdio.h>

#include <stdlib.h>

int main(){

FILE *fptr1, *fptr2;

char c;

// Open One file for reading

fptrl = fopen("[Link]", "r");

if( fptrl == NULL ){

printf("Cannot open a file");

exit(0);

//opeaning another file for writing

fptr2 = fopen("[Link]", "w");

if( fptr2 == NULL ){

printf("Cannot open a file");

exit(0);

}
//Read contents from file

c = fgets(fptr1);

while(c != EOF){

fputc(c, fptr2);

c = fgetc(fptr1)''

printf("\nContents copied");

fclose(fptr1);

fclose(fptr2);

return 0;

4. Discuss di erent logical operation in detail.

Solution

They compare or evaluate logical and relational expressions. Following table shows all the logical
operations supported by C language. Assume variable A holds 1 and variable B holds 0 then:

Operators Description Example

If both the operands are non-


&& (Logical AND) zero, then the condition (A && B) is false.
becomes true.

If any of the two operands is


|| (Logical OR) non-zero, then the condition (A || B) is true.
becomes true.

It is used to reverse the


logical state of its operand. If
| (Logical NOT) a condition is true, then !(A && B) is true.
Logical NOT operator will
make it false.
This is the program to demonstrate the use of logical operators

#include <stdio.h>

main() {

int a = 5;

int b = 20;

int c ;

if ( a && b ) {

printf("Line 1 - Condition is true\n" );

if ( a || b ) {

printf("Line 2 - Condition is true\n" );

/* lets change the value of a and b */

a = 0;

b = 10;

if ( a && b ) {

printf("Line 3 - Condition is true\n" );

} else {

printf("Line 3 - Condition is not true\n" );

if ( !(a && b) ) {

printf("Line 4 - Condition is true\n" );

The output of above program is

Line 1 - Condition is true

Line 2 - Condition is true

Line 3 - Condition is not true

Line 4 - Condition is true


What is break statement? Discuss with example. How the break statement is di erent from continue
statement?

Solution

The breakstatement terminates the execution of the loop and the control is transferred to the statement
immediately following the loop. Generally, the loop is terminated when its test condition is false. But if we
have to terminate the loop instantly without testing loop termination condition, the breakstatement is
useful. The syntax for this is:

break;

Example of break statement

#include <stdio.h>

int main(){

int x;

for ( x=1; x <= 10; x++ )

printf("The value of x = %d", x);

if( x == 5)

break;

return 0;

The output of above program is

The value of x = 1

The value of x = 2
The value of x = 3

The value of x = 4

The value of x = 5

The di erence between break and continue statement is

break continue

A break can appear in both switch and A continue can appear only in loop (for, while, do)
loop (for, while, do) statements. statements.

A continue doesn’t terminate the loop, it causes the loop


A break causes the switch or loop
to go to the next iteration. All iterations of the loop are
statements to terminate the moment it
executed even if continue is encountered.
is executed. Loop or switch ends
The continue statement is used to skip statements in the
abruptly when break is encountered.
loop that appear after the continue.

The break statement can be used in The continue statement can appear only in loops. You will
both switch and loop statements. get an error if this appears in switch statement.

When a break statement is


encountered, it terminates the block When a continue statement is encountered, it gets the
and gets the control out of the switch or control to the next iteration of the loop.
loop.

A break causes the innermost


A continue inside a loop nested within a switch causes the
enclosing loop or switch to be exited
next loop iteration.
immediately.

Write a program to check whether a number entered is even or odd.

Solution
#include <stdio.h>

int main() {

int num;

printf("Enter an integer: ");

scanf("%d", &num);

// true if num is perfectly divisible by 2

if(num % 2 == 0)

printf("%d is even.", num);

else

printf("%d is odd.", num);

return 0;

The output of above program is

Enter an integer: -7

-7 is odd.

Write a program to calculate sum of first 10 odd numbers.

Solution

#include<stdio.h>

int main(){

int i, sum=0;

for(int i = 1; i < 20; i = i+2)

sum += i;

printf("sum=%d", sum);

The output of above program is

sum=100
What is preprocessor directives? Discuss # define directive with example.

Solution

Preprocessor directives are lines included in a program that begin with the character #, which make them
di erent from a typical source code text. They are invoked by the compiler to process some programs
before compilation. Preprocessor directives change the text of the source code and the result is a new
source code without these directives.

A preprocessor directive is usually placed in the top of the source code in a separate line beginning with
the character “#”, followed by directive name and an optional white space before and after it. Because a
comment on the
same line of declaration of the preprocessor directive has to be used and cannot scroll through the
following line, delimited comments cannot be used. A preprocessor directive statement must not end
with a semicolon ().Preprocessor directives can be defined in source code or in the common line as
argument during compilation.

In the C Programming Language, the #define directive allows the definition of macros within your source
code. These macro definitions allow constant values to be declared for use throughout your code.

Macro definitions are not variables and cannot be changed by your program code like variables. You
generally use this syntax when creating constants that represent numbers, strings or expressions.

Syntax:
The syntax for creating a constant using #define in the C language is:

#define CNAME value

OR

#define CNAME(expression)

Where,

 CNAME: The name of the constant. Most C programmers define their constant names in
uppercase, but it is not a requirement of the C Language.

 Value: The value of the constant.

 Expression: Expression whose value is assigned to the constant. The expression must be enclosed
in parentheses if it contains operators.

Example:
#include <stdio.h>

#define NAME "Aaray"

#define AGE 10

int main(){

printf("%s is over %d years old. \n", NAME, AGE);

return 0;

Discuss any five string library functions.

Solution

1. strlen()
This gives the length of the given string including blank spaces and null character.

Example: Write a program to read any string and then find out its length

#include <stdio.h>
#include <string.h>
void main(){
char st[20];
int l;
printf("Enter any string");
gets(st); //or scanf("%s" st);
l = strlen(st);
printf("The length of string is:%d",1);
}

2. strcpy()
This is used to copy the content of one string to another string. It takes two arguments: the first is for
the destination string array and the second is for the source string array. The source string is copied
to the destination string.

Example: Write a program to read any string and then copy to another string by using strcpy()
function
#include<stdio.h>
#include<string.h>
void main(){
char st1[] = "Bhupendra";
char st2[10];
strcpy(st2.st1);
puts(st2);
}

3. strcat()
This is used to concatenate (join) two strings and the resulting string is a single string. It takes two
arguments: the first is for the destination string array and the Second is for the source string array.
The source string and the destination strings are concatenated and the resulting string is stored in the
first destination.

Example: Write a program to concatenate any two strings together by using string strcat() function

#include<stdio.h>
#include<string.h>
void main(){
char str1[] = "Welcome ";
char str2[] = "HamroCSIT";
strcat(str1, str2);
puts(str1);
}

4. strcmp()
This is used to compare two strings, character by character. It accepts two strings as parameter and
returns an integer whose value is

 <0 if the first string is smaller than the second

 == if both are equal or same

 >0 if the first string is greater than the second

Example: Write a program to compare any two strings by using strcmp() function

#include<stdio.h>
#include<string.h>
void main(){
char str1[20], str2[20];
printf("Enter first string:");
gets(str1);
printf("Enter second string:");
gets(str2);
if( strcmp( str1, str2 ) > 0 ){
printf("Greater is %s", str1);
}else{
printf("Greater is %s", str2);
}
}

5. strev()
This string manipulation function which is used to reverse the given string.

Example: A program to reverse the given string using the function strrev().

#include<stdio.h>
#include<string.h>
void main(){
char str[20];
printf("Enter any string:");
gets(str);
strev(str);
printf("Reverse is %s", str);
}

What is dynamic memory allocation? Discuss the use of malloc() in dynamic memory allocation with
example.

Solution
As we know, an array is a collection of a fixed number of values. Once the size of an array is
declared, you cannot change it.

Sometimes the size of the array you declared may be insufficient. To solve this issue, you can
allocate memory manually during run-time. This is known as dynamic memory allocation in C
programming.
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used.
These functions are defined in the header file.

malloc()
The name “malloc” stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a
pointer of void which can be casted into pointers of any form.

Syntax:

ptr = (castType*) malloc(size);


Example:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
// Get the number of elements for the array
printf("Enter number of elements:");
scanf("%d",&n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully allocated
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}

What is structure? Create a structure rectangle with data members length and breadth.

Solution
A structure is a collection of variables under a single name. These variables can be of different types,
and each has a name that is used to select it from the structure. The variables are called members
of the structure. A structure is a convenient way of grouping general pieces of the related
information together.

A structure can be defined as a new named type or user-defined data type, thus extending the
number of available types. It can be our other structures, arrays, or pointers as some of its members.

The syntax of structure is

struct structure_name
{
data_type member_variables1;
data_type member_variables2;
...... .......
data_type member_variablesn;
}
Once structure_name is declared as a new data type, the variable of that can be declared as

struct structure_name structure_variable;


Example: A program to assign values of length and breadth to the member of structure. Rectangle
and to display on the screen.

#include<stdio.h>
struct Rectangle{
int length;
int breadth;
};
void main(){
struct Rectangle r;
[Link] = 55;
[Link] = 30;
printf("The length of rectangle is %d", [Link]);
printf("The breadth of rectangle is %d", [Link]);
}

Write short notes on:

a. Benefits of data files


b. Graphics functions

Solution

a) Benefits of Data Files


Many application require information be written to or read from an auxiliary storage devices. Such
information is stored on the storage device in the form of data file. Thus data files allows us to store
information permanently and to access later on and alter that information whenever necessary.

Benefit of data files are listed below

 Backup: possible to take faster and automatic back-up of database stored in files of computer-
based systems

 Compactness: possible to store data compactly

 Data Retrieval: Computer-based systems provide enhanced data retrieval techniques to


retrieve data stored in files in easy and efficient way.

 Editing: easy to edit any information stored in computers in form of files.

 Remote access: possible to access data remotely.

 Sharing: Data stored in files of computer-based systems ca be shared among multiple users
at a same time.

b) Graphics Functions
There are so many built in graphics functions defined in C library. The basic graphics functions are
described as below. Graphics functions are text mode graphics functions as well as graphical mode
functions
Name Of The Function Purpose Example

Plots the pixel at


putpixel(320,240) – plots a pixel with the set
putpixel(x,y) the grid location
color at the center of the screen.
(x,y).

Gets the color of


getpixel(320,240) – gets the color of the center
getpixel(x,y) the pixel located at
of the screen for 640X480 resolution.
(x,y).

Draws a line from


line(0,0,320,240) – draws a line from the upper
line(x1, y1, x2, y2) (x1, y1) to (x2,
left of screen to the center.
y2).

Draws a circle circle(320,240,10) – draws a circle with center


circle(xc, yc, r) with center (xc, at the center of the screen and radius = 10
yc) & radius = r. units.

Draws a rectangle
rectangle(320,240,400, 300) – will draw a
with (x1, y1) and
rectangle(x1,y1,x2,y2) rectangle such that (320,240) is the left-top co-
(x2, y2) as
ordinate and (400,300) is the right-bottom one.
corners.

Draws an ellipse
with (xc,yc) as
center. xr&yr are
ellipse(320,240,0,360,100,50) – draws an
semimajor and
entire ellipse whose center is at (320,240) with
ellipse(xc, yc, s, e, xr, yr) semiminor axes
semimajor and semiminor axes 100 & 50
respectively. If
respectively.
s=0 & e=180 only
upper half of the
ellipse is drawn.

Draws an arc with


arc(320,240,45,135,100) – draws an arc whose
center as (xc,yc),
center is at (320,240), radius is 100 units and
arc(xc, yc, s, e, r) radius=r & staring
the start angle is 45 degrees & the end angle
& end angles as s
135 degrees.
& e respectively.
Moves the cursor moveto(320,240) – moves the cursor to the
moveto(x,y)
pointer to (x, y). center of the screen from its current location.

Draws a line up to
(x, y) from the lineto(320,240) – will draw a line from the
lineto(x,y)
current cursor current location to the center of the screen.
location.

Moves the cursor


by a relative moverel(10, 5) – moves the cursor in the x-
moverel(xr, yr) distance of xr direction by 10 units and in the y-direction by
along x-axis and 15 units.
yr along y-axis.

Draws a line from


the cursor point to
linerel(10, 5) – draws a line from the current
a point at a
position to a point whose distance from the
linerel(xd,yd) relative distance of
current position is 10 units along x and 5 units
xd along x and yd
along y.
along y, from the
current position.

Displays the string


outtextxy(320,240,“Graphics”) – displays the
within inverted
outtextxy(x,y,“string”) word Graphics with the first letter starting
commas at
from the center of the screen.
location (x,y).

Draws lines with


specified styles,
where x is the line
type, y is the
pattern and z is the setlinestyle(0,1,1) – sets the system for
setlinestyle(x,y,z) thickness. (x=0 ⇒ drawing a solid line with thickness 1 and a
solid, x=1⇒dotted, particular pattern.
x=2⇒ center
line,x=3⇒ dashed,
x=4 ⇒user-
defined line).

Sets color of line.


setcolor(RED) – sets the color of the drawing
setcolor(x) There are 16
pen as RED.
possible colors.
Sets a predefined
fill style where
setfillstyle(SOLID_FILL, RED) – prepares to
setfillstyle(x,y) x⇒item number
fill an area in solid style and with RED color.
identifying a fill
style &y⇒color.

Fills up an ellipse
fillellipse(320,240,100,50)– fills an ellipse
with center
fillellipse(xc,yc,xrad,yrad) whose center is at (320,240) and the two axes
(xc,yc), a=xrad&
at x=100 and y=50.
b=yrad.

Draws a polygon
where x⇒number
of points used to
build the polygon drawpoly(4,array) – draws a polygon
drawpoly(x,y) and y⇒base containing 4 points and the base address is
address of the contained in the array array[].
array containing
the co-ordinate
points.

Fills up a polygon.
x⇒number of
points used to
fillpoly(x,y) – draws a polygon containing 4
build the polygon
points and the base address is contained in the
fillpoly(x,y) and y⇒base
array array[]. It also fills up the polygon using
address of the
the current fill style and color.
array containing
the co-ordinate
points.

Filling up the
elements of the
structure
getnewsettings(&vp) viewporttype (ex
vp) with the co-
ordinates of the
current viewport.

Gets the set of


getpalette(&palette)
color values.
Palette is of
structure
palettetype.

Changes the color


values. setpalette setpalette(0,5) – Changes the first color in the
setpalette(colornum,color) changes the current palette (background color) to actual
colormun entry in color number 5.
palette to color.

Returns true if
keyboard is hit.
kbhit() This is useful for
interactive
graphics.

Sets font style.


x⇒font type, settextstyle(DEFAULT_font,HORIZ_DIR,4) –
settextstyle(x,y,z) y⇒font direction draws a text in the existing font and from left
(e.g. VERT_DIR), to right
z⇒point size.

Activates the
speaker at a
sound(x) sound(7) – will activate a sound at 7 Hz.
specific time unit
in x Hz.

Stops previously
nosound()
activated sound.

Allowing the
previously
executed
delay(6000) – will make the command run for
delay(x) command to
6 sec.
remain activated
for a time unit x(in
msec).

A function for
storing the image.
getimage(x,y,a,b,c)
x⇒x co-ordinate
of the top left
corner of the
block. y⇒y co-
ordinate of the top
left corner of the
block. a⇒x co-
ordinate of the
bottom right
corner of the
block. b⇒y co-
ordinate of the
bottom right
corner of the
block. c⇒the
address of the
memory location
from where the
image would be
stored.

Draws a filled-in
two-dimensional
rectangular bar. It
does not draw the bar(20,30,40,70) – will draw a rectangle whose
bar(left,top,right,bottom) bar boundary. The upper left corner is at (20,30) and lower right
rectangle is drawn corner is at (40,70).
using the current
fill pattern and
color.

2077

What do you mean by looping? Explain while loop with suitable example. Compare while loop with
do-while loop. Write a program to find sum and average of first n natural numbers.

Solution
Loop may be defined as a block of the statement which is repeatedly executed for a certain number
of times or until a particular condition is satisfied. When an identical task is to be performed for a
number of times, then the loop is used.

The syntax of while loop is:


while(test condition)
{
//body of loop
}

The test condition is evaluated and if the


condition is true, then the body of the loop is executed. After execution of the body once, the test-
condition is again evaluated and if it is true, the body is executed once again. This process of
repeated execution of the body continues until the test-condition finally becomes false and the control
is transferred out of the loop. On exit, the program continues with the statement immediately after the
body of the loop.

Example:

#include <stdio.h>
int main(){
int i=1;
while(i<=10){
printf("The value of a = %d", i);
i++;
}
}
The output of the above program is:

The value of a = 1
The value of a = 2
The value of a = 3
The value of a = 4
The value of a = 5
The value of a = 6
The value of a = 7
The value of a = 8
The value of a = 9
The value of a = 10
The comparison between while loop and do-while loop are

While Loop Do While Loop

The statement is executed after the condition is The statement is executed at least once, then after the
checked. condition is checked.

The statement is executed zero times if the


At least once, the Statement is executed.
condition is fast at first.

There is no semi-column at the end of the while


The is a semi-column at the end of the while loop.
loop.

If there is a simple statement, Brackets are not


Brackets are required for all conditions.
required.

While loop is entry controlled loop. Do while loop is exit controlled loop.

The program to find sum and average of first n natural numbers is

#include <stdio.h>
int main(){
int a, i = 0, sum = 0;
float average;
printf("How many numbers?\n");
scanf("%d", &a);
for(int i = 1; i <= a; i++){
sum += i;
}
average = sum / a;
printf("\nSum = %d", sum);
printf("\nAverage = %0.2f", average);
}
The output of above program is

How many numbers?


10
Sum = 55
Average = 5.00

What are the benefits of using arrays? Compare one dimensional array with two dimensional array.
Write a program to find transpose of a matrix.

Solution
An array is a group of related data items that share a common name. In the other words, an array is
a data structure that stores a number of data items as a single entity (object).

The benefit of using arrays are given below

1. In array, We can access the data very easily using index number
2. We can apply searching process in array easily
3. We can represent 2D arrays as matrices
4. We can used to implement other data structure like linked lists, stack, queue, trees, graph etc.

The compare one dimensional array with two dimensional array is given below

Basis One Dimension Array Two Dimension Array

Store a single list of the element Store a ‘list of lists’ of the


Definition
of a similar data type. element of a similar data type.

Represent multiple data items as


Represent multiple data items as
Representation a table consisting of rows and
a list.
columns.

datatype
Declaration datatype variable_name[row]
variable_name[row][column]
size of(datatype of the variable
size of(datatype of the variable
Size of the array)* the number of
of the array) * size of the array
rows* the number of columns.

Example int arr[7]; int arr[7][5];

Program to Transpose of Matrix

#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
{
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// printing the matrix a[][]
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
{
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
// computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
{
transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j)
{
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
The output of above program is

Enter rows and columns: 3


3
Enter matrix elements:
Enter element a11: 1
Enter element a12: 2
Enter element a13: 3
Enter element a21: 4
Enter element a22: 5
Enter element a23: 6
Enter element a31: 7
Enter element a32: 8
Enter element a33: 9
Entered matrix:
123
456
789
Transpose of the matrix:
147
258
369
What is structure? How is it different from union? Create a structure named course with name, code,
and credit_hour as its members. Write a program using this structure to read data of 5courses and
display data of those curses with credit_hour greater than 3.

Solution
A structure is a collection of variables under a single name. These variables can be of different types,
and each has a name that is used to select it from the structure. The variables are called members
of the structure. A structure is a convenient way of grouping general pieces of related information
together.

The difference between structure and union is:

Structure Union

1) Each member within a structure is assigned its 1) All members within the union share the same
own unique storage. It takes more memory than a storage area of computer memory. It takes less
union. memory than structure.

2) The amount of memory required to store a union is


2) The amount of memory required to store a
the same as a member that occupies the largest
structure is the sum of the size of all members.
memory.

3) All the structures can be accessed at any point 3) Only one member of the union can be accessed at
in time. any given time.

Source: [Link]

Program:

#include <stdio.h>
#include <string.h>
struct student {
int credit_hour;
char name[10];
char code[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 courses:\n");
for (i = 0; i < 5; i++){
printf("\nEnter Subject Name: ");
scanf("%s", &st[i].name);
printf("Enter Subject Code: ");
scanf("%s", &st[i].code);
printf("Enter Credit Hour: ");
scanf("%d", &st[i].credit_hour);
printf("\n");
}
printf("\n\nCourse Information List:\n");
for (i = 0; i < 5; i++){
if( st[i].credit_hour > 3 ){
printf("\nSubject Name:%s, Subject Code:%s, Subject Credit Hour:%d\n", st[i].name, st[i].code,
st[i].credit_hour);
}
}
return 0;
}
The output of the above program is

Enter Records of 5 courses:


Enter Subject Name: Physic
Enter Subject Code: PHY
Enter Subject Code: 3
Enter Subject Name: Math
Enter Subject Code: MTH
Enter Subject Code: 4
Enter Subject Name: DigitalLogic
Enter Subject Code: DL
Enter Subject Code: 4
Enter Subject Name: C
Enter Subject Code: c
Enter Subject Code: 3
Enter Subject Name: IIT
Enter Subject Code: IIT
Enter Subject Code: 4
Course Information List:
Subject Name:Math, Subject Code:MTH, Subject Credit Hour:4
Subject Name:DigitalLogDL, Subject Code:DL, Subject Credit Hour:4
Subject Name:IIT, Subject Code:IIT, Subject Credit Hour:4

Explain flowchart with example. What are the benefits of using flowcharts?

Solution
A flowchart is simply a graphical representation of steps. It shows steps in sequential order and is
widely used in presenting the flow of algorithms, workflow or processes. Typically, a flowchart shows
the steps as boxes of various kinds, and their order by connecting them with arrows.

In flowchart, Different shapes have different meanings. The meanings of some of the more common
shapes are as follows:
Example of flowchart to check vowel or not

What is data type? Why do we need it in programming? Explain any three basic data types with
example.

Solution
Data types are the type of data or the category of data which we will be using for the program. For
example, data 10 and 100.5 are the data of different types. Data 10 is an integer number(i.e whole
number) while 100.5 is a fractional number. There are other varieties of data types supported by the
C Programming, each of which may be represented differently within the computer’s memory. the
variety f data type available allows the programmer to select the type needed by the application.

Basically, Data types have three classes.

 Primary data types


 User-defined data types

 Derived data types

Data types are important in programming languages, so that the memory which has to be given to
store a particular data that can be stored. Data types tells MMU that how much memory requirement
it has before the program compiles.

Data types are important in programming language because

1. It tells MMU(Memory Management Unit) that how much requirement it has before the program
compiles.
2. As the name suggests, it indicates the type/category of data/information. To categorize the
related information/characteristics of the real world entities into few categories which can be
easily understood by programs/machines in order to process them.

Here are the three basic type of data-types

1. Int
Data types that holds integer value

int hamrocsit = 100;


Here variable hamrocsit store integer value of 100.

2. Float
Data types that holds floating-point value

float hamrocsit = 64.5;


Here variable hamrocsit store floating point value of 64.5.

2. Char
Data types that holds character such as ‘a’, ‘b’, ‘C’ etc.

char hamrocsit = 'Y';


Here variable hamrocsit store character ‘Y’.

What do you mean by unformatted I/O? Explain

Solution
C Program provides us console input and output functions. As the name says, the console
input/output functions allow us to –
 Read the input from the keyboard by the user accessing the console.

 Display the output to the user at the console.

The are two types of console input / output functions

1. Formatted input/output functions


2. Unformatted input/output functions

Unformatted console input/output functions are used to read a single input from the user at console
and it also allows us to display the value in the output to the user at the console.

Some of the most important formatted console input/output functions are –

Functions Description

Reads a single character from the user at the console, without echoing
getch()
it.

getche() Reads a single character from the user at the console, and echoing it.

Reads a single character from the user at the console, and echoing it,
getchar()
but needs an Enter key to be pressed at the end.

gets() Reads a single string entered by the user at the console.

puts() Displays a single string’s value at the console.

putch() Displays a single character value at the console.

putchar() Displays a single character value at the console.

Why the functions are called unformatted console


I/O functions?
While calling any of the unformatted console input/output functions, we do not have to use
any format specifiers in them, to read or display a value. Hence, these functions are
named unformatted console I/O functions.
Write a program to display first n prime numbers.

Solution
The program to print N prime number is

#include <stdio.h>
int main(){
int n, count = 1, flag, i = 2, j;
printf("Enter how many prime numbers? \n");
scanf("%d", &n);
/* Generating prime numbers */
while (count <= n){
flag = 0;
for (j = 2; j <= i / 2; j++){
if (i % j == 0)
{
flag = 1;
break;
}
}
if (flag == 0){
printf("%d\t", i);
count++;
}
i++;
}
return (0);
}
The output of above program is

Enter how many prime numbers?


10
2 3 5 7 11 13 17 19 23 29

Write a program to find product of two integers using your own function.
Solution
#include <stdio.h>
int multiply(int, int);
int main(){
int a, b;
printf("Enter Two Numbers: ");
scanf("%d%d", &a, &b);
printf("Product of %d x %d = %d", a, b, multiply(a, b));
return 0;
}
//Own Function to perform multiplication
int multiply(int a, int b){
return a * b;
}
The output of above program is

Enter Two Numbers: 3


6
Product of 3 x 6 = 18

Define pointer. Flow to you return pointers from functions? Explain with example.

Solution
A pointer is a variable that contains a memory address of data or another variable. Normally, a
pointer variable is declared to some type, like any other variables, so that it will work only with data of
given type.

The syntax of pointer is

data_type *pointer;
C Program allows us to return a pointer from a function. To do this, we have to declare the function
returning pointer

int *function(){
// body of function
}
Example that return pointer from function
This is the example to check the greatest number among two number.

#include <stdio.h>
// function declaration
int *getMax(int *, int *);
int main(void){
int x = 5;
int y = 10;
// pointer variable
int *max = NULL;
max = getMax(&x, &y);
// print the greater value
printf("Max value: %d\n", *max);
return 0;
}
// function definition
int *getMax(int *m, int *n){
if (*m > *n){
return m;
}else{
return n;
}
}
The output of above program is

Max value: 10

In the above example, First we have declared two integer variables x and y that has 5 and 10 value
respectively. And also we have declared null pointer with name max.

Then we have called the function getMax that return pointer. On this function, we have passed
address of the variables x and y.

if the value pointed by pointer m is greater than n then, getMax function return the address stored in
the pointer variable m otherwise it returns the address stored in the pointer variable n.
Explain different file I/O functions with example.

Solution
C provides a number of functions that helps to perform basic file operations.

Following are the functions:

1. fopen()
It is used to create new file or open a existing file

Syntax:

ptr = fopen("fileopen","mode");
Example:

fopen("E:\\cprogram\\[Link]", "w");
It will create file [Link] if not exists in the path E:\\cprogram\\

2. fclose()

It is used to close the file after reading and writing.

fclose(fptr);

3. getc()
It is used to read the character from the file

Syntax

int getc(FILE *stream)


4. fprintf()

It is used to write a set of data values to files

Syntax:

int fprintf(FILE *stream, const char *format, ...)


Example:

fp = fopen("[Link]", "w+");
fprintf(fp, "Welcome to Hamro CSIT");
5. fscanf()
It is used to read a set of data values to files

Syntax

int fscanf(FILE *stream, const char *format, ...)


Example:

char str1[10], str2[10], str3[10];


FILE * fp;
fp = fopen ("[Link]", "w+");
fputs("We are in 2012", fp);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

6. fputs()
It is used to write a string to file

Syntax:

int fputs(const char *str, FILE *stream)


Example:

fputs("This is c programming.", fp);

7. fgets()
It is used to read a line

Syntax

char *fgets(char *str, int n, FILE *stream)


Example:

char str[60];
fgets (str, 60, fp)

Write a program to draw a circle using graphics function


Solution
#include<stdio.h>
#include <graphics.h>
int main(){
int gd = DETECT, gm;
initgraph(&gd, &gm, "c://tc//bgi");
// circle function
circle(250, 200, 50);
closegraph();
return 0;
}

Write short notes On

a. Compilation and execution


b. Operator precedence and associativity

Solution

1. Compiling and Execution:


The compilation and execution process of C can be divided in to multiple steps:

 Preprocessing – Using a Preprocessor program to convert C source code in expanded


source code. “#includes” and “#defines” statements will be processed and replaced actually
source codes in this step.

 Compilation – Using a Compiler program to convert C expanded source to assembly source


code.

 Assembly – Using a Assembler program to convert assembly source code to object code.

 Linking – Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.

 Loading – Using a Loader program to load the executable code into CPU for execution.

2. Operator precedence and associativity


Operator precedence describes the way in which the operations are evaluated. When we have
several operations in an expression, each part is evaluated and resolved in a predetermined order
decided by the operator precedence.

Operators having higher precedence are solved first as compared to the lower precedence operators.

For example:

5+3*7 // it gives 26

This is so because the multiplication operator (“*”) has higher precedence over the addition operator
(“+”), thus the expression 3 * 7 will solved first and the result of it (i.e. 21) becomes the right operand
for the addition and then the addition is performed as 5 + 21 which returns 26.

Associativity defines the way in which the operators having same precedence are evaluated.

For example:

10*5/2 // it gives 25

(“*”) and (“/”) have same precedence and “left to right” associativity therefore 10*5 evaluated first,
then its result (50) becomes the second operand for (“/”) and after that 50/2 is evaluated which gives
25.

2079

What is the di erence between exit(0) and exit(1)? Discuss the need of nested
structue with an example. Write a program to find the value of xy without using
POW code.

Solution
The di erence between exit(0) and exit(1) are

exit(0) exit(1)
Reports the successful
Reports the abnormal termination of
termination/completion of the
the program.
program.

Reports the termination when the Reports the termination when some
program gets executed without any error or interruption occurs during
error. the execution of the program.

The syntax is exit(0); The syntax is exit(1);

The use of exit(0) is fully portable. The use of exit(1) is not portable.

The macro used for return code 0 The macro used for return code 1
is EXIT_SUCCESS is EXIT_FAILURE

EXIT_FAILURE is not restricted by the


EXIT_SUCCESS is defined by the
standard to be one, but many
standard to be zero.
systems do implement it as one.

Nested Structure in c:
C provides us the feature of nesting one structure within another structure by
using which, complex data types are created. For example, we may need to
store the address of an entity employee in a structure. The attribute address
may also have the subparts as street number, city, state, and pin code. Hence,
to store the address of the employee, we need to store the address of the
employee in a separate structure and nest the structure address into the
structure employee. Consider the following program.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",[Link],[Link], &[Link],
[Link]);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:
%s",[Link],[Link],[Link],[Link]);
}
Run Code
The output of above program is
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
Program to find the value of xy without using the POW function.
#include <stdio.h>
int Pow(int X, int Y) {
int power = 1, i;
for (i = 1; i <= Y; ++i) {
power = power * X;
}
return power;
}
int main() {
long long int base, exponent;
printf("Enter Base: ");
scanf("%d", &base);
printf("Enter Power: ");
scanf("%d", &exponent);
printf("%d ^ %d = %d", base, exponent, Pow(base, exponent));
return 0;
}
Run Code
The output of the above program is
Enter Base: 5
Enter Power: 3
5 ^ 3 = 125

Why do we need a break and continue statement? Define formal argument and actual argument in
function with examples. Identify and list the errors in the following code.

int main(){
int a,b,c
scanf("%d%d%d, &a, &b, &c);
sum(a, b, c);
return -1;
}
void sum(int x, int y, int z){
int sum;
sum = a + b + c;
return sum;
}

Solution
Break statements are used to stop the loop immediately when it is encountered whereas the continue
statement skips the current iteration of the loop and continues with the next iteration.

Syntax:

break;
continue;
Example of break statement:

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


if(j > 5) break;
printf("%d", j);
}
Here, when j values reach 6 then the loop stop.

Example of continue statement:

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


if(j == 5) continue;
printf("%d", j);
}
Here, when j value reaches 5 then it skips. It means it prints from 0 to 10 except 5.

Formal and Actual Argument:

Arguments that are mentioned in the function call are known as the actual argument. For example:

func1(12, 23);
here 12 and 23 are actual arguments.

Actual arguments can be constant, variables, expressions, etc.

Arguments that are mentioned in the definition of the function are called formal arguments. Formal
arguments are very similar to local variables inside the function. Just like local variables, formal
arguments are destroyed when the function ends.

int factorial(int n)
{
// write logic here
}
Here n is the formal argument.

Program Error Identification Part:

Part Remark

The given program doesn’t have any header files


Missing Header Files
#include<stdio.h>
Since, the sum function is defined in bottom but
prototype is not defined above
Missing Function Prototype
int sum(int, int, int)

int a, b, c Semicolumn is missing

Double quote is missing


scanf(“%d%d%d, &a, &b, &c); scanf(“%d%d%d”, &a, &b, &c);

It means function has error but there is not any error


so
return -1
return 0;

sum function must have integer return type


Function (sum) return type int sum()

Since, sum function is adding a, b, and c which is


undefind. Here,
Undefined variable
sum = x + y + z;

The correct program is

#include<stdio.h>
int sum(int, int, int);
int main(){
int a,b,c;
scanf("%d%d%d", &a, &b, &c);
sum(a, b, c);
return 0;
}
int sum(int x, int y, int z){
int sum;
sum = x + y + z;
return sum;
}
Run Code

Write a program to demonstrate the following menu-driven program. The user will provide an integer
and alphabet for making choice and the corresponding task has to be performed according as follow:

A. Find Odd or Even


B. Find Positive or Negative
C. Find the Factorial value
D. Exit

The choice will be displayed until the user will give “D” as a choice.

Solution
#include<stdio.h>
void oddeven(int num);
void posneg(int num);
void fact(int num);
int main(){
int number;
char choice;
do{
printf("A. Find Odd or Even\nB. Find Positive or Negative\nC. Find the Factorial value\[Link]");
printf("\n\nEnter your choice: ");
scanf(" %c", &choice);
if( choice != 'D' ){
printf("Enter a number: ");
scanf(" %d", &number);
}
switch(choice){
case 'A':
oddeven(number);
break;
case 'B':
posneg(number);
break;
case 'C':
fact(number);
break;
case 'D':
printf("\nExiting program\n");
break;
}
}while( choice != 'D' );
return 0;
}
void oddeven(int num){
if( num % 2 == 0 ){
printf("\n\n================\n%d is even number\n================\n\n", num);
}else{
printf("\n\n================\n%d is odd number\n================\n\n", num);
}
}
void posneg(int num){
if( num >= 0 ){
printf("\n\n================\n%d is positive number\n================\n\n", num);
}else{
printf("\n\n================\n%d is negative number\n================\n\n", num);
}
}
void fact(int num){
int i = 0, factorial = 1;
for( i = 1; i <= num; i++){
factorial *= i;
}
printf("\n\n================\nFactorial of %d = %d\n================\n\n", num, factorial);
}
Run Code
The output of above program is

A. Find Odd or Even


B. Find Positive or Negative
C. Find the Factorial value
[Link]
Enter your choice: A
Enter a number: 5
================
5 is odd number
================
A. Find Odd or Even
B. Find Positive or Negative
C. Find the Factorial value
[Link]
Enter your choice: B
Enter a number: 5
================
5 is positive number
================
A. Find Odd or Even
B. Find Positive or Negative
C. Find the Factorial value
[Link]
Enter your choice: C
Enter a number: 5
================
Factorial of 5 = 120
================
A. Find Odd or Even
B. Find Positive or Negative
C. Find the Factorial value
[Link]
Enter your choice: D
Exiting program
How do you swap the values of two integers without using the third temporary
variable? Justify with the example.

Solution
We can swap two variables without using a third temporary variable using the
following methods.
1. By using + and –
2. By using * and /
By using + and -:
Let’s see a simple c example to swap two numbers without using a third
variable.
#include <stdio.h>
int main()
{
int a = 10, b = 20;
printf("Before swap a=%d b=%d", a, b);
a = a + b; // a=30 (10+20)
b = a - b; // b=10 (30-20)
a = a - b; // a=20 (30-10)
printf("\nAfter swap a=%d b=%d", a, b);
return 0;
}
Run Code
By using * and /:
Let’s see another example to swap two numbers using * and /.
#include <stdio.h>
int main()
{
int a = 10, b = 20;
printf("Before swap a=%d b=%d", a, b);
a = a * b; // a=200 (10*20)
b = a / b; // b=10 (200/20)
a = a / b; // a=20 (200/10)
printf("\nAfter swap a=%d b=%d", a, b);
return 0;
}
Run Code
The output of the above program remains the same.
Before swap a=10 b=20
After swap a=20 b=10

Write a program to find the sum of digits of a given integer using recursion.

Solution
#include <stdio.h>
int sum (int a);
int main()
{
int num, result;
printf("Enter the number: ");
scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}
int sum (int num)
{
if (num != 0){
return (num % 10 + sum (num / 10));
}else{
return 0;
}
}
Run Code
The output of the above program is

Enter the number: 123456


Sum of digits in 123456 is 21

Differentiate between constant and literals. Why do we need to define the type of data?

Solution
A literal is a value that is expressed as itself. For example, the number 25 or the string “Hello World”
are both literal.

A constant is a data type that substitutes a literal. Constants are useful in situations where

 a specific, unchanging value is to be used at various times during the software program

 you want to more easily understand the software code


A variable in a program can change its value during the course of execution of the program. A
constant retains the same value throughout the program.

For example, if you have a constant named PI that you’ll be using at various places in your program
to find the area, circumference, etc of a circle, this is a constant as you’ll be reusing its value. But
when you’ll be declaring it as:

const float PI = 3.141;


The 3.141 is a literal that you’re using. It doesn’t have any memory address of its own and just sits in
the source code whereas PI is a constant of decimal type. It has a memory address also.

Requirement of Data type in c:

Data types used in C language refer to an extensive system that we use to declare various types of
functions or variables in a program. Here, on the basis of the type of variable present in a program,
we determine the space that it occupies in storage, along with the way in which the stored bit pattern
will be interpreted.

A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.

Whenever we utilize a data type in a C program, we define the variables or functions used in it. We
do so because we must specify the type of data that is in use so that the compiler knows exactly what
type of data it must expect from the given program.

Write a program to find the second largest number in the given array of numbers.

Solution
#include <stdio.h>
void main()
{
int i, j, a, n, counter, ave, number[30];
printf("Enter the value of N: ");
scanf("%d", &n);
printf("Enter the numbers:\n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The 2nd largest number is = %d\n", number[1]);
}
Run Code
The output of the above program is

Enter the value of N: 5


Enter the numbers:
1
3
10
8
9
The 2nd largest number is = 9

Create a structure “Employee” having Name, Address, Salary, and Age as member functions. Display
the name of the employee having aged between 40 and 50 are living in Kathmandu.

Solution
#include <stdio.h>
#include <string.h>
struct Employee{
char Name[100];
char Address[500];
int Salary;
int Age;
};
int main(){
int size, i, compare = 0;
printf("Enter number of Employee: ");
scanf("%d", &size);
struct Employee emp[size];
printf("\nEnter Employee Details:\n");
for(i=0; i < size; i++){
printf("\n\nEnter %d employee record:\n", i);
printf("Enter Name: ");
scanf(" %s", emp[i].Name);
printf("Enter Address: ");
scanf(" %s", emp[i].Address);
printf("Enter Age: ");
scanf(" %d", &emp[i].Age);
printf("Enter Salary: ");
scanf(" %d", &emp[i].Salary);
}
/** Print Employee with condition*/
printf("\n\nAll the employee of Kathmandu between age 40 and 50 are: \n");
for( i = 0; i < size; i++ ){
compare = strcmp(emp[i].Address, "Kathmandu");
if( compare == 0 ){
if( emp[i].Age >= 40 && emp[i].Age <= 50 ){
printf("%s\n", emp[i].Name);
}
}
}
return 0;
}
Run Code
The output of the above program is

Enter number of Employee: 4


Enter Employee Details:
Enter 0 employee record:
Enter Name: Suresh
Enter Address: Kathmandu
Enter Age: 45
Enter Salary: 450
Enter 1 employee record:
Enter Name: Julian
Enter Address: Dang
Enter Age: 46
Enter Salary: 230
Enter 2 employee record:
Enter Name: Lalit
Enter Address: Kathmandu
Enter Age: 56
Enter Salary: 560
Enter 3 employee record:
Enter Name: Rajesh
Enter Address: Nepal
Enter Age: 34
Enter Salary: 120
All the employee of Kathmandu between age 40 and 50 are:
Suresh

List any one advantage and disadvantage of the pointer. How do you pass pointers as function
arguments?

Solution
One advantage and disadvantage of the pointer is

Note: We have added many pointer advantages and disadvantages but you have to answer
according to the question.

Advantage:

 Pointers provide direct access to memory

 Pointers provide a way to return more than one value to the functions

 Reduces the storage space and complexity of the program


 Reduces the execution time of the program

 Provides an alternate way to access array elements

 Pointers can be used to pass information back and forth between the calling function and
called function.

 Pointers allow us to perform dynamic memory allocation and deallocation.

 Pointers help us to build complex data structures like a linked list, stack, queues, trees, graphs,
etc.

 Pointers allow us to resize the dynamically allocated memory block.

 Addresses of objects can be extracted using pointers

Disadvantage:

 Uninitialized pointers might cause segmentation faults.

 A dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to a


memory leak.

 Pointers are slower than normal variables.

 If pointers are updated with incorrect values, it might lead to memory corruption.

Pass pointer as function argument:

Just like any other argument, pointers can also be passed to a function as an argument. Let’s take an
example to understand how this is done.

In this example, we are passing a pointer to a function. When we pass a pointer as an argument
instead of a variable then the address of the variable is passed instead of the value. So any change
made by the function using the pointer is permanently made at the address of a passed variable. This
technique is known as call by reference in C.

Example:

This is one of the most popular examples that show how to swap numbers using call-by-reference.

#include <stdio.h>
void swapnum(int *num1, int *num2)
{
int tempnum;
tempnum = *num1;
*num1 = *num2;
*num2 = tempnum;
}
int main( )
{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
/*calling swap function*/
swapnum( &v1, &v2 );
printf("\nAfter swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
}
Run Code
The output of the above program is

Before swapping:
Value of v1 is: 11
Value of v2 is: 77
After swapping:
Value of v1 is: 77
Value of v2 is: 11

Suppose a file named “[Link]” contains a list of integers. Write a program to extract the prime
numbers only from that file and write them on “[Link]” file.

Solution
Program to read prime numbers from file “[Link]” and write it to “[Link]” file is

#include <stdio.h>
int is_prime(int);
int main(){
FILE* ptr;
ptr = fopen("[Link]", "r");
FILE* fp;
fp = fopen("[Link]", "a+");
if (NULL == ptr) {
printf("File can't be opened \n");
return 0;
}
int num;
printf("\nPrime number in files are:\n");
while (fscanf(ptr, "%d", &num) != EOF){
if( is_prime( num ) ){
printf("%d\n", num);
fprintf(fp, "%d ", num);
}
}
return 0;
}
int is_prime( int n ){
if( n == 1 ){
return 0;
}
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}

What is the advantage of the union over structure? List any four-string library functions with the
prototype.

Solution
The advantage of the union over the structure are

 It occupies less memory compared to the structure.

 When you use union, only the last variable can be directly accessed.

 Union is used when you have to use the same memory location for two or more data
members.

 It enables you to hold data of only one data member.

 Its allocated space is equal to the maximum size of the data member.

Any four string library functions are:

1. strlen():

The strlen() function returns the length of the given string. It doesn’t count null character ‘\0’.

Syntax:

strlen(string_name)
2. strcpy():

The strcpy(destination, source) function copies the source string in destination.

Syntax:

strcpy(destination, source)
3. strcmp():

The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are
equal.

Syntax:

strcmp(first_string, second_string)
4. strrev():

The strrev(string) function returns reverse of the given string.

Syntax:

strrev(string)
Write short notes on

a. Local, Global, and Static variables


b. Conditional Operator

Solution
a) Local, Global and Static variable:

The variables which are declared inside the function, compound statement (or block) are called Local
variables.

void function_1()
{
int a, b; // you can use a and b within braces only
}
void function_2()
{
printf("%d\n", a); // ERROR, function_2() doesn't know any variable a
}
The variables declared outside any function are called global variables. They are not limited to any
function. Any function can access and modify global variables. Global variables are automatically
initialized to 0 at the time of declaration. Global variables are generally written before main() function.

int a, b;
int main(){
a=5;
b=6;
sum();
}
int sum(){
printf("%d", a + b);
}
Here a and b are global variables that can be accessed by the sum function also.

A Static variable is able to retain its value between different function calls. The static variable is only
initialized once, if it is not initialized, then it is automatically initialized to 0. Here is how to declare a
static variable.

b) Conditional Operator:
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements that depend upon the output of the expression. It is represented by two
symbols, i.e., ‘?’ and ‘:’.

As a conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the ‘if-else’ statement as the ‘if-else’ statement is
also a decision-making statement.

Syntax:

Expression1 ? expression2 : expression3;


Example:

#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
return 0;
}
Run Code
In the above code, we are taking input as the ‘age’ of the user. After taking input, we have applied the
condition by using a conditional operator. In this condition, we are checking the age of the user. If the
age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf(“eligible for
voting”)) otherwise, statement2 will execute, i.e., (printf(“not eligible for voting”)).

2080

Define structure and nested structure. Write a program to find out whether the nth term of the
Fibonacci series is a prime number or not. Read the value of n from the user and display the result in
the main function. Uses separate user-defined function to generate the nth Fibonacci term and to
check whether that number is prime or not.

Solution
In C, a structure is a user-defined data type that allows you to group different types of variables
under a single name. It is a way to organize data. For example:
struct Point {
int x;
int y;
};

A nested structure in C is a structure that is a member of another structure. This allows you to
create more complex data structures. For example:

struct Address {
char city[50];
char state[50];
};

struct Person {
char name[50];
int age;
struct Address address;
};

Program

#include <stdio.h>

// Function to generate the nth Fibonacci term


int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n – 1) + fibonacci(n – 2);
}
}

// Function to check whether a number is prime


int isPrime(int num) {
if (num <= 1) {
return 0; // Not a prime number
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // Not a prime number
}
}
return 1; // Prime number
}

int main() {
int n, nthTerm;

// Read the value of n from the user


printf(“Enter the value of n: “);
scanf(“%d”, &n);
// Generate the nth Fibonacci term
nthTerm = fibonacci(n);

// Check if the nth term is a prime number


if (isPrime(nthTerm)) {
printf(“%dth term of Fibonacci series (%d) is a prime number.\n”, n, nthTerm);
} else {
printf(“%dth term of Fibonacci series (%d) is not a prime number.\n”, n, nthTerm);
}

return 0;
}

Explain the relation to array and pointer. Differentiate call by value and call by reference with a
suitable program.

Solution
Relation to Array and Pointer:

In C, arrays and pointers have a close relationship. An array name is essentially a constant pointer to
the first element of the array. Consider the following example:

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};

// Using array notation


printf(“Using array notation: %d\n”, arr[2]);

// Using pointer notation


printf(“Using pointer notation: %d\n”, *(arr + 2));

return 0;
}

In this example, arr is an array, and arr itself represents the address of the first element. The
expression arr[2] is equivalent to *(arr + 2). Both statements print the third element of the array.

Arrays and pointers also become more intertwined when passing them to functions. When you pass
an array to a function, you’re effectively passing a pointer to the first element of the array.

#include <stdio.h>

// Function to modify array elements


void modifyArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};

// Passing array to a function


modifyArray(arr, 5);

// Displaying modified array


for (int i = 0; i < 5; i++) {
printf(“%d “, arr[i]);
}

return 0;
}

In this program, modifyArray takes a pointer to an integer (int *arr) and modifies the elements of the
array passed to it. This is possible because the array is effectively passed as a pointer.

Call by Value and Call by Reference:

In C, function arguments can be passed in two ways: call by value and call by reference.

Call by Value:

In call by value, the actual value of the variable is passed to the function. Modifications made to the
parameter inside the function do not affect the original variable outside the function.

#include <stdio.h>

// Function using call by value


void increment(int num) {
num++;
}

int main() {
int x = 5;

// Passing x by value
increment(x);

// x remains unchanged
printf(“Value of x: %d\n”, x);

return 0;
}

Call by Reference:
In call by reference, the address of the variable is passed to the function using pointers. Modifications
made to the parameter inside the function affect the original variable.

#include <stdio.h>

// Function using call by reference


void incrementByReference(int *num) {
(*num)++;
}

int main() {
int x = 5;

// Passing address of x
incrementByReference(&x);

// x is modified
printf(“Value of x: %d\n”, x);

return 0;
}

Differentiate between source code and object code. Create a structure named Book with members
Book_Name, Price and Author_Name, then take input for 10 records of Book and print the name of
authors having the price of book greater than 1000.

Solution
Source Code vs Object Code

Source Code Object Code

Machine-readable, binary representation of the


Human-readable form of a program written in a
program generated by the compiler from the source
programming language like C, C++, Java, etc.
code.

The code that programmers write using a text


Intermediate form before the final step of creating an
editor or an integrated development
executable file.
environment (IDE).
Not human-readable and is specific to the target
Contains high-level instructions and is written in
architecture or platform for which the program is
a syntax that is understandable to programmers.
compiled.

Generated after the compilation process and may


Has file extensions like .c, .cpp, .java, etc.
have file extensions like .obj, .o, or .class.

Program

#include <stdio.h>

// Define the structure named Book


struct Book {
char Book_Name[50];
float Price;
char Author_Name[50];
};

int main() {
// Declare an array of Book to store 10 records
struct Book books[10];

// Input data for 10 records


for (int i = 0; i < 10; i++) {
printf(“Enter details for Book %d:\n”, i + 1);
printf(“Book Name: “);
scanf(“%s”, books[i].Book_Name);
printf(“Price: “);
scanf(“%f”, &books[i].Price);
printf(“Author Name: “);
scanf(“%s”, books[i].Author_Name);
}

// Print names of authors with the price greater than 1000


printf(“\nAuthors with the price of the book greater than 1000:\n”);
for (int i = 0; i < 10; i++) {
if (books[i].Price > 1000) {
printf(“%s\n”, books[i].Author_Name);
}
}

return 0;
}
Describe the different types of I/O functions used in file handling with syntax.

Solution
There are different types of I/O functions used in file handling, and they are categorized into two main
types: formatted I/O functions and unformatted I/O functions.

Formatted I/O Functions:

Formatted I/O functions are used for reading and writing data in a formatted way, where the format is
specified using format specifiers. The most commonly used formatted I/O functions for file handling in
C are fprintf, fscanf, printf, and scanf.

 fprintf: int fprintf(FILE *stream, const char *format, …);

 fscanf: int fscanf(FILE *stream, const char *format, …);

 printf: int printf(const char *format, …);

 scanf: int scanf(const char *format, …);

Unformatted I/O Functions:

Unformatted I/O functions are used for reading and writing data as raw bytes without any formatting.
The commonly used unformatted I/O functions for file handling in C are fread, fwrite, fgetc, fputc,
fgets, and fputs.

 fread: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

 fwrite: size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

 fgetc: int fgetc(FILE *stream);

 fputc: int fputc(int c, FILE *stream);

 fgets: char *fgets(char *s, int size, FILE *stream);

 fputs: intfputs(const char *s, FILE *stream);

Example:

#include <stdio.h>

int main() {
FILE *file;
char text[100];

// Writing to a file using fprintf


file = fopen(“[Link]”, “w”);
fprintf(file, “Hello, this is a sample text.\n”);
fclose(file);

// Reading from a file using fscanf


file = fopen(“[Link]”, “r”);
fscanf(file, “%[^\n]”, text);
printf(“Content of the file: %s\n”, text);
fclose(file);

return 0;
}

Write a program to read P*Q matrix of integers and find the largest integer of each row and display it.

Solution
#include <stdio.h>

int main() {
int P, Q;

// Read the dimensions of the matrix


printf(“Enter the number of rows (P): “);
scanf(“%d”, &P);

printf(“Enter the number of columns (Q): “);


scanf(“%d”, &Q);

// Check for valid dimensions


if (P <= 0 || Q <= 0) {
printf(“Invalid dimensions. Exiting.\n”);
return 1;
}

int matrix[P][Q];

// Read the matrix elements


printf(“Enter the elements of the matrix:\n”);
for (int i = 0; i < P; i++) {
for (int j = 0; j < Q; j++) {
printf(“Enter element at position (%d, %d): “, i + 1, j + 1);
scanf(“%d”, &matrix[i][j]);
}
}
// Find and display the largest integer in each row
printf(“\nLargest integers in each row:\n”);
for (int i = 0; i < P; i++) {
int max = matrix[i][0];

for (int j = 1; j < Q; j++) {


if (matrix[i][j] > max) {
max = matrix[i][j];
}
}

printf(“Row %d: %d\n”, i + 1, max);


}

return 0;
}

Write a program to calculate the factorial of a given number using recursion.

Solution
#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n – 1);
}
}

int main() {
int num;

// Read the number from the user


printf(“Enter a non-negative integer: “);
scanf(“%d”, &num);

// Check for a non-negative integer


if (num < 0) {
printf(“Please enter a non-negative integer.\n”);
return 1;
}

// Calculate and display the factorial


printf(“Factorial of %d = %d\n”, num, factorial(num));

return 0;
}

Write a program to check whether the entered word is pallindrome or not.

Solution
#include <stdio.h>
#include <string.h>

// Function to check if a word is a palindrome


int isPalindrome(char word[]) {
int length = strlen(word);

// Compare characters from both ends towards the center


for (int i = 0; i < length / 2; i++) {
if (word[i] != word[length – i – 1]) {
return 0; // Not a palindrome
}
}

return 1; // Palindrome
}

int main() {
char word[100];

// Read the word from the user


printf(“Enter a word: “);
scanf(“%s”, word);

// Check if the word is a palindrome


if (isPalindrome(word)) {
printf(“%s is a palindrome.\n”, word);
} else {
printf(“%s is not a palindrome.\n”, word);
}
return 0;
}

List different types of operators and explain any three of them.

Solution
In C programming, operators are symbols that perform operations on operands. Here are different
types of operators in C:

Arithmetic Operators:

+ (addition), – (subtraction), * (multiplication), / (division), % (modulo, gives the remainder).

int a = 10, b = 3;
int sum = a + b; // Addition
int difference = a – b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulo

Relational Operators:

== (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater
than or equal to).

int x = 5, y = 10;
if (x == y) {
// Equality check
}
if (x != y) {
// Not equal check
}
if (x < y) {
// Less than check
}
if (x > y) {
// Greater than check
}
if (x <= y) {
// Less than or equal to check
}
if (x >= y) {
// Greater than or equal to check
}
Logical Operators:

&& (logical AND), || (logical OR), ! (logical NOT).

int a = 1, b = 0;
if (a && b) {
// Logical AND: true if both a and b are true
}
if (a || b) {
// Logical OR: true if either a or b is true
}
if (!a) {
// Logical NOT: true if a is false
}

Other types of operators include assignment operators, bitwise operators, conditional (ternary)
operators, increment and decrement operators, and more.

Trace the output

#include<conio.h>

#include<stdio.h>

void main(){

int i =0,k;

for(k=5;k>=0;k–){

i=i+k;

printf(“%d\t”,i);

getch();

Solution
Iteration 1: i = 0 + 5 = 5
Iteration 2: i = 5 + 4 = 9
Iteration 3: i = 9 + 3 = 12
Iteration 4: i = 12 + 2 = 14
Iteration 5: i = 14 + 1 = 15
Iteration 6: i = 15 + 0 = 15

Final value of i: 15

Write a program to compute the sum of first 10 even numbers using function.

Solution
#include <stdio.h>

// Function to compute the sum of the first n even numbers


int sumOfEvenNumbers(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
// Formula to find the nth even number: 2 * n
int evenNumber = 2 * i;
sum += evenNumber;
}
return sum;
}

int main() {
// Calculate the sum of the first 10 even numbers using the function
int result = sumOfEvenNumbers(10);

// Display the result


printf(“Sum of the first 10 even numbers: %d\n”, result);

return 0;
}

What is dynamic memory allocation? Explain with a suitable program.

Solution
Dynamic memory allocation is a process in which memory is allocated or deallocated during the
execution of a program. Unlike static memory allocation, where the size of memory is determined at
compile-time, dynamic memory allocation allows the program to allocate memory at runtime. In C,
dynamic memory allocation is achieved using functions like malloc, calloc, realloc, and free from the
<stdlib.h> library.

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

int main() {
int n;

// Read the number of elements from the user


printf(“Enter the number of elements: “);
scanf(“%d”, &n);

// Dynamically allocate memory for an integer array


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

// Check if memory allocation is successful


if (arr == NULL) {
printf(“Memory allocation failed. Exiting.\n”);
return 1;
}

// Input values into the dynamically allocated array


printf(“Enter %d elements:\n”, n);
for (int i = 0; i < n; i++) {
scanf(“%d”, &arr[i]);
}

// Display the elements of the dynamically allocated array


printf(“Elements of the array are: “);
for (int i = 0; i < n; i++) {
printf(“%d “, arr[i]);
}

// Dynamically deallocate the allocated memory


free(arr);

return 0;
}
Write a program to initialize an array of dimension 10 and sort the numbers within the array in
ascending order.

Solution
#include <stdio.h>

// Function to perform ascending order sorting


void sortArray(int arr[], int size) {
for (int i = 0; i < size – 1; i++) {
for (int j = 0; j < size – i – 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
// Initialize an array of dimension 10
int numbers[10] = {9, 3, 5, 1, 7, 2, 8, 4, 6, 10};

// Calculate the size of the array


int size = sizeof(numbers) / sizeof(numbers[0]);

// Display the original array


printf(“Original array: “);
for (int i = 0; i < size; i++) {
printf(“%d “, numbers[i]);
}
printf(“\n”);

// Sort the array in ascending order


sortArray(numbers, size);

// Display the sorted array


printf(“Sorted array in ascending order: “);
for (int i = 0; i < size; i++) {
printf(“%d “, numbers[i]);
}
printf(“\n”);

return 0;
}
2081(new)

List different types of operators and explain any four of them.

Solution
C has a rich set of operators which can be classified as:

1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

Any four of the operators are defined below as:

Arithmetic Operator:
Arithmetic operators are those that carry out mathematical operations such as modulo, addition,
subtraction, multiplication, and division.
List of Arithmetic Operator:

 + (Addition)

 – (Subtraction)

 * (Multiplication)

 / (Division)

 % (Modulo)

Relational operators:
Relational operators return a Boolean value (true or false) based on a comparison between two
operands.
List of Arithmetic Operator:

 == (Equal to)

 != (Not equal to)

 > (Greater than)

 < (Less than)


 >= (Greater than or equal to)

 <= (Less than or equal to)

Logical Operators:
These operators are used to combine multiple Boolean expressions.
List of Logical Operator:

 && (Logical AND)

 || (Logical OR)

 ! (Logical NOT)

Bitwise Operators: These operators perform operations on individual bits of data.


List of Bitwise Operator:

 & (Bitwise AND)

 | (Bitwise OR)

 ^ (Bitwise XOR)

 ~ (Bitwise NOT)

 << (Left shift)

 >> (Right shift)

What are the characteristics of array? Write a program to input age of 500 persons and display the
following

a. Average age
b. Age between 25 to 30

Solution
Arrays are basic computer data structures that hold a group of elements, usually of the same kind.
The following are the main attributes of arrays:

1. Fixed Size: An array’s size is fixed at construction and cannot be altered while it is being used.
2. Contiguous Memory Allocation: Arrays are kept in memory in contiguous areas. This implies
that the components are kept in memory sequentially, facilitating effective access and
modification.
3. Index-Based Access: An index can be used to access elements in an array. In majority of
programming languages, the index typically begins at 0.
4. Same Type of Elements: An array can only contain elements of the same kind, such as all
strings, all float or all integers.

Program part:

Program to input age of 500 persons and display the Average age, Age between 25 to 30.

#include <stdio.h>
int main() {
int ages[500];
int i;
int count = 0;
float sum = 0.0;
float average_age;
for (i = 0; i < 500; i++) {
printf("Enter age for person %d: ", i + 1);
scanf("%d", &ages[i]);
while (ages[i] < 0) {
printf("Please enter a valid age (0 or greater): ");
scanf("%d", &ages[i]);
}
sum += ages[i];
}
average_age = sum / 500;
for (i = 0; i < 500; i++) {
if (ages[i] >= 25 && ages[i] <= 30) {
count ++;
}
}
printf("\nAverage age: %.2f\n", average_age);
printf("Number of persons aged between 25 and 30: %d\n", count);
return 0;
}
Explain the basic structure of C Programming.

Solution

fig : Structure of C

Structure of C is defined below as:

 Documentation section: This section contains comments that explain what the program
does.

 link section: This section contains header files, which are libraries that provide pre-written
functions and macros.

 definition section: This section contains data types and variables declared.
 Global declaration section: This section contains declarations for the variables that are
accessible from anywhere in the program.

 main () function section: This section contains the main function, which is the entry point of
the program.

 Declaration part: This part contains declarations of variables and functions that are
used in the executable part.

 Executable part: This part contains the actual code that is executed by the program.

 User defined function section: This section contains user-defined functions that can be
called from other parts of the program. function 1, function 2 …. function n are the user defined
functions.

This structure allows you to organize your C code into a logical and easy-to-read format.

Write a program to display first 50 prime numbers.

Solution
#include <stdio.h>
int main() {
int i, j, count = 0;
for (i = 2; count < 50; i++) {
int isPrime = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("%d ", i);
count++;
}
}
return 0;
}
Demonstrate the use of recursive function with a suitable example.

Solution
A function that invokes itself inside its own specification is known as a recursive function. It may be
used to issues that can be divided into more manageable, related subissues.

#include <stdio.h>
int factorial(int n);
int main() {
int num;
printf("Enter the number whose factorial you want to get: ");
scanf("%d",&num);
int result = factorial(num);
printf("Factorial of %d is %d\n", num, result);
return 0;
}
int factorial(int n) {
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}

Explain different file opening modes.

Solution
Openings Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file


R Open for reading If the file does not exist, fopen() returns NULL

Rb Open for reading in binary mode If the file does not exist, fopen() returns NULL

If the file exists, its contents are overwritten. If the


W Open for reading
file does not exist, it will created

If the file exists, its contents are overwritten. If the


Wb Open for writing in binary mode
file does not exist, it will created

Open for append. Data is added to the


A If the file does not exist, if will be created.
end of the file.

Open for append in binary mode. Data


Ab If the file does not exist, it will be created
is added to the end of the file.

r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.

Open for both reading and writing in


rb+ If the file does not exist, fopen() returns NULL.
binary mode.

If the file exists, its contents are overwritten. If the


w+ Open for both reading and writing
file does not exist, it will be created.

Open for both reading and writing in If the file exists, its contents are overwritten. If the
wb+
binary mode. file does not exist, it will be created.

a+ Open for both reading and appending. If the file does not exist, it will be created.

Open for both reading and appending in


ab+ If the file does not exist, it will be created.
binary mode.
Describe different formatted input and output functions. Why do we use them?

Solution
Formatted Input/ Output:
These functions are used to read numbers, character or string from a file or write them to a file in
format as our requirement.

Formatted Input : These functions read input in a structured format.

1. scanf()
It takes input from the keyboard, which is the typical input. It controls data reading by using
format specifiers.
example:int num;
scanf(“%d”, &num);
2. fscanf()
It reads input from a file that has been formatted. Though it needs a file reference, it is
comparable to scanf().
example:FILE *fp = fopen(“[Link]”, “r”);
int num;
fscanf(fp, “%d”, &num);
fclose(fp);

Formatted Output: These functions display output in a structured format.

1. printf(): Prints formatted output to the standard output (screen).


example:int num = 10;
printf(“The number is %d\n”, num);
2. fprintf()
It is formatted output function which is used to write integer , float, char or string data to a file.
example:FILE *fp = fopen(“[Link]”, “w”);
fprintf(fp, “Number: %d”, 10);
fclose(fp);

We use Formatted Input/Output functions for following reasons:

 Type-Specific Handling :
It uses format specifiers (such as %d for integers) to make that the right data types are read or
shown, avoiding errors caused by mismatched types.

 Effective output formatting:


It arranges output in a comprehensible manner, enabling data display that is well-aligned and
enhances user understanding of the content.

 Adaptable Input Management:


It increases program adaptability by enabling the use of functions like scanf and fscanf to read
data from several sources (console, files).

 Write a program to draw two shapes of your choice using graphics function.

 Solution
 Program to draw a circle.

 #include<stdio.h>
 #include<conio.h>
 #include<graphics.h>
 int main()
 {
 int gd=DETECT,gm;
 char txt [20];
 intitgraph(&gd, &gm, "c:");
 circle(200,200,50);
 getch();
 closegraph();
 return 0:
 }
 Program to draw a hexagon.

 #include<stdio.h>
 #include<conio.h>
 #include<graphics.h>
 int main ()
 {
 int gdriver = DETECT, gmode;
 int poly [] = {10,75,50,25,100,25,140,75,100125,50,125,10,75};
 intgraph(&gdriver, &gmode, "c:\\tc\\bgi");
 drawpoly(7,poly);
 illpoly(7, poly);
 closegraph ();
 return 0;
 }
Write a program to display the following series up to 25 terms but do not print the 7th term. 2 x 3, 3 x
5, 4 x 7, 5 x 9…

Solution
Program to display the following series up to 25 terms but not to print the 7th term in the series 2 x 3,
3 x 5, 4 x 7, 5 x 9…

#include <stdio.h>
int main() {
int i, first = 2, second = 3;
for (i = 1; i <= 25; i++) {
if (i == 7) {
printf("\t");
first++;
second += 2;
continue;
}
printf("%d x %d", first, second);
if (i < 25) {
printf(", ");
}
first++;
second += 2;
}
return 0;
}

Write short notes on:

a. Global variable
b. Debugging

Solution
a. Global variable :
A variable that may be accessed from anywhere in a program, independent of the scope in
which it was declared, is called a global variable. If a global variable is defined, then any
function or block of code in the program can use and change it.

int a, b;

int main(){

a=5;

b=6;

sum();

int sum(){

printf("%d", a + b);

Here a and b are global variables that can be accessed by the sum function also.

b. Debugging:
The process of locating, separating, and resolving issues or “bugs” in a computer program or
system is known as debugging. Syntax problems, logical flaws, runtime errors, and
unexpected behavior brought on by erroneous assumptions about how the code should work
are just a few of the many possible causes of bugs. Once the source of the problem is
identified, the developer modifies the code to fix the issue and then tests the program to
ensure that the bug is resolved and that no new issues have been introduced.

You might also like