Programming in c Dod Question Bank
Programming in c Dod Question Bank
Programming In C
Question Bank
Winter 19
2 marks
2
• Find the output of the following program:
#include
void main( )
{
int x = 10, y = 10, v1, v2;
v1 = x++;
v2 = ++y;
printf(“value of v1: %d, v1);
printf(“value of v2: %d, v2);
}
Output:
value of v1:10value of v2:11
== - returns true if the values of two operands are equal else returns false.
E.g: if (A= = B){ }
!= - returns true if values of two operands are not equal, else returns false
E.g: if (A! = B){ }
<- returns true if the first operand is less than the second, else returns false.
E.g: if (A< B){ }
>- returns true if the first operand is greater than the second, else returns false.
E.g: if (A> B){ }
<= returns true if the first operand is less than or equal to the second, else returns false.
E.g: if (A< = B){ }
>= returns true if the first operand is greater than or equal to the second, else returns false.
3
E.g: if (A> = B){ }
-can be used to quickly communicate the ideas or plans that one programmer envisions to other people
who will be involved in the process.
- aid in the analysis of the process to make sure nothing is left out and that all possible inputs, processes,
and outputs have been accounted for.
4
-help programmers develop the most efficient coding because they can clearly see where the data is
going to end up.
- help programmers figure out where a potential problem area is and helps them with debugging or
cleaning up code that is not working.
- are a useful tool in visualizing a module's flow of execution before writing any code. This allows
developers to do three things:
(i) verify the algorithm's correctness before writing code
(ii) visualize how the code will ultimately be written
(iii) and communicate and document the algorithm with other developers and even non-developers.
-may be used in conjunction with other tools, such as pseudo-code, or may be used by itself to
communicate a module's ultimate design, depending on the level of detail of the flowchart.
• Write a program to declare structure student having rollno, name & marks.
(Note: Any other correct logic shall be considered). Accept and display data for three
students.
• Explain pointer arithmetic with example. (Note: Code snippet shall be considered).
The pointer arithmetic is done as per the data type of the pointer.
The basic operations on pointers are:
Increment It is used to increment the pointer. Each time a pointer is incremented, it points to the next
location.
Eg, for an int pointer variable, if the current position of pointer is 1000, when incremented it points to
1002 because for storing an int value it takes 2 bytes of memory. Decrement It is used to decrement the
pointer. Each time a pointer is decremented, it points to the previous location.
Eg, if the current position of pointer is 1002, then decrement operation results in the pointer pointing to
the location 1000.
5
Addition and subtraction:
When addition or subtraction operation is performed on the pointer variable, it shows that particular
location in the memory.
Eg:
int *ptr; -say address is 1000.
If -> ptr+n- then ptr+n*2 .
If -> ptr-n thenptr-n*2.
#include
#include
void main()
{
int i = 10;
int *ptr=&i;
clrscr();
printf("%x%d",ptr,i);
ptr++;
printf("\n%x%d",ptr,i);
printf("\n%x",ptr+2);
printf("\n%x",ptr-2);
getch();
}
• Explain nested if-else with example. (Note: Any example shall be considered)
When a series of decision is required, nested if-else is used. Nesting means using one if-else construct
within another one. If the condition in the outer if, is true, then only the inner if-else will get executed.
Further the statements in the inner if will get execute only if the condition of inner if, evaluates to true.
If it is false, the statements in inner else will get executed. If the outer if evaluates to false, then the
statements in outer else get executed.
General syntax:
if(condition)
{
if(condition)
{ statements }
else
{ statements }
} else
6
{ statements }
statements
Example:
#include
#include
void main()
{
int val;
clrscr();
printf("Enter a number");
scanf("%d",&val);
if(val>=5)
{
if(val>5)
{
printf("Number is greater than 5");
}
else
{
printf("Number is equal to 5");
}
}
else
{
printf("Number is less than 5");
}
getch();
}
7
Keyword: Keywords are special words in C programming which have their own predefined meaning. The
functions and meanings of these words cannot be altered.
Some keywords in C Programming are if, while, for, do, etc..
Identifier: Identifiers are user-defined names of variables, functions and arrays. It comprises of
combination of letters and digits.
Example
int age1;
float height_in_feet;
Here, age1 is an identifier of integer data type. Similarly height_feet is also an identifier but of floating
integer data type
Variable: A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.
Example:
add, a, name
Constant: Constants refer to fixed values that the program may not change during its execution. These
fixed values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are enumeration constants
as well.
Example:
121
234
3.14
8
• Explain conditional operator with example.
• List the categories of functions and explain any one with example.
Different categories of function:
9
1) Function with no arguments and no return value.
2) Function with arguments and no return value.
3) Function with no arguments and return value.
4) Function with arguments and return value.
10
{
inta,b,c;
a=5;
b=6;
c=a+b;
return(c);
}
It should be called as int x = add();
where x will store value returned by the function.
11
Summer 19
2 Marks
• Draw flowchart for checking whether given number is even or odd
• (b) List any four keywords used in ‘C’ with their use.
(any other relevant keyword in ‘C’ may be considered.)
12
13
• Write the syntax of switch case statement.
switch(variable)
{
case value1:
statements
break;
case value2:
statements;
break;
...
default:
statements;
break;
}
• State any two differences between while and do-while statement. (Note: Any 2 points
shall be considered).
14
• State difference between array and string. (Note: Any two valid points shall be
considered).
struct student
{
int roll_no;
char name[20];
};
• Distinguish between call by value and call by reference. (Note: Any two points shall be
considered).
15
Winter 18
2 Marks
• Define Algorithm
“math.h” header file supports all the mathematical related functions in C language.
stdio.h header file is used for input/output functions like scanf and printf
if(condition_expression_One)
{
statement1;
}
else if (condition_expression_Two)
{
statement2;
}
16
else if (condition_expression_Three)
{
statement3;
}
else
{
statement4;
}
• Define Array.
An array is a collection of data items, all of the same type, accessed using a common name. A one-
dimensional array consists of similar type of multiple values in it. A two dimensional array consists of
row and column
Definition:
A pointer is a variable that stores memory address of another variable which is of similar data type.
Declaration:
datatype *pointer_variable_name;
17
Summer 18
2 Marks
• Define:
(i) Two dimensional array
(ii) (ii) Multi-dimensional array
o Two dimensional array Two dimensional array is a collection of similar type of data elements
arranged in the form of rows & columns.
E.g. Array can be declared as int arr[3][3]; In this there can be 9 elements in an array with 3
rows and 3 columns.
o Multi-dimensional array: An array with more than one dimension is called as multidimensional
array.
18
For example, float x[3][4]; Similarly, you can declare a three-dimensional (3d) array. For
example, float y[2][4][3];
Advantages of pointer:
1. Pointers reduce the length and complexity of a program.
2. They increase execution speed.
3. A pointer enables us to access a variable that is defined outside the function.
4. Pointers are more efficient in handling the data tables.
5. The use of a pointer array of character strings results in saving of data storage space in memory.
6. It supports dynamic memory management.
Definition type casting: The conversion of one data type to another is known as type casting. The values
are changed for the respective calculation only, not for any permanent effect in a program.
For example, x=int (7.5) means 7.5 is converted to integer by truncating it i.e. 7 b=(int) 22.7/(int) 5.3
means 22.7 will be converted to 22 and 5.3 to 5 so answer will be 22/5=4 c=(double) total/num means
the answer will be in float value. p=sin((int)x) means x will be converted to integer and then sine angle
will be calculated.
• State any four math functions with its use. (Note: Any other relevant math function shall
be considered)
Math Functions:
sqrt() - square root of an integer
abs() - absolute value of an integer
sin() - compute the sine value of an input value
19
cos()- compute the cosine value of an input value
pow()- compute the power of a input value
floor()- round down the input value
ceil()- round up the input value
While loop is used in programming to repeat a specific block of statement until some end condition is
met.
The syntax of a while loop is:
while (test Expression)
{
Statements… statements….
}
20
Summer 22
a) Draw and label different symbols used in flowchart.
1. The Oval
An End or Beginning While Creating a Flowchart
The oval, or terminator, is used to represent the start and end of a process. Remember to use
the same symbol again to show that your flowchart is complete.
2. The Rectangle
A Step in the Flowcharting Process
The rectangle is your go-to symbol once you've started flowcharting. It represents any step in
the process you’re diagramming and is the workhorse of the flowchart diagram. Use rectangles
to capture process steps like basic tasks or actions in your process.
3. The Arrow
Indicate Directional Flow
The arrow is used to guide the viewer along their flowcharting path. And while there are many
different types of arrow tips to choose from, we recommend sticking with one or two for your
entire flowchart. This keeps your diagram looking clean, but also allows you to emphasize
certain steps in your process.
21
4. The Diamond
Indicate a Decision
The diamond symbolizes that a decision is required to move forward. This could be a binary,
this-or-that choice or a more complex decision with multiple choices. Make sure that you
capture each possible choice within your diagram.
In the C programming language, keywords are reserved words that have special meanings and
cannot be used as identifiers (names for variables, functions, etc.). Here are four keywords in C:
1) if statement: The if statement is used to execute a block of code if a specified condition is true.
2) if-else statement: The if-else statement is used to execute one block of code if the condition is
true and another block if the condition is false.
3) else if statement: The else if statement is used to test multiple conditions sequentially. It
allows checking for multiple conditions and executing the corresponding block of code for the
first true condition.
4) switch statement: The switch statement is used to select one of many blocks of code to be
executed. It provides an alternative to a sequence of if-else if-else statements.
22
These decision-making statements provide flexibility in controlling the flow of a C program
based on different conditions.
d) Define array. List its types.
Definition of Array:
An array in programming is a collection of elements of the same data type that are stored in
contiguous memory locations. Each element in an array is identified by an index or a key. Arrays
provide a way to store multiple values under a single variable name, making it easier to manage
and manipulate data.
Types of Arrays:
1) One-dimensional array:
An array that stores elements in a linear sequence. Each element has a unique index, and
accessing elements involves using a single subscript or index.
2) Two-dimensional array:
An array of arrays, where each element is identified by two indices (row and column). It
represents a table of values with rows and columns.
3) Multi-dimensional array:
Arrays with more than two dimensions. While less common, they can have three or more
indices to represent data structures with higher dimensions.
5) Dynamic array:
An array whose size can be dynamically adjusted during runtime. In languages like C++, dynamic
arrays are implemented using data structures like vectors.
These are some common types of arrays. Each type serves a specific purpose, and the choice of
array type depends on the requirements of the program.
23
e) Write syntax and use of POW ( ) function or header file.
In C, the pow() function is used for power or exponentiation. To use this function, you need to include
the <math.h> header file.
Syntax:
#include <math.h>
ANS: i) Flowchart:
A flowchart is a visual representation of a process or algorithm. It uses various symbols and shapes to
represent different steps, decisions, and the flow of control within a program or system. Flowcharts help
in understanding and designing algorithms.
ii) Algorithm:
24
b) State any four data types used in ‘C’.
In C, a structure is a user-defined data type that allows combining different data types under a single
name. It is used to group related data items.
Example:
struct Point {
int x;
int y;
};
This defines a structure named Point that contains two members: x and y, both of type int.
e) State any two advantages of function.
1) Modularity: Functions allow breaking down a program into smaller, manageable, and reusable pieces.
This promotes modularity, making the code easier to understand, maintain, and debug.
2) Code Reusability: Functions can be reused in different parts of a program or even in different
programs. Once a function is defined, it can be called multiple times, reducing code duplication and
promoting efficiency.
25
f) Write the meaning of ‘&’ and * with respect to pointer.
g) Draw any two symbols used to construct flow chart. Also state their use
1. The Oval
An End or Beginning While Creating a Flowchart
The oval, or terminator, is used to represent the start and end of a process. Remember to use
the same symbol again to show that your flowchart is complete.
2. The Rectangle
A Step in the Flowcharting Process
The rectangle is your go-to symbol once you've started flowcharting. It represents any step in
the process you’re diagramming and is the workhorse of the flowchart diagram. Use rectangles
to capture process steps like basic tasks or actions in your process.
26
Summer-19
4 Marks
• State four arithmetic operations perform on pointer with example. (Note: Code snippet
shall be considered)
27
• Write a program to reverse the number 1234 (i.e. 4321) using function. (Note: Any other
correct logic shall be considered).
#include
#include
void findReverse();
void main()
{
findReverse();
}
void findReverse()
{
int num, res=0,ans=0;
clrscr();
28
printf("Enter the number");
scanf("%d", &num);
while(num!=0)
{
res=num%10;
ans=ans*10+res;
num=num/10;
}
printf("Reverse number is %d", ans);
getch();
}
• Differentiate between character array and integer array with respect to size and
initialisation.
Bitwise operators:
Bitwise OR-|
It takes 2 bit patterns and performs OR operations on each pair of corresponding bits. The following
example will explain it.
1010
1100
29
OR
1110
Bitwise NOT
One's complement operator (Bitwise NOT) is used to convert each "1-bit to 0-bit" and "0-bit tol-bit", in
the given binary pattern. It is a unary operator i.e. it takes only one operand.
1001
NOT
0110
Bitwise XOR ^
Bitwise XOR ^, takes 2 bit patterns and perform XOR operation with it.
0101
0110
XOR 0011
• With suitable example, explain how two dimensional arrays can be created.
The array which is used to represent and store data in a tabular form is called as two dimensional array.
Such type of array is specially used to represent data in a matrix form.
Declaration of two dimensional arrays:
30
Syntax:-
Data type arrayname [row size] [column size];
Eg:
int arr[3][4];
This will declare “arr”with 3 rows and 4 columns. A two-dimensional array can be considered as a table
which will have x number of rows and y number of columns. A two-dimensional array a, which contains
three rows and four columns can be shown as follows-
Thus, every element in the array a is identified by an element name of the form a[i ][ j ], where 'a' is the
name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
Example :
main()
{
int a[2][2]={{1,2},{4,5});
int i,j;
for(i=0;i
printf( "%d",a[i][j]);
}
printf("\n");
}
}
Strlen function:
strlen( ) function in C gives the length of the given string. strlen( ) function counts the number of
characters in a given string and returns the integer value. It stops counting the character when null
character is found. Because, null character indicates the end of the string in C.
Syntax: strlen(stringname);
Example:
Consider str1="abc"
31
strlen(str1); returns length of strl as 3
strcat() function:
In C programming, strcat() concatenates (joins) two strings. It concatenates source string at the end of
destination string.
Syntax:
strcat( destinationsource, source string);
Example:
Consider str1="abc" and str2="def" strcat(str1,str2); returns abcdef in str1 and str2 remains unchanged.
strcpy() function
strncpy() function copies portion of contents of one string into another string.
Syntax:
strncpy( destination string, source string, size );
Example:
Consider str1="abc" strcpy(str1,str2); returns abcstr2
strcmp() function
The stremp function compares two strings which are passed as arguments to it. If the strings are equal
then function returns value 0 and if they are not equal the function returns some numeric value.
Syntax:
strcmp(str1, str2);
Example:
Consider str1="abc" and str2="abc"
Then strcmp(str1,str2) returns 0 as both the strings are same.
32
• Describe generic structure of C program.
33
Global declaration section: There are some variables that are used in more than one function, Such
variables are called global variables and are declared in the global declaration section that is outside of
all the functions.
Declaration part: The declaration part declares all the variables used in the executable part.
Subprogram section: If the program is a multi-function program
then the subprogram section contains all the user-defined functions that are called in the main ()
function. User-defined functions are generally placed immediately after the main () function, although
they may appear in any order.
Header files
A header file is a file with extension h which contains C function declarations and macro definitions to be
shared between several source files.
Include Syntax
Both the user and the system header files are included using the preprocessing directive #include.
'main' function
main() function is the entry point of any C program. It is the point at which execution of program is
started. Every C program have a main() function.
• Write a program to take input as a number and reverse it by while loop. (Note: Any other
correct logic shall be considered).
#include
#include
void main()
{
int no;
int sum=0,rem;
printf("\n Enter number:");
scanf("%d",&no);
while(no>0)
{
rem=no%10;
no=no/10;
sum=sum*10+ rem;
}
printf("\nsum=%d",sum);
getch();
}
34
• Write a program to accept 10 numbers in array and arrange them in ascending order.
(Note: Any other correct logic shall be considered).
#include
#include
void main()
{ int arr[10],i,j,temp;
clrscr();
printf("Enter array elements:");
for(i=0;i<10;i++)
{
scanf("%d",&arr[i]);
}
printf("\n\n Array elements are:"); for(i=0;i<10;i++)
{
printf("%d" arr[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<10;i++)
{
if(arr[i+1]<arr[i])
{
temp=arr[i];
arr[i]=arr[i+1]; arr[i+1]=temp;
}
}
}
printf("\n\nArray elements in ascending order are:"); for(i=0;i<10;i++)
{
printf("%d ",arr[i]);
}
getch();
}
int *a,b;
It is declaration of integer pointer a and integer variable b
b=20;
value 20 is assigned to variable b.
*a=b;
Value of b is assigned to pointer a.
A=&b;
Address of b is assigned to variable A.
Summer 18
4 marks
• Develop a simple ‘C’ program for addition and multiplication of two integer numbers.
(Note: Any other relevant logic shall be considered)
#include
#include
void main()
{
int a,b,add,mul;
clrscr();
printf("Enter value for a and b:");
scanf("%d%d",&a,&b);
add=a+b;
mul=a*b;
printf("\nAddition of a and b=%d\n",add);
printf("\Multiplication of a and b=%d",mul);
getch();
}
When pointer (addresses) is passed to the function as an argument instead of value then function is
called as call by reference.
36
Example:
#include
#include
int add(int *);
void main()
{
int *ptr,pos=0;
clrscr();
printf("Enter position:");
scanf("%d",&pos);
ptr=&pos;
printf("\nSum=%d",add(ptr));
getch();
}
int add(int *p)
{
int i=0;
int sum=0;
for(i=1;i<=(*p);i++)
{
sum=sum+i;
}
return sum;
}
In the above program function passes the address of „pos‟ to the ptr. The value of ptr is passed while
calling the function. In function definition in *p it takes value of ptr instead of address for performing
addition of numbers up to specific position.
getchar( ) - It is function from stdio.h header file. This function is used to input a single character. The
enter key is pressed which is followed by the character that is typed. The character that is entered is
echoed.
Syntax:
37
ch=getchar();
Example:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
During the program execution, a single character gets or read through the getchar(). The given value is
displayed on the screen and the compiler waits for another character to be typed. If you press the enter
key/any other characters and then only the given character is printed through the printf function.
putchar( ) - It is used from standard input (stdio.h) header file. This function is the other side of getchar.
A single character is displayed on the screen.
Syntax:
putchar(ch);
voidmain()
{
char ch='a';
putchar(ch);
getch();
}
getch( ) - It is used from the console (conio.h) header file. This function is used to input a single
character. The character is read instantly and it does not require an enter key to be pressed. The
character type is returned but it does not echo on the screen.
Syntax:
ch=getch();
Where, ch - assigned the character that is returned by getch().
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
During the program execution, a single character gets or read through the getch(). The given value is not
displayed on the screen and the compiler does not wait for another character to be typed. And then, the
given character is printed through the printf function.
38
putch( )- It is used from console input output header file (conio.h) This function is a counterpart of
getch(). Which means that it will display a single character on the screen. The character that is displayed
is returned.
Syntax:
putch(ch);
Where, ch - the character that is to be printed.
void main()
{
char ch='a';
putch(ch)
}
• Develop a program to accept an integer number and print whether it is palindrome or not.
(Note: If string is considered instead of number for palindrome checking, then that
logic shall be considered)
#include
#include
void main()
{
int n,num,rev=0,digit,i;
clrscr();
printf("Enter the number: ");
scanf("%d",&num);
n=num;
for(i=0;num!=0;++i)
{
digit=num%10;
rev=rev*10+digit;
num=num/10;
}
if(n==rev)
printf("Number is palindrome");
else printf("Number is not palindrome");
getch();
}
printf() function is used to print the character, string, float, integer, octal and hexadecimal values onto
the output screen.
scanf() function is used to read character, string, numeric data from keyboard.
%d format specifier is used in printf() and scanf() to specify the value of an integer variable.
%c is used to specify character,
%f for float variable,
%s for string variable,
and %x for hexadecimal variable.
Example:
#include
#include
void main()
{
int i;
clrscr();
printf("Enter a number");
scanf("%d",&i);
printf("Entered number is: %d",i);
getch();
}
40
Formatted input: When the input data is arranged in a specific format, it is called formatted input. scanf
function is used for this purpose in C.
General syntax:
scanf(“control string”, arg1, arg2..);
Control string here refers to the format of the input data. It includes the conversion character %, a data
type character and an optional number that specifies the field width. It also may contain new line
character or tab. arg1, arg2 refers to the address of memory locations where the data should be stored.
Example:
scanf(“%d”,&num1);
Eg:
#include
#include
void main()
{
int i;
clrscr();
printf("Enter a number");
scanf("%d",&i);
printf("Entered number is: %d",i);
getch();
}
• Develop a program to find factorial of a number using recursion. (Note: Any other
relevant logic shall be considered)
#include
#include
int factorial(int num)
{
if(num==1)
{
return 1;
}
else
{
return(num*factorial(num-1));
}
41
}
void main()
{
int num;
int result;
clrscr();
printf("Enter a number");
scanf("%d",&num);
result=factorial(num);
printf("Factorial of %d is %d",num,result);
getch();
}
• Write a program to sweep the values of variables a = 10, b = 5 using function. (Note : Read
sweep as swap in the question) (Note: Any other logic using function shall be considered)
#include
#include
void swapvalues(int *i, int *j)
{
int temp;
temp=*i;
*i=*j;
*j=temp;
}
void main()
{
int a=10;
int b=5;
clrscr();
printf("The values before swaping:\na=%d, b=%d",a,b);
swapvalues(&a,&b);
printf("\nThe values after swaping:\na=%d, b=%d",a,b);
getch();
}
• Develop a program using structure to print data of three students having data members
name, class, percentage. (Note: Any other relevant logic shall be considered)
42
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[20];
char c[20];
int per;
} s[3];
int i;
clrscr();
for(i=0;i<3;i++)
{
printf("Enter name, class, percentage");
scanf("%s%s%d", &s[i].name,&s[i].c,&s[i].per);
}
for(i=0;i<3;i++)
{
printf("%s %s %d\n",s[i].name,s[i].c,s[i].per);
}
getch();
}
• Design a program to print a message 10 times. (Note: Any other relevant logic shall be
considered)
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<10;i++)
{
printf("Welcome to C programming\n");
}
getch();
}
43
• Draw a flowchart for checking whether given number is prime or not. (Note: Any correct
flowchart shall be considered)
• Implement a program to demonstrate logical AND operator. (Note: Any other relevant
logic shall be considered)
#include
#include
void main()
{
int i;
int j;
clrscr();
printf("Enter the values of i and j");
scanf("%d%d",&i,&j);
if(i==5 && j==5)
44
{
printf("Both i and j are equal to 5");
}
else
{
printf("Both the values are different and either or both are not equal to 5");
}
getch();
}
Winter 18
4 marks
Step 1- Start
Step 2- Read / input the number.
Step 3- if n%5==0 then goto step 5.
Step 4- else number is not divisible by 5 goto step 6.
Step 5- display the output number is divisible by 5.
Step 6- Stop
Do-While statement:
• In some applications it is necessary to execute the body of the loop before the condition is checked;
such situation can be handled by do statement.
• At least once the body of loop will be executed.
• do statement, first executes the body of the loop.
• At the end of the loop, the test condition in the while statement is evaluated. If the condition is true,
then it continues to execute bodyof the loop once again.
• This process continues as long as the condition is true.
• When the condition becomes false, the loops will be terminated and the control goes to next
statement after while statement.
Example:
#include
#include
45
void main()
{
int i=1;
clrscr();
printf("\n Odd numbers from 1 to 20 are \n");
do
{
if(i%2 ! = 0)
printf("\n %d", i);
i++;
}
while(i<=20); /* The loop iterates till the value of i is less than or equal to 20 */
getch();
}
I. One dimensional array: An array is a collection of variables of the same type that are referred
through a common name. A specific element in an array is accessed by an index. In C, all arrays
consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
Syntax: data_type array_name[array_size];
Example: int marks[10];
II. Two dimensional array : Two dimensional array is a collection of similar type of data elements
arranged in the form of rows & columns.
Example: Array can be declared as int arr[3][3]; In this there can be 9 elements in an array with
3 rows and 3 columns.
Output :
STATE BOARD OF TECHNICAL EDUCATION
Increment operator is used to increment or increase the value of a variable by one. It is equivalent to
adding one to the value of the variable. The symbol used is ++.
The decrement operator is used to decrement or decrease the value of variable by 1. It is equivalent to
subtracting one from the value of the variable. The symbol used is --.
Syntax:
++var or var++ for increment and --var or var--for decrement.
Example:
int m=5;
int n = ++m;
printf(%d%d”,m,n);
When the increment operator is used prior to the variable name m, the value of the variable m is
incremented first and then assigned to the variable n. The values of both the variable m and n here will
be 6. But if the increment operator ++ is used after the variable name, then the value of the variable m is
assigned to the variable n and then the value of m is increased. Therefore the values of m and n will be 6
and 5 respectively.
Example for decrement operator
int m=5;
int n=--m;
printf(“%d%d”,m,n);
or
#include
#include
void main()
{
int m=4,n=6;
clrscr();
printf("values of m and n before changing%d%d",m,n);
m++;
n--;
printf("\nvalues after changing%d%d",m,n);
47
getch();
}
Functions are basic building blocks in a program. It can be predefined/ library functions or user defined
functions. Predefined functions are those which are already available in C library. User defined functions
are those which are written by the users to complete a specific task. Execution of a C program starts
from main(). User defined functions should be called from main() for it to execute. A user defined
function has a return type and a name. it my or may not contain parameters.
The general syntax of a user defined function :
Return_type func_name(parameter list)
Example:
#include
#include
void myFunc(int a)
{
printf("The value is: %d",a);
}
void main()
{
myFunc(10);
getch()
}
Conditional operators return one value if condition is true and returns another value is condition is false.
This operator is also called as ternary operator as it takes three arguments.
Syntax :
(Condition? true_value: false_value);
Example:
#include
#include
void main()
{
int i;
48
clrscr();
printf("Enter a number:");
scanf("%d",&i);
i%2==0?printf("%d is even",i):printf("%d is odd",i) ;
getch();
}
strlen()- this function is used to find the length of a string. It counts the number of characters comprising
the string.
Syntax:
strlen(char[] str)- finds the length of the string str.
Example:
#include
#include
#include
void main()
{
char str[] = "mystring";
int len=0;
clrscr();
len=strlen(str);
printf("Length of string is :%d",len);
getch();
}
Example:
#include
#include
#include
void main()
{
char source[]="mystring";
49
char dest[10];
clrscr();
printf("%s%s",source,dest);
strcpy(dest,source);
printf("\n%s %s",source, dest);
getch();
}
• Write algorithm and draw flow-chart to print even numbers from 1 to 100.
Algorithm:-
1. Start
2. Initialize the variable i to 1.
3. while i<=100
4. if i%2==0
5. print the number
6. increment value of i
7. Stop
Flowchart:-
50
• Write a program to accept marks of four subjects as input from user. Calculate and display
total and percentage marks of student. Note: Any other correct logic shall be considered
#include
#include
void main()
{
float marks[4];
float total=0.0, perc=0.0;
int i;
clrscr();
for(i=1;i<=4;i++)
{
printf("Enter marks of subject %d",i);
scanf("%f%",&marks[i]);
}
for(i=1;i<=4;i++)
{
51
total=total+marks[i];
}
printf("Total is :%f",total);
perc=total/4;
printf("Percentage is %f",perc);
getch();
}
• Write a program to accept the value of year as input from the keyboard & print whether it
is a leap year or not.
#include
#include
void main()
{
int year;
clrscr();
printf("Enter year");
scanf("%d",&year);
if(year%4==0)
{
printf("Year %d is a leap year",year);
}
else
{
printf("Year %d is not a leap year",year);
}
getch();
}
• Write a program to accept a string as input from user and determine its length. [Don’t use
built in library function strlen()]
#include
#include
void main()
{
char str[50];
int i, len=0;
clrscr();
52
printf("Enter a string");
scanf("%s",&str);
for(i=0; str[i]!='\0'; i++)
{
len++;
}
printf("The length of string is %d",len);
getch();
}
#include
#include
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("Numbers after swapping no1=%d and no2=%d",a,b);
}
void main()
{
int no1, no2;
clrscr();
printf("Enter the 2 numbers");
scanf("%d%d",&no1,&no2);
printf("Numbers before swapping no1=%d and no2= %d",no1, no2);
swap(no1,no2);
getch();
}
Winter 19
4 marks
• State the importance of flow chart.
53
A flowchart is a type of diagram that represents an algorithm. It is a visual representation of a sequence
of steps to complete the process. A flow chart describes a process using symbols rather than words.
Computer programmers use flow charts to show where data enters the program, what processes the
data goes through, and how the data is converted to output.
-can be used to quickly communicate the ideas or plans that one programmer envisions to other people
who will be involved in the process.
- aid in the analysis of the process to make sure nothing is left out and that all possible inputs, processes,
and outputs have been accounted for.
-help programmers develop the most efficient coding because they can clearly see where the data is
going to end up.
- help programmers figure out where a potential problem area is and helps them with debugging or
cleaning up code that is not working.
- are a useful tool in visualizing a module's flow of execution before writing any code.
This allows developers to do three things: verify the algorithm's correctness before writing code,
visualize how the code will ultimately be written, and communicate and document the algorithm with
other developers and even non-developers.
-may be used in conjunction with other tools, such as pseudo-code, or may be used by itself to
communicate a module's ultimate design, depending on the level of detail of the flowchart.
• Write a program to declare structure student having rollno, name & marks. (Note: Any
other correct logic shall be considered).
Accept and display data for three students.
#include
#include
void main()
{
int i;
struct student
{
int rollno;
char name[20];
int marks;
}
s[3];
clrscr();
for(i=0;i<3;i++)
{
printf("Enter rollno, name and marks\n");
54
scanf("%d%s%d", &s[i].rollno,&s[i].name,&s[i].marks);
}
for(i = 0; i<3;i++)
{
printf("\nThe details of student %d\n",i+1);
printf("Roll no %d\n",s[i].rollno);
printf("Name is %s\n",s[i].name);
printf("Marks %d\n",s[i].marks);
}
getch();
}
• Explain pointer arithmetic with example. (Note: Code snippet shall be considered).
The pointer arithmetic is done as per the data type of the pointer. The basic operations on pointers are:
Increment:
It is used to increment the pointer. Each time a pointer is incremented, it points to the next location.
Eg, for an int pointer variable, if the current position of pointer is 1000, when incremented it points to
1002 because for storing an int value it takes 2 bytes of memory.
Decrement:
It is used to decrement the pointer. Each time a pointer is decremented, it points to the previous
location.
Eg, if the current position of pointer is 1002, then decrement operation results in the pointer pointing to
the location 1000.
• Explain nested if-else with example. (Note: Any example shall be considered)
When a series of decision is required, nested if-else is used. Nesting means using one if-else construct
within another one. If the condition in the outer if, is true, then only the inner if-else will get executed.
Further the statements in the inner if will get execute only if the condition of inner if, evaluates to true.
If it is false, the statements in inner else will get executed.
If the outer if evaluates to false, then the statements in outer else get executed.
General syntax:
if(condition)
{
if(condition)
{
statements
}
else
{
Statements
}
}
else
{
statements
}
statements
Example:
#include
56
#include
void main()
{
int val;
clrscr();
printf("Enter a number");
scanf("%d",&val);
if(val>=5)
{
if(val>5)
{
printf("Number is greater than 5");
}
else
{
printf("Number is equal to 5");
}
}
else
{
printf("Number is less than 5");
}
getch();
}
(i) Keyword: Keywords are special words in C programming which have their own predefined meaning.
The functions and meanings of these words cannot be altered. Some keywords in C Programming are if,
while, for, do, etc..
(iv) Constant: Constants refer to fixed values that the program may not change during its execution.
These fixed values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are enumeration constants
as well.
Example:
121
234
3.14
58
• Explain conditional operator with example.
• List the categories of functions and explain any one with example.
1) Function with no arguments and no return value: This category of function cannot return
any value back to the calling program and it does not accept any arguments also. It has to be
declared as void.
For example:
void add()
{
Int a,b,c;
a=5;
b=6;
c=a+b;
printf(“%d”,c);
}
It should be called as add();
2) Function with arguments and no return value: This category of function cannot return any
value back to the calling program but it takes arguments from calling program. It has to be
declared as void. The number of arguments should match in sequence, number and data
type. For example:
void add(intx,int y)
{
int z;
z=x+y;
printf(“%d”,z);
}
It should be called as add(4,5); where x will take 4 and y will take 5 as their values.
3) Function with no arguments and return value: This category of function can return a value
back to the calling program but it does not take arguments from calling program. It has to be
declared with same data type as the data type of return variable.
For example:
int add()
{
inta,b,c;
a=5;
60
b=6;
c=a+b;
return(c);
}
It should be called as int x = add(); where x will store value returned by the function.
4) Function with arguments and return value: This category of function can return a value
back to the calling program but it also takes arguments from calling program. It has to be
declared with same data type as the data type of return variable.
For example:
int add(intx,int y)
{
int z;
z=x+y;
return(z);
}
It should be called as int s = add(4,5); where x will have 4 and y will have 5 as their values
and s will store value returned by the function.
Step 1- Start
Step 2- Read / input the number.
Step 3- if n%2==0 then number is even.
Step 4- else number is odd.
Step 5- display the output.
Step 6- Stop
Break:
It breaks the execution of the loop which allows exiting from any loop or switch, such that break
statement skips the remaining part of current iterations of the loop.
Syntax: break;
61
Continue: It is used when it is required to skip the remaining portion of the loop without breaking loop it
will transfer control directly to next iteration
Syntax: continue;
In given program sequence if “break” executes then execution control will jump out of loop & next
statement after loop will be executed. In given program sequence if “continue” executes then execution
control will skip remaining statements of loop & will start next iteration of loop
• Write a program to add, subtract, multiply and divide two numbers, accepted from user
switch case. (Note: Any other correct logic shall be considered).
#include
#include
void main()
{
int a,b,ch,add,sub,mul,div;
clrscr();
printf("\n1 for addition \n2 for substraction");
printf("\n3 for multiplication \n4 for division");
printf("\nEnter two numbers:");
scanf("%d%d",&a,&b);
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
62
add=a+b;
printf("Addition of a & b=%d",add);
break;
case 2:
sub=a-b;
printf("Substraction of a & b=%d",sub);
break;
case 3:
mul=a*b;
printf("Multiplication of two numbers=%d",mul);
break;
case 4:
div=a/b;
printf("Division of two numbers=%d",div);
break;
default:
printf("Invalid choice. ...");
}
getch();
}
• Write a program to read two strings and find whether they are equal or not. (Note: Any
other correct logic shall be considered).
#include
#include
#include
void main()
{
char st1[20],st2[20];
printf(“enter string 1”);
scanf(“%s”,st1);
printf(“enter second string”);
scanf(“%s”,st2);
if(strcmp(st1,st2)==0)
64
printf(“\nboth strings are equal”);
else
printf(“\nstrings are not equal”);
}
Winter 22
4 marks
a) Explain any four guidelines for preparation of flowchart.
1. Understand the Problem: Before creating a flowchart, thoroughly understand the problem or process
you are representing. Identify the input, output, and key steps involved.
2. Use Standard Symbols: Utilize standard flowchart symbols for processes, decisions, inputs/outputs,
connectors, etc. This ensures that your flowchart is easily understandable and follows widely accepted
conventions.
3. Keep it Simple and Clear: Aim for simplicity and clarity. Avoid unnecessary details and make sure that
the flowchart is easy to follow. Use concise labels for processes and decisions.
4. Maintain Consistency: Be consistent with the use of symbols and formatting throughout the flowchart.
This helps in maintaining a clean and organized visual representation.
65
c) Explain declaration and initialization of one dimensional array using example.
Declaration: In C, to declare a one-dimensional array, specify the data type of its elements followed by
the array name and the size of the array in square brackets.
Initialization: To initialize an array, provide the values for each element enclosed in curly braces {} at the
time of declaration.
Example:
#include <stdio.h>
int main() {
// Declaration and initialization of an integer array
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and printing elements of the array
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
In this example, an integer array numbers is declared and initialized with values 1, 2, 3, 4, and 5. The for
loop is then used to iterate through the array and print its elements.
66
Ans:
It appears that there are a few syntax errors and issues in the provided code:
1) void main() should be corrected to int main().
2) print f should be corrected to printf.
3) <conio.h> is not a standard header in C, and getch() is not used in the code, so you can remove it.
e) Explain data type conversion with example.
Data type conversion, also known as type casting, is the process of converting a value from one data
type to another. Implicit conversion occurs automatically by the compiler, while explicit conversion
(casting) involves the programmer specifying the conversion.
Example:
#include <stdio.h>
int main() {
int integerNumber = 10;
double doubleNumber;
// Implicit Conversion
doubleNumber = integerNumber; // int to double
return 0;
}
In this example, an integer variable integerNumber is implicitly and explicitly converted to a double
variable doubleNumber.
67
f) Explain any two string handling functions with syntax and example.
1. strlen() - String Length:This function calculates and returns the length of the string str. It does not
include the null-terminating character ('\0') in the count. The function takes a pointer to a constant
character (const char *str) as its argument.
syntax:
#include <string.h>
size_t strlen(const char *str);
example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
size_t length = strlen(str);
printf("Length of the string: %zu\n", length);
return 0;
}
In this example, strlen() is used to determine the length of the string "Hello, World!" and prints the
result.
2. strcpy() - String Copy:This function copies the contents of the string src to the string dest. It returns a
pointer to the destination string (char *dest). Both src and dest should be null-terminated strings. If dest
is not large enough to accommodate the contents of src, it may lead to undefined behavior.
syntax:
#include <string.h>
char *strcpy(char *dest, const char *src);
example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello";
char destination[20];
68
// Copy source to destination
strcpy(destination, source);
In this example, strcpy() is used to copy the contents of the string "Hello" to the destination string,
which is then printed.
g) Describe scanf() function with its syntax and example.
The scanf() function is used for reading input from the standard input (keyboard) in C.The scanf()
function is a part of the C Standard Library and is used for reading input from the standard input. It
allows the program to interact with the user by capturing input data.
Syntax:
#include <stdio.h>
int scanf(const char *format, ...);
Example:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num); // Reads an integer from the user
printf("You entered: %d\n", num);
return 0;
}
In this example, scanf("%d", &num) reads an integer from the user and stores it in the variable num.
A recursive function is a function that calls itself, either directly or indirectly, to solve a smaller instance
of the same problem. Calculating the factorial of a number is a classic example of using recursion in
programming. The factorial of a non-negative integer n is the product of all positive integers less than or
equal to n and is denoted by n!.
69
The factorial function is defined as follows:
n!=n×(n−1)×(n−2)×…×2×1
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
return 0;
}
70
5!=5×4!=5×4×3!=5×4×3×2!=5×4×3×2×1!=5×4×3×2×1×0!
The base case is reached when n=0 or n=1, and the recursion stops. The final result is then calculated by
multiplying the values back up the chain, giving the factorial of 5.
i) Write an algorithm and draw a flowchart to find largest number from three numbers.
1)Start
2) Input three numbers: num1, num2, num3.
3) Set largest to the value of num1.
4) If num2 is greater than largest, set largest to the value of num2.
5) If num3 is greater than largest, set largest to the value of num3.
6) Output the value of largest as the result.
7)End
71
Flowchart:
#include <stdio.h>
int main() {
// Input temperature in Fahrenheit
double fahrenheit;
printf("Enter temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit);
return 0;
}
int main() {
int rows = 5;
return 0;
}
l) Write a program to declare an array of 5 elements and display sum of all array elements.
#include <stdio.h>
int main() {
int array[5] = {1, 2, 3, 4, 5};
int sum = 0;
73
// Display the sum
printf("Sum of array elements: %d\n", sum);
return 0;
}
#include <stdio.h>
int main() {
double radius;
return 0;
}
74
Winter 19
6 marks
• Write a program to calculate sum of all the odd numbers between 1 to 20. (Note: Any
other correct logic shall be considered).
#include
#include
void main()
{
Int i,sum=0;
clrscr();
for(i=1;i<=20;i++)
{
if(i%2!=0)
{
sum=sum+i;
}
}
printf("Sum=%d",sum);
getch();
}
• Write a program for addition of two 3 x 3 matrices. (Note: Any other correct logic shall be
considered).
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("\n Enter first matrix"); for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
75
printf("\n Enter second matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\n Addition:\n"); for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
• Write a program to compute the sum of all elements stored in an array using pointers.
(Note: Any other correct logic shall be considered).
•
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],sum=0,i,*ptr;
clrscr();
printf("\n Enter array elements:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
ptr=&a[0];
for(i=0;i<5;i++)
{
sum-sum+(*ptr);
ptr ptr+1;
76
}
printf("\n Sum=%d",sum);
getch();
}
• Write a program to sort elements of an array in ascending order. (Note: Any other correct
logic shall be considered).
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,j,temp;
clrscr();
printf("\n Enter array elements:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
{
for(j=0;j<4-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<5;i++)
printf("\n %d",a[i]);
getch();
}
• Write a function to print Fibonacci series starting from 0, 1. (Note: Any other correct logic
shall be considered).
void Fibbo()
{
77
inta,b,c,limit,i;
printf("\n Enter number:");
scanf("%d",&limit);
a=0;
b=1;
printf("%d\t%d",a,b);
for(i=0;i<limit-2;i++)
{
c=a+b;
printf("\t%d",c);
a=b;
b=c;
}
}
#include
#include
int factorial(int no)
{
if(no==1)
return(1);
else
return(no*factorial(no-1));
}
void main()
{
intfact,no;
clrscr();
printf("\n Enter number");
scanf("%d",&no);
fact=factorial(no);
printf("\n Factorial number=%d",fact);
getch();
}
78
Summer 19
6 marks
#include<stdio.h>
#include<conio.h>
void add(int x, int y)
{
printf("\nAddition=%d",x+y);
} void sub(int x,int y)
{ printf("\nSubtraction=%d",x-y); }
void mult(int x, int y)
{ printf("\nMultiplication=%d",x*y);
}
void div(int x,int y)
{
printf("\nDivision=%d",x/y);
}
void main()
{
intx,y;
clrscr();
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
add(x,y);
sub(x,y);
mult(x,y);
div(x,y);
getch();
}
79
• Define Array. Write a program to accept ten numbers in array. Sort array element and
display.
Definition of Array:
An array is a collection of data elements, all of the same type, accessed using a common name
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,temp;
clrscr();
printf("Enter numbers:");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]>a[j])
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
printf("\n Sorted array elements:");
for(i=0;i<10;i++)
printf("\n %d",a[i]);
getch();
}
• Write a program to print reverse of a entered string using pointer. (Note: Any other
correct logic shall be considered).
#include
#include
void main()
{
char str[10],*ptr;
int 1=0;
clrscr();
80
printf("Enter string:");
scanf("%s", str);
ptr=str;
while(*ptr!='\0')
{
I=1+1;
ptr ptr+1;
}
while(10)
{
ptr ptr-1;
printf("%c", *ptr);
-1;
}
getch();
}
Recursion means a function calls itself repetitively. A recursive function contains a function call to itself
inside its body.
Example:
#include
#include
int factorial(int N);
void main()
{
int N,fact;
clrscr();
printf("Enter number:");
scanf("%d",&N);
fact=factorial(N);
printf("\n Factorial is:%d",fact); getch();
}
int factorial(int N)
{
if(N==1)
return(1);
else
1
return(N*factorial(N-1));
}
Advantages:
o Reduces length of the program
o Reduces unnecessary calling of a function.
o Useful when same solution is to be applied many times.
• Write a program to accept ten numbers and print average of it. (Note: Program without
array shall be considered).
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,sum=0;
float avg;
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
sum=sum+a[i];
clrscr();
printf("Enter numbers:");
avg-sum/10;
printf("\n Average =%f", avg);
getch();
}
Format specifier tells the compiler what type of data a variable holds during taking input and printing
output using scanf() and printf() functions respectively.
Format specifiers used in C programming:
82
Winter 18
6 marks
• Write a program using switch statement to check whether entered character is VOWEL or
CONSONANT Note : Assume that the entered character is only alphabet.
#include
#include
void main()
{
char ch;
clrscr();
printf("Enter character:");
scanf("%c",&ch);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
83
case 'U':
printf("\n Entered character is VOWEL");
break;
default:
printf("\n Entered character is CONSONANT");
}
getch();
}
#include<stdio.h>
#include<conio.h> void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter first matrix elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter second matrix elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
84
printf("\n\nAddition of two matrices is:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}
#include
#include
void main()
{
int a,b;
clrscr();
a=5;
b=10;
printf("\n Value of a=%d",a);
printf("\n Address of a=%u",&a);
printf("\n Value of b=%d",b);
printf("\n Address of b=%u",&b);
getch();
}
• Write a program to declare structure employee having data member name, age, street
and city. Accept data for two employees and display it. Note : Two structure variables or
array of structure variables shall be considered.
#include<stdio.h>
#include<conio.h>
struct employee
{
85
char name[10],street[10],city[10];
int age;
};
void main()
{
int i;
struct employee e[2];
clrscr();
for(i=0;i<2;i++)
{
printf("\n Enter name:");
scanf("%s", &e[i].name);
printf("\n Enter age:");
scanf("%d",&e[i].age);
printf("\n Enter street:");
scanf("%s", &e[i].street);
printf("\n Enter city:");
scanf("%s",&e[i].city);
}
for(i=0;i<2;i++)
{
printf("\n Name=%s",e[i].name);
printf("\n Age=%d",e[i].age);
printf("\n Street=%s",e[i].street);
printf("\n City=%s",e[i].city);
}
getch();
}
• If the value of a number (N) is entered through keyboard. Write a program using recursion
to calculate and display factorial of number (N).
#include
#include
int factorial(int N);
void main()
{
int N,fact;
86
clrscr();
printf("Enter number:");
scanf("%d",&N);
fact=factorial(N);
printf("\n Factorial is:%d",fact);
getch();
}
int factorial(int N)
{
if(N==1)
return(1);
else
return(N*factorial(N-1));
}
• Write a program to accept two numbers from user and perform addition, subtraction,
multiplication and division operations using pointer.
•
#include
#include
void main()
{
int no1,no2,*ptr1,*ptr2,result;
clrscr();
printf("Enter no1:");
scanf("%d",&no1);
printf("\nEnter no2:");
scanf("%d",&no2);
ptr1=&no1;
ptr2=&no2;
result=*ptr1+*ptr2;
printf("\n Addition=%d",result);
result=*ptr1-*ptr2;
printf("\n Subtraction=%d",result);
result=*ptr1**ptr2;
printf("\n Multiplication=%d",result);
result=*ptr1/(*ptr2);
printf("\n Division=%d",result);
getch();
87
}
Summer 18
6 marks
• Draw a flowchart of Do-while loop and write a program to add numbers until user enters
zero.
Program:-
#include
#include
void main()
{
int no,sum=0;
clrscr();
do
{
printf("\n Enter a number:");
scanf("%d",&no);
sum=sum+no;
}
while(no!=0);
printf("\n Sum of entered numbers =%d",sum);
getch();
}
88
• Give a method to create, declare and initialize structure also develop a program to
demonstrate nested structure. Declaration of structure:-
Declaration of structure:-
struct structure_name
{
data_type member 1;
data_type member 2;
.
.
.
data_type member n;
} structure variable 1, structure variable 2,..., structure variable n;
Example:-
struct student
{
int rollno;
char name[10];
}s1;
Initialization:-
struct student s={1,"abc"};
structure variable contains two members as rollno and name. the above example initializes rollno to 1
and name to "abc".
Program:-
#include
#include
struct college
{
int collegeid;
char collegename[20];
};
struct student
{
int rollno;
char studentname[10];
89
struct college c;
};
void main()
{
struct student s={1,"ABC",123,"Polytechnic"};
clrscr();
printf("\n Roll number=%d",s.rollno);
printf("\n Student Name=%s",s.studentname);
printf("\n College id=%d",s.c.collegeid);
printf("\n College name=%s",s.c.collegename);
getch();
}
Pointer to function:
include<stdio.h>
int sum(int x, int y)
{
return x+y;
}
int main()
{
int s;
int(*fp)(int, int);
fp = sum;
s = fp(10,12);
printf(“Sum = %d”,s);
return 0;
}
• Develop a program to swap two numbers using pointer and add swaped numbers also
print their addition. (Note: Any other relevant logic shall be considered)
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
90
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int x,y,sum;
printf("\n Enter value for x:");
scanf("%d",&x);
printf("\n Enter value for y:");
scanf("%d",&y);
swap(&x,&y);
printf("\nx=%d",x);
printf("\ny=%d",y);
sum=x+y;
printf("Sum of x+y = %d",sum);
}
#include<stdio.h>
#include<conio.h>
#define max 50
void main()
{
int a[max],i,n;
clrscr();
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter array element:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Array elements in reverse order:");
for(i=n-1;i>=0;i--)
printf("\t%d",a[i]);
getch();
}
91
Develop a program to find diameter, circumference and area of circle using function. (Note: Any other
relevant logic shall be considered)
#include<stdio.h>
#include<conio.h>
void circle(float r)
{
float diameter, circumference,area;
diameter=2*r;
printf("\n Diameter=%f", diameter);
circumference=2*3.14*r;
printf("\n Circumference=%f", circumference);
area=3.14*r*r;
printf("\n Area=%f",area);
}
void main()
{
float radius;
clrscr();
printf("\n Enter radius:");
scanf("%f",&radius);
circle(radius);
getch();
}
92
Winter 22
6 marks
a) Write a C program with comments to reverse the digit of integer number. For example the number
12345 should be displayed as 54321.
#include <stdio.h>
int main() {
int number, reversedNumber = 0;
return 0;
} #include <stdio.h>
int main() {
int number, reversedNumber = 0;
return 0;
}
OUTPUT:
#include <stdio.h>
int main() {
int matrix1[3][3], matrix2[3][3], sumMatrix[3][3];
return 0;
}
OUTPUT:
#include <stdio.h>
95
// Function to find the largest number in an array using pointer
int findLargest(int *arr, int size) {
int *ptr = arr;
int largest = *ptr;
return largest;
}
int main() {
int numbers[] = {23, 45, 12, 67, 89, 54, 32};
int size = sizeof(numbers) / sizeof(numbers[0]);
return 0;
}
OUTPUT:
d) Write a C program to declare structure employee having data member name, age, designation and
salary. Accept and display information of 1 employee.
96
#include <stdio.h>
int main() {
// Declare an instance of the Employee structure
struct Employee emp;
return 0;
}
97
OUTPUT:
#include <stdio.h>
int main() {
int num;
// Input a number
printf("Enter a non-negative integer: ");
scanf("%d", &num);
98
// Call the recursive function to find factorial
int result = factorial(num);
return 0;
}
OUTPUT:
f) Write a C program using pointer to read an array of characters and print them in reverse order.
#include <stdio.h>
int main() {
char array[50];
OUTPUT:
100