C Program All Model Question Solved
C Program All Model Question Solved
2074
Solution
Any C program is consists of 6 sections. Below you will find brief explanation of each of them.
Documentation Section
Link Section
Definition 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
*/
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
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.
int a=7;
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
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
#include<stdio.h>
#define PI 3.142
int main(){
float r;
scanf("%f", &r);
return 0;
float area(float r) {
return PI * r * r;
if statement
if….else statement
else…..if 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(){
if(num % 2 == 0){
printf("Number is Even\n");
return 0;
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(){
if(num % 2 == 0)
printf("Number is Even\n");
else
printf("Number is Odd\n");
return 0;
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(){
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;
Number is Odd
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;
int main(){
if(num % 2 == 0)
if(num > 5 == 0)
}else{
else
printf("Number is Odd\n");
return 0;
Source: [Link]
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.
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.
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
ARRAY STRUCTURE
Array uses subscripts or “[ ]” (square bracket) for Structure uses “.” (Dot operator) for element
element access access
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
Array declaration is done simply using [] and not Structure declaration is done with the help of
any keyword. “struct” keyword.
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(){
int n, i;
scanf("%d", &n);
for( i = 0; i < n; i++ ){
printf("%s\n", s[i].name);
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.
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.
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.
SN Algorithm Flowchart
Algorithm is complex to
2. Flowchart is easy to understand.
understand.
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.
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
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;
printf("%c", x);
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;
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.
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;
#include<stdio.h>
int main()
int x = 12, y = 1;
return 0;
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++;
y = x--;
#include<stdio.h>
int main()
int x = 12, y = 1;
return 0;
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()
scanf("%d", &num);
while(num!=0)
return 0;
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.
9. Write a program to find sum and average of 10 integer numbers stored in an array.
Solution
#include <stdio.h>
int main()
float avg;
scanf("%d", &n);
scanf("%d", &array[i]);
avg = (float)sum / n;
return 0;
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.
data_type *pointer;
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;
return 0;
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
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,
…
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)
exit(0);
printf("%c", ch);
fclose(fp);
return 0;
Solution
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.
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()
{
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.
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
Flowchat
Example:
#include <stdio.h>
int main(){
// This statement would be executed repeatedly until the condition i<=10 returns false.
return 0;
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
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){
i++;
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
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{
num++;
}while(i<=10);
return 0;
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.
1. In array, We can access the data very easily using index number
4. We can used to implement other data structure like linked lists, stack, queue, trees, graph etc.
#include <stdio.h>
int main()
scanf("%d", &r);
scanf("%d", &c);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
scanf("%d", &b[i][j]);
if (j == c - 1)
printf("\n\n");
return 0;
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.
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 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.
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(){
char c;
exit(0);
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;
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:
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
if ( a || b ) {
a = 0;
b = 10;
if ( a && b ) {
} else {
if ( !(a && b) ) {
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;
#include <stdio.h>
int main(){
int x;
if( x == 5)
break;
return 0;
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
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.
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.
Solution
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
if(num % 2 == 0)
else
return 0;
Enter an integer: -7
-7 is odd.
Solution
#include<stdio.h>
int main(){
int i, sum=0;
sum += i;
printf("sum=%d", sum);
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:
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.
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 AGE 10
int main(){
return 0;
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
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:
#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.
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
#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]);
}
Solution
Backup: possible to take faster and automatic back-up of database stored in files of computer-
based systems
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
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 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.
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.
Returns true if
keyboard is hit.
kbhit() This is useful for
interactive
graphics.
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.
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
The statement is executed after the condition is The statement is executed at least once, then after the
checked. condition is checked.
While loop is entry controlled loop. Do while loop is exit controlled loop.
#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
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).
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
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.
#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
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.
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.
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
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.
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.
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.
1. Int
Data types that holds integer value
2. Float
Data types that holds floating-point value
2. Char
Data types that holds character such as ‘a’, ‘b’, ‘C’ etc.
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.
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.
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.
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
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
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.
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.
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()
fclose(fptr);
3. getc()
It is used to read the character from the file
Syntax
Syntax:
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
6. fputs()
It is used to write a string to file
Syntax:
7. fgets()
It is used to read a line
Syntax
char str[60];
fgets (str, 60, fp)
Solution
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.
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 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
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:
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.
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.
Part Remark
#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:
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
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
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
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:
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
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
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 a way to return more than one value to the functions
Pointers can be used to pass information back and forth between the calling function and
called function.
Pointers help us to build complex data structures like a linked list, stack, queues, trees, graphs,
etc.
Disadvantage:
If pointers are updated with incorrect values, it might lead to memory corruption.
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
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.
Its allocated space is equal to the maximum size of the data member.
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():
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():
Syntax:
strrev(string)
Write short notes on
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:
#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>
int main() {
int 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};
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>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
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.
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>
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>
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
Program
#include <stdio.h>
int main() {
// Declare an array of Book to store 10 records
struct Book books[10];
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 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.
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);
Example:
#include <stdio.h>
int main() {
FILE *file;
char text[100];
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;
int matrix[P][Q];
return 0;
}
Solution
#include <stdio.h>
int main() {
int num;
return 0;
}
Solution
#include <stdio.h>
#include <string.h>
return 1; // Palindrome
}
int main() {
char word[100];
Solution
In C programming, operators are symbols that perform operations on operands. Here are different
types of operators in C:
Arithmetic Operators:
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:
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.
#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>
int main() {
// Calculate the sum of the first 10 even numbers using the function
int result = sumOfEvenNumbers(10);
return 0;
}
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;
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>
int main() {
// Initialize an array of dimension 10
int numbers[10] = {9, 3, 5, 1, 7, 2, 8, 4, 6, 10};
return 0;
}
2081(new)
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
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)
Logical Operators:
These operators are used to combine multiple Boolean expressions.
List of Logical Operator:
|| (Logical OR)
! (Logical NOT)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
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
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.
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);
}
}
Solution
Openings Modes in Standard I/O
Rb Open for reading in binary mode If the file does not exist, fopen() returns NULL
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
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.
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.
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);
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.
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;
}
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.