First Year C Question Bank With Solution
First Year C Question Bank With Solution
Q1. What is algorithm? Write down the general characteristics of an algorithm and write an
algorithm to print the digits of a number in reverse order.
Ans. Algorithm: An algorithm is a sequence of finite instructions, often used for calculation and data
processing.
An algorithm is a step-by-step method of solving a problem.
An algorithm is a set of instructions designed to perform a specific task.
Characteristics of the algorithm:
1) Finiteness: - an algorithm terminates after a finite number of steps.
2) Definiteness: - each step-in algorithm is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any
confusion.
3) Input: - an algorithm accepts zero or more inputs
4) Output:- it produces at least one output.
5) Effectiveness: - it consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time.
Algorithm to print the digits of a number in reverse order:
Digitsreverse(num)
1. Start.
2. Please enter number.
3. Read num.
4. While (num>0) repeat steps 5,6 and 7 otherwise go to step 8.
5. Do digit =num%10
6. Print digit;
7. Do num= num/10
8. Stop
Q2. What do you understand by flow chart? Draw a flow chart to find maximum of three numbers.
Ans-
Flow chart:
It is a very important tool for developing algorithm and program.
It is pictorial representation of step by step solution of a problem. Programmer often uses it as a program
planning tool for visually organizing step necessary to solve a problem.
It uses boxes of different shapes that denote different type of instruction.
While making a flow chart a programmer needs not to pay attention to the elements of the programming
language, he has to pay attention to the logic of solution to the problem
Q3. Define computer. Explain anatomy of computer in detail.
Ans- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amount of data.
A computer system consists of mainly four basic units; namely input unit, storage unit, central
processing unit and output unit. Central Processing unit further includes Arithmetic logic unit and
control unit, as shown in the figure:
Input Unit: This unit is used for entering data and programs into the computer system by the user for
processing. Input devices are,Keyboard, Mouse, Trackball, Touchpad, Light Pen, Magnetic ink character
recognition (MICR), Optical mark recognition (OMR), Bar code reader.
Memory Unit: The storage unit is used for storing data and instructions before and after processing.
Computer’s memory can be classified into two types; primary memory and secondary memory.
Primary Memory can be further classified as RAM and ROM.
RAM or Random Access Memory is the unit in a computer system. It is the place in a computer where the
operating system, application programs and the data in current use are kept temporarily so that they can
be accessed by the computer’s processor. It is said to be ‘volatile’ since its contents are accessible only as
long as the computer is on. The contents of RAM are no more available once the computer is turned off.
ROM or Read Only Memory is a special type of memory which can only be read and contents of which
are not lost even when the computer is switched off. It typically contains manufacturer’s instructions.
Among other things, ROM also stores an initial program called the ‘bootstrap loader’ whose function is to
start the operation of computer system once the power is turned on.
Secondary Memory
RAM is volatile memory having a limited storage capacity. Secondary/auxiliary memory is storage other
than the RAM. These include devices that are peripheral and are connected and controlled by the
computer to enable permanent storage of programs and data.
Secondary storage devices are of two types; magnetic and optical. Magnetic devices include hard disks
and optical storage devices are CDs, DVDs, Pen drive, Zip drive etc.
Output Unit: The output unit is used for storing the result as output produced by the computer after
processing. Output devices are monitor, printer etc.
CPU: The Central Processing Unit (CPU) takes data and instructions from the storage unit and makes all
sorts of calculations based on the instructions given and the type of data provided. It is then sent back to
the storage unit. CPU includes Arithmetic logic unit (ALU) and control unit (CU)
• Arithmetic Logic Unit: All calculations and comparisons, based on the instructions provided, are
carried out within the ALU. It performs arithmetic functions like addition, subtraction, multiplication,
division and also logical operations like greater than, less than and equal to etc.
• Control Unit: Controlling of all operations like input, processing and output are performed by control
unit. It takes care of step by step processing of all operations inside the computer.
Q4. What do you mean by operating system? Explain various functions of operating system.
Operating System:
It is a software program that acts as an interface between the user and the computer. It is a software
package which allows the computer to function.
It is a program that controls the execution of application programs.
It is an interface between applications and hardware.
Functions:
1. Program creation
2. Program execution
3. Access to Input/Output devices
4. Controlled access to files
5. System access
6. Error detection and response
7. Interpreting the commands
8. Managing peripherals
9. Memory management
10. Processor management
11. Information management
12. Process communication
Q5. What is a computer? Explain classification of computer in detail.
Ans-- Computer: Computer is an electronics device that can perform various arithmetic and logical
operations. It can receive data, process it and produce output. It can store large amounts of data.
Classification of Computer:
Computers differ based on their data processing abilities. They are classified according to purpose, data
handling and functionality.
Geneal purpose computers are designed to perform a range of tasks. They have the ability to store
numerous programs, but lack in speed and efficiency.
Specific purpose computers are designed to handle a specific problem or to perform a specific task. A set
of instructions is built into the machine.
According to data handling, computers are analog, digital or hybrid.
Analog Computer
An analog computer (spelt analogue in British English) is a form of computer that uses
continuous physical phenomena such as electrical, mechanical, or hydraulic quantities to model the
problem being solved
Digital Computer
A computer that performs calculations and logical operations with quantities represented as digits,
usually in the binary number system
Hybrid Computer (Analog + Digital)
A combination of computers that are capable of inputting and outputting in both digital and analog
signals. A hybrid computer system setup offers a cost-effective method of performing complex
simulations.
On the basis of Size
Supercomputer
The fastest and most powerful type of computer Supercomputers are very expensive and are employed for
specialized applications that require immense amounts of mathematical calculations. For example,
weather forecasting requires a supercomputer. Other uses of supercomputers include animated graphics,
fluid dynamic calculations, nuclear energy research, and petroleum exploration.
The chief difference between a supercomputer and a mainframe is that a supercomputer channels all its
power into executing a few programs as fast as possible, whereas a mainframe uses its power to execute
many programs concurrently.
Mainframe Computer
A very large and expensive computer capable of supporting hundreds, or even thousands, of users
simultaneously. In the hierarchy that starts with a simple microprocessor (in watches, for example) at the
bottom and moves to supercomputers at the top, mainframes are just below supercomputers. In some
ways, mainframes are more powerful than supercomputers because they support more simultaneous
programs. But supercomputers can execute a single program faster than a mainframe.
Mini-computer
It is a midsized computer. In size and power, minicomputers lie between workstations and mainframes. In
the past decade, the distinction between large minicomputers and small mainframes has blurred, however,
as has the distinction between small minicomputers and workstations. But in general, a minicomputer is a
multiprocessing system capable of supporting from 4 to about 200 users simultaneously.
Micro Computer or Personal Computer
Desktop Computer: a personal or micro-mini-computer sufficient to fit on a desk.
• Laptop Computer: a portable computer complete with an integrated screen and keyboard.
It is generally smaller in size than a desktop computer and larger than a notebook computer.
• Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer. Palmtops have
no keyboard, but the screen serves both as an input and output device.
Workstations
It is a terminal or desktop computer in a network. In this context, workstation is just a generic term for a
user's machine (client machine) in contrast to a "server" or "mainframe."
Q6. What do you mean by translator? Differentiate compiler and interpreter.
Ans- A translator is a computer program that performs the translation of a program written in a given
programming language into a functionally equivalent program in a different computer language, without
losing the functional or logical structure of the original.
Examples of widely used types of computer languages translators include interpreters, compilers, and
assemblers.
Difference between Compiler and Interpreter
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input .
2 Intermediate Object Code is Generated No Intermediate Object Code is Generated
Conditional Control Statements are Executes Conditional Control Statements are Executes
3
faster slower
Memory Requirement : More (Since Object
4 Memory Requirement is Less
Code is Generated)
Every time higher level program is converted into
5 Program need not be compiled every time
lower level program
Errors are displayed after entire program is Errors are displayed for every instruction
6
checked interpreted (if any)
7 Example : C Compiler Example : BASIC
Ans-
Q3. What is data type in c? Explain basic data type in terms of range, format specifier and size?
Ans-Data Type:
A Data Type is a Type of Data.
Data Type is a Data Storage Format that can contain a Specific Type or Range of Values.
When computer programs store data in variables, each variable must be assigned a specific data
type.
C supports three classes of data types
1)Primary data type→ char, int, float
2) Derived data type→ array, pointer
3)User defined data type → structure, union, enum
Basic data type in C:
Data Type Range Bytes Format
signed char -128 to + 127 1 %c
unsigned char 0 to 255 1 %c
short signed int -32768 to +32767 2 %d
short unsigned int 0 to 65535 2 %u
signed int -32768 to +32767 2 %d
unsigned int 0 to 65535 2 %u
long signed int -2147483648 to 4 %ld
+2147483647
long unsigned int 0 to 4294967295 4 %lu
Float -3.4e38 to +3.4e38 4 %f
double -1.7e308 to +1.7e308 8 %lf
long double -1.7e4932 to +1.7e4932 10 %Lf
Note: The sizes and ranges of int, short and long are compiler dependent. Sizes
in this figure are for 16-bit compiler.
NULL \0 NULL
Documentation section: It consists of a set of comment lines giving the name of the author date etc. of
program and other details.
Link section: It provides information or instructions to the compiler to link functions from the system
library.
Definition section: It defines all symbolic constants.
Global declaration section: Variables that are declared outside all the functions and are used in more
than one function.
Main function section: This section contains two parts declaration part and execution part.
Subprogram section: It contains all the user defined functions that are called in main functions.
Example:
// Sample of C Program(documentation Section)
#inclufe<stdio.h> // link section
#include<conio.h> // link section
#define pi 3.14 // definition section
int a=10; // global variable declaration
void disp(); // global function declaration
void main() // main function definition
{
float area,r;
printf(“enter radius”);
scanf(“%f”,&r);
area=pi*r*r;
printf(“area=%f”,area);
disp();
getch();
}
void disp() // user defined function definition
{
printf(“hello”);
}
Q5: Define different type of errors in c program.
Ans: There are different types of error in C
1. Syntax error
2. Run Time error
3. Linker error
4. Logical error
5. Semantic error
Syntax error:
• The errors which arises due to violation of any rule or regulation(syntax) of C language during
the development of program those errors are known as Syntax error.
• Syntax errors are also known as the compilation errors as they occurred at the compilation time,.
These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of
the specified programming language.
Examples:-Missing of semicolon or parenthesis (}) or Displaying the value of a variable without its
declaration while writing the code.
1.If we want to declare the variable of type integer,
int a; // this is the correct form
Int a; // this is an incorrect form. .
2. #include <stdio.h>
int main()
{
a = 10; // a is not declared
printf("The value of a is : %d", a);
return 0;
}
3. #include <stdio.h>
int main()
{
int a=2;
if(.) // syntax error we put the (.) instead of condition in 'if', so this generates the syntax error
printf("a is greater than 1");
return 0;
}
Runtime error: The error which occurs during the execution of program those errors are turn termed as
runtime error. The division by zero is the common example of the run-time error. These errors are very
difficult to find, as the compiler does not point to these errors.
Linker error
• Linker errors are mainly generated when the executable file of the program is not created.
• This can be happened either due to the wrong function prototyping or usage of the wrong header
file.
Example1: The most common linker error that occurs is that we use Main() instead of main().
Example2: Using print() instead of printf().
Logical error : The errors which are introduced due to usage of wrong expression formula for logic in
program these errors are called as logical error.
The logical error is an error that leads to an undesired output.
For example using 2 * 3.14 *r as area of circle.
Or by mistake semi colon after for statements.
for(i=0;i<10;i++);
printf(”hello”);
semantic error: This error occurs when a statement is syntactically valid, but does not do
what the programmer intended.
The following can be the cases for the semantic error:
1.Use of a un-initialized variable.
int i;
i=i+2;
2.Type compatibility
int b = "VINEET";
3.Errors in expressions
int a, b;
b = a+”hi” ;
4.Array index out of bound
int a[10];
a[10] = 34;
Important programs:
1. Write a c program to swap two numbers with or without using third variable.
2. Write a program to find area of circle.
3. WAP to find area of triangle using Heron’s formula.
4. WAP to find simple interest.
5. WAP to print ASCII value of entered character.
UNIT-3
Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation and used with integer only.
Operator Description
& Binary AND Operator copies a bit to the
result if it exists in both operands.
| Binary OR Operator copies a bit if it exists in
eather operand.
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
~ Binary Ones Complement Operator is unary
and has the efect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
>> Binary Right Shift Operator. The left
operands value is moved right by the number
of bits specified by the right operand.
Assignment Operators:
Operator Description
= Simple assignment operator, Assigns
values from right side operands to left
side operand
+= Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
-= Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
*= Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
/= Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
%= Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment
operator
|= bitwise inclusive OR and assignment
operator
Misc Operators
Operator Description
sizeof() Returns the size of an variable.
& Returns the address of an variable.
* Pointer to a variable.
?: Conditional Expression
Q2. What do you mean by ternary operator in c? Write a program to find the largest of three
numbers using ternary operator.
Ans- Ternary Operator: In C programming language the operator which takes THREE arguments
(operands) is called as Ternary Operator. The "Conditional Operator" ( ? : ) is called as "Ternary
Operator" in C Language, because this operator takes three operands.
Syntax: condition ? Expression_1 : Expression_2 ;
Here, if the given condition is TRUE then Expression_1 is performed, if the condition is FALSE
then Expression_2 is preformed.
Program to find largest of three using ternary operator :
# include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, big ;
clrscr() ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
getch() ;
}
Output of above program
Enter three numbers : 20 30 10
The biggest number is : 30
| Bitwise OR
^ Bitwise exclusive OR
Operators Meaning of operators
~ Bitwise complement
Bitwise OR operator in C
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming,
bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Q6. What do understand by type conversion? Explain implicit and explicit type conversion with
example.
Ans- Type conversion: Conversion of one data type from another data type is called type casting.
Conversion between data types can be done in two ways :
• Implicit conversion
• Explicit conversion g
Implicit conversion:
Implicit conversion doesn't require a casting operator. This casting is normally used when converting
data from smaller integral types to larger or derived types to the basic type. Implicit Type Conversion
also known as Widening.
int x = 123;
double y = x;
In the above statement, the conversion of data from int to double is done implicitly, in other words
programmer don't need to specify any type operators.
Explicit conversion: Explicit conversion requires a casting operator. This conversion is normally used
when converting a double to int or a base type to a derived type. The Explicit type Conversion is also
known as borrowing.
double y = 123;
int x = (int)y;
In the above statement, we have to specify the type operator (int) when converting from double to int
else the compiler will throw an error.
Q7. Define sizeof() operator with example. Differentiate pre and post increment.
Ans- sizeof() operator
1. sizeof() operator is used to calcualte the size of data type or variables.
2. sizeof() operator will return the size in integer format.
3. sizeof() operator syntax looks more like a function but it is considered as an operator in c
programming
Example of sizeof() operator :
#include<stdio.h>
#include<conio.h>
void main()
{
int ivar;
char cvar;
float fvar;
clrscr();
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
1. If statement: The code inside if body executes only when the condition defined by if statement is
true. If the condition is false then compiler skips the statement enclosed in if’s body. We can have
any number of if statements in a C program.
Syntax:
if (condition)
{
Statements;
}
2. If-else statement: Here, we have two block of statements. If condition results true then if block
gets execution otherwise statements in else block executes. else cannot exist without if statement.
Syntax:
if (condition)
{
Statements;
}
else
{
Statements;
}
3. Switch-case statement: This is very useful when we have several blocks of statements, which
requires execution based on the output of an expression or condition. Switch defines an
expression (or condition) and case has a block of statements, based on the result of expression,
corresponding case gets execution. A switch can have any number of cases; however there should
be only one default handler.
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter number");
scanf("%d",&n);
if(n%2==0)
printf("%d is EVEN\n",n);
else
printf("%d is ODD ",n);
getch();
}
Q9. What is the importance of switch case in c. Write a menu driven program to add, subtract,
multiply and divide two numbers.
Ans-
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among
many alternatives, nested if-else can be used but, this makes programming logic complex. This
type of problem can be handled in C programming using switch statement.
Syntax of switch-case
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement.
If the ndoesn't matches any of the constant in case, then the default codes are executed and
control moves out of switch statement.
The break statement at the end of each case cause switch statement to exit. If break statement is
not used, all statements below that case statement are also executed.
/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */
#include<conio.h>
# include <stdio.h>
void main()
{
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
fflush(stdin);
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case '+':
printf("%f + %f = %f",num1, num2, num1+num2);
break;
case '-':
printf("%f - %f = %f",num1, num2, num1-num2);
break;
case '*':
printf("%f * %f = %f",num1, num2, num1*num2);
break;
case '/':
printf("%f / %f = %f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
}
Q10. What do you understand by else if ladder? Write a program to find largest of three numbers.
Ans- In C programming language the else if ladder is a way of putting multiple ifs together when
multipath decisions are involved. It is a one of the types of decision making and branching statements. A
multipath decision is a chain of if’s in which the statement associated with each else is an if. The general
form of else if ladder is as follows -
if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}
statement-x;
This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder to
downwards. As soon as a true condition is found, the statement associated with it is executed and the
control is transferred to the statement-x (skipping the rest of the ladder). When all the n conditions
become false, then the final else containing the default statement will be executed.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("\n enter three no.");
scanf("%d%d%d",&a,&b,&c);
if(a>=b)
{if(a>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
else
{
if(b>=c)
printf("%d is largest",a);
else
printf("%d is largest",a);
}
}
Q11. Differentiate conditional operator and if else . Write a program to check whether a given year
is leap year or not.
Ans-
In if else statement else is optional Both expr2 and expr3 are needed.
N statement can be written within if and else 1 statement can be written within exp2 and expr3
block. block.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("enter year");
scanf("%d",&n);
if(n%100==0)
{
if(n%400==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
else
{
if(n%4==0)
printf("%d is LEAP YEAR\n",n);
else
printf("%d is NOT LEAP YEAR ",n);
}
}
Q12. Differentiate switch case and if else.
Ans:
If else switch
All data types are permit able in condition Float value is not allowed as case label.
Ans- Iteration, in the context of computer programming, is a process wherein a set of instructions or
structures are repeated in a sequence a specified number of times or until a condition is met. When the
first set of instructions is executed again, it is called iteration. When a sequence of instructions is executed
in a repeated manner, it is called a loop.
There are following differences between while and do-while:
Sr.N. do while While
1. do -while loop runs at least once even while loop do not run in case the condition given is
though the the condition given is false false
2. In a do-while loop the condition is In a while loop the condition is first tested and if it
tested at the last. returns true then it goes in the loop.
3. do while is exit control loop. While loop is entry control loop
4. Syntax do while loop : Syntax while loop:
do while (condition)
{ {
Statements; Statements;
}while(condition); }
Initialization;
do {
some code/s;
At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes false (zero).
{
printf("*");
}
printf("\n");
}
}
}
Unit-4 and 5
Q1. What do you understand by function? Write a program to calculate ab using function (without
using library function pow()).
Ans-
Function in programming is a segment that groups a number of program statements to perform specific
task. A C program has at least one function main( ). Without main() function, there is technically no C
program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int power(int,int);
printf("enter number and its power\n");
scanf("%d%d",&a,&b);
r=power(a,b);
printf("result=%d\t",r);
}
int power(int m,int n)
{
int i,p=1;
for(i=1;i<=n;i++)
p=p*m;
return(p);
}
Q2. What do mean by library function. Explain four type of user defined function with example.
Ans- Library function:
• Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
• Each library function in C performs specific operation.
• We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
• These library functions are created by the persons who designed and created C compilers.
• All C standard library functions are declared in many header files which are saved as file_name.h.
User defined Function: These function are created by user as per his need.
Type of user defined function:
1. No argument no return value
void add(void);
2. With argument but no return value
void add(int,int);
3. No argument with return value
int add(void);
4. With argument with return value
int add(int,int);
Q3. What is recursive function? Write a program to calculate factorial of a number using
recursion.
Recursive Function: Recursive function is the function which calls itself repeatedly until some condition
is met and then the function stops calling itself and returns to the caller.
A recursive function has two parts:
1- Base case (stopping condition)
2-Recursive case :which must always get closer to base case from one invocation to another.
/*program to calculate factorial using recursive function*/
#include<stdio.h>
int fact(int);
int main(){
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}
Q4. Differentiate iteration and recursion. Write a recursive program to find GCD(greatest common
divisor) of two numbers.
Ans- Difference between Recursion and Iteration
RECURSION ITERATIONS
Recursive function – is a function that is partially Iterative Instructions –are loop based
defined by itself repetitions of a process
Infinite recursion occurs if the recursion step does An infinite loop occurs with iteration if the
not reduce the problem in a manner that converges loop-condition test never becomes false
Recursion terminates when a base case is recognized It terminates when the loop-condition fails
Recursion is usually slower then iteration due to Iteration does not use stack so it's faster than
Infinite recursion can crash the system infinite looping uses CPU cycles repeatedly
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,r;
int gcd(int,int); //Function prototype
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
r=gcd(a,b);
else
r=gcd(b,a);
printf("result=%d\t",r);
}
int gcd(int m,int n)
{
if(n==0)
return(m);
else
return(gcd(n,m%n));
}
}
Q5. Differentiate call by value and call by reference with example.
Difference between call by value and call by reference in c:
No. Call by value Call by reference
1 A copy of value is passed to the function An address of value is passed to the function
2 Changes made inside the function is not Changes made inside the function is reflected
reflected on other functions outside the function also
3 Actual and formal arguments will be created Actual and formal arguments will be created
in different memory location in same memory location
Q6. What is pointer? Write a program to swap two numbers using call by reference.
Ans-
Pointer-A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before you can use it to store
any variable address.
The general form of a pointer variable declaration is:
type *var-name;
example- int *p; here p is a pointer which stores the address of an integer variable.
int a,b;
void swap(int *,int *);
printf("enter first no.");
scanf("%d",&a);
printf("enter second no.");
scanf("%d",&b);
printf("before swapping =%d b=%d\n",a,b);
swap(&a,&b);
printf("\nafter swapping in main a=%d b=%d ",a,b);
}
void swap(int *p,int *q)
{
int c;
c=*p;
*p=*q;
*q=c;
printf("after swapping in swap a=%d b=%d ",*p,*q);
}
Q7. What is double pointer? Write a program to calculate area and perimeter of a circle using
pointer.
Ans-
Pointer Stores the address of the Variable. Double Pointer Stores the address of the Pointer Variable.
Double (**) is used to denote the double Pointer.
Exp:
int num = 45 , *ptr , **ptr2 ;
ptr = #
ptr2 = &ptr;
Statement What will be the Output ?
*ptr 45
**ptr2 45
Ptr &num
ptr2 &ptr
• An array is a collection of similar data type elements stored in contiguous memory locations.
• An array is also termed as subscript variable. Here first element is stored as 0th location.
• Till the array is not initialized it contains garbage value while if partially initialized it contains
zero.
• One of the limitation of array is, it does not provide bound checking.
• Array name is base address of array (base address is the address of first element of array). And
You cannot change the base address of array.
Application of Array
Searching- It is the process of finding the location of specific element in an array of n elements. e.g.
linear search, binary search
Sorting- It is the process of arranging the elements in specific order in an array of n elements. e.g. bubble
sort
Example for C Arrays:
• int a[10]; // integer array
• char b[10]; // character array
// WAP to search an element in one dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int i,num,pos,c=0,n;
clrscr();
printf("enter size of array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter value");
scanf("%d",&a[i]);
}
printf("enter number which you want to search");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(num==a[i])
{
printf("%d is found at a[%d]\n",num,i);
c++;
}
}
if(c==0)
printf("%d in not present in array");
else
printf("%d is fount %d times in array",num,c);
getch();
}
Q9. What is 2D array? Write a program to find sum of all elements of 2D array.
Ans- Two dimensional array in C:
• Two dimensional array is nothing but array of array.
• syntax : data_type array_name[num_of_rows][num_of_column]
S.no Array declaration Array initialization Accessing array
Syntax: data_type arr_name data_type arr_name[2][2] =
1 arr_name[index];
[num_of_rows][num_of_column]; {{0,0},{0,1},{1,0},{1,1}};
arr [0] [0] = 1; arr [0]
]1] = 2;arr [1][0] = 3;
2 Example:int arr[2][2]; int arr[2][2] = {1,2, 3, 4};
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n,s=0;
clrscr();
printf("enter the order of matrix");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter matrix");
scanf("%d",&a[i][j]);
s=s+a[i][j];
}
}
printf("\nsum=%d",s);
getch();
}
Q10. What is storage class in c? Explain various storage classes in c in detail.
Ans-
A storage class is an attribute that tells us where the variable would be stored, what will be the initial
value of the variable if no value is assigned to that variable, life time of the variable and scope of the
variable.
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Initial /
Storage Storage
S.No. default Scope Life
Specifier place
value
Structure Union
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. When a variable is associated with a structure, 2. When a variable is associated with a union, the
the compiler allocates the memory for each compiler allocates the memory by considering the
member. The size of structure is greater than or size of the largest memory. So, size of union is
equal to the sum of sizes of its members. The equal to the size of largest member.
smaller members may end with unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in ascending 4. The address is same for all the members of a
order This indicates that memory for each member union. This indicates that every member begins at
will start at different offset values. the same offset value.
5 Altering the value of a member will not affect 5. Altering the value of any of the member will
other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize at 7. Only the first member of a union can be
once. initialized.
Q11. What is union? Write a program to print the record of student having maximum marks.
Structure student has following fields: Integer roll number, string student name, string class name,
integer marks.
Ans- A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for multi-
purpose.
Defining a Union: To define a union, you must use the union statement. Here is the way you would
define a union type named Data which has the three members i, f, and str. The format of the union
statement is as follows:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. The
memory occupied by a union will be large enough to hold the largest member of the union. For example,
in above example Data type will occupy 20 bytes of memory space because this is the maximum space
which can be occupied by character string.