0% found this document useful (0 votes)
41 views40 pages

Solution - List of Important Questions

The document provides an overview of key concepts in computer science, including digital computers, memory hierarchy, operating systems, algorithms, flowcharts, and data types in C language. It explains various components of digital computers, functions of operating systems, and characteristics of algorithms. Additionally, it discusses type conversion, operators, and their precedence and associativity in C programming.

Uploaded by

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

Solution - List of Important Questions

The document provides an overview of key concepts in computer science, including digital computers, memory hierarchy, operating systems, algorithms, flowcharts, and data types in C language. It explains various components of digital computers, functions of operating systems, and characteristics of algorithms. Additionally, it discusses type conversion, operators, and their precedence and associativity in C programming.

Uploaded by

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

PRANVEER SINGH INSTITUTE OF TECHNOLOGY

Programming for Problem Solving(BCS-101/BCS-201)


IMPORTANT QUESTIONS

1.What is digital computer? Draw block diagram of digital computer and explain each component of it.
Ans: A digital computer is an electronic device working on 0’s and 1’s. It was invented by Charles Babbage
who is known as the “Father of Modern Digital Computer”.
Functional Components of digital computer:
1. Input Unit
2. Output Unit
3. Storage Unit
4. Processing Unit (CU and ALU)

Input Unit:
Performs the following functions:
1. It accepts or reads the data and program (set of instructions).
2. It converts these instructions and data in computer acceptable form.
3. It supplies the converted instructions and data to the computer system for further processing.
– Keyboard, Mouse, Scanner, Digital Camera etc.

Block Diagram of the digital computer

Output Unit:
Performs the following functions:
 It accepts the results produced by the computer which are in coded (binary) form.
 It converts these coded results to human acceptable form.
 It supplies, the converted results to the outside world.
-monitor, printer, plotter etc.

Storage Unit:
Page 1
Performs following functions:
 It stores the data and the program (set of instructions).
 It holds the intermediate results during processing.
 It stores the final results of processing before they are passed onto the output unit.
-RAM, ROM

Central Processing Unit:


The major sections of a CPU are:
(i) Arithmetic and Logic Unit (ALU),
(ii) Control Unit (CU).
ALU: Performs arithmetic and logic operations such as addition, subtraction, multiplication and division:
AND, OR, NOT, EXCLUSIVE-OR Operations.
Control Unit: The control unit is the most important part of the C.P.U. as it controls and co-ordinates the
activities of all other units such as ALU, memory unit, input and output unit.
 Gets the instructions from the memory unit.
 Decodes the instructions.
Generates control signals accordingly for other units.

2.Explain memory hierarchy with the help of diagram.


Ans: Memory hierarchy is arranging different kinds of storage present on a computing device based on
speed of access, storage capacity and cost per bit.
At the very top, the highest performing storage is CPU registers which are the fastest to read and write to.
Next is cache memory followed by conventional RAM memory, followed by disk storage with different
levels of performance including optical and magnetic disk drives.

3.What is an Operating System? Discuss various functions of Operating System.


Ans: An operating system is a system software that acts as a bridge between the user and the hardware.
Operating system is an important software that does critical maintenance and scheduling of tasks in a
system. Some of the most important functionalities of an operating are:
Page 2
Functions of Operating System:
1. Memory Management:
 allocation of memory to the running programs
 removes the programs from memory when it completes
2. Process management:
 processing the jobs, deciding on the job scheduling technique
3. Device management (Resource Allocation):
 allocating the input and output devices to the running processes and de-allocating them when the
processes are over.
4. File Management:
 Managing the file system in terms of where the files are stored, their status and memory locations
 Opening and closing the file
5. Input/Output Management:
 Managing input and output operations between the computer and external devices, such as
keyboards, mice, printers, hard drives, and monitors.

4. Write short notes on i) Compiler ii) Interpreter iii) Assembler iv) Loader v) Linker
Ans: Compiler:
A compiler is a computer program (or a set of programs) that transforms source code written in a
programming language (the source language) into another computer language (the target
language) or machine language. The entire source code is translated into machine code all at once.
Errors found wherever are listed towards the end.

Interpreter:
An interpreter is a common kind of language processor. Instead of producing target program as a
translation, an interpreter appears to directly execute the operations specified in the source
program on inputs supplied by the user.
In contrast to the compiler, an interpreter reads a statement from the input, converts it to an
intermediate code, execute it, then takes the next statement in sequence.
If an error occurs, an interpreter stops execution and reports it.

Page 3
Assembler:
An assembler translates assembly language programs into machine code. The output of a
assembler is called an object file, which contains a combination of machine instruction as well as
the data required to place these instructions in memory.

Linker:
Linker is a computer program that links and merges various object files together in order to make
an executable file. All these files might have been compiled by separate assembler.
The major task of a linker is to search and locate referenced module/routines in a program and to
determine the memory location where these codes will be loaded making the program instruction
to have absolute reference.

Loader:
Loader is a part of operating system and is responsible for loading executable files into memory
and execute them.
Sends the starting address of the program to the Memory Address Register (MAR) and the
Program Counter (PC) so that Control Unit reads this address and starts the execution of the
program.
It calculates the size of a program (instructions and data) and requests the OS for the memory
space for it. It initializes various registers to initiate execution.

5.What do you mean by an algorithm? Discuss characteristics of a good algorithm.


Ans: An algorithm is a step by step sequence of instructions for solving any problem. Some of the
characteristics of a good algorithm are as below:
Characteristics:
1.Finiteness: An algorithm must terminate after a finite number of steps and further each step must be
executable in finite amount of time.
2. Definiteness (no ambiguity): Each steps of an algorithm must be precisely defined.
3.Inputs: An algorithm has zero or more but only finite, number of inputs.

Page 4
4.Output: An algorithm has one or more outputs
5.Effectiveness: An algorithm should be effective. This means that each of the operation to be performed
must be sufficiently basic that it can, in principle, be done exactly and in a finite length of time, by person
using pencil and paper.

6.What do you mean by flowchart? Discuss the different symbols used in flowchart.
Ans: A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be
defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task.
Different symbols used in a flowchart are as below:

Symbol Name Symbol Representation


Terminal/Terminator

Process

Decision

Data or Input/Output

Flow Arrow

On-page connector/reference

Off-page connector/reference

Page 5
(i) Draw a flowchart to find the factorial of the given number.

(ii) Write an algorithm and draw a flowchart for finding the largest among 3 numbers.
Algorithm:
Step 1: Enter 3 numbers : a, b, c.
Step 2 : if a>b then goto Step 3 else goto Step 5
Step 3 : if a > c then print “a is largest” goto Step 6 else goto Step 4
Step 4 : print “c is largest” goto Step 6
Step 5: if b> c then print “b is largest” else goto Step 4
Step 6 : stop.

Page 6
Flowchart:

(iii) Draw a flowchart to sum first n natural numbers.

(iv) Write an algorithm and draw a flowchart to check leap year.


Algorithm:
Step 1 : Enter any year.
Step 2 : if year is divisible by 100 goto Step 3 else goto Step 6
Step 3 : if year is divisible by 400 then goto Step 4 else goto Step 5
Step 4 : print “Year is leap year” goto Step 7.
Step 5 : print “Year is NOT leap year” goto Step 7.
Page 7
Step 6 : if year is divisible by 4 then goto Step 4 else goto Step 5.
Step 7 : Stop.

Flowchart:

(v) Draw a flowchart to check whether a triangle is isosceles, equilateral or scalene.

(vi) Develop an algorithm to check that given number is prime number or not.
Algorithm:
Step 1 : Enter a number , N
Step 2 : Take K = 2
Step 3 : if N is divisible by K then goto Step 7 else goto Step 4
Step 4 : K= K+1
Page 8
Step 5 : if K < N goto Step 3 else goto Step 6
Step 6 : print “Number is Prime” goto Step 8
Step 7: Print “Number is NOT prime
Step 8 : Stop

(vii) Draw flowchart to check that entered number is palindrome or not.

(viii) Draw a flowchart to print Fibonacci series of n terms.

Page 9
7.Differentiate between:
(i) System Software and Application Software
System Software -- System Software is the type of software that is the interface between application
software and the system. Low-level languages are used to write the system software. System Software
maintains the system resources and gives the path for application software to run. An important thing
is that without system software, the system can not run. It is general-purpose software.
Application Software -- Application Software is the type of software that runs as per user request. It
runs on the platform which is provided by system software. High-level languages are used to write the
application software. It’s a specific purpose software. The main difference between System Software
and Application Software is that without system software, the system can not run on the other hand
without application software, the Low-level maintenance system always runs.

(ii) Machine Language, Assembly Language and High Level Language:

Page
10
(iii) Compiler and Interpreter

8.What are different data types in C language? Explain range, memory size and format specifier of
primitive data types.
Ans: Each data in C is associated with some data type. The data type tells the compiler type of data to be
held in a variable, number of bytes it will occupy in the RAM and range of values held by a variable.
Accordingly, the data types in C are divided into 3 categories primitive, derived and user-defined.

A) Primitive data types-these are in-built into the language and compiler understands their meaning by
default. Eg: int, float, char, double, void
B) Derived data type –these are made from the primitive data types. Eg: arrays, pointers, functions.
C) User defined data types –these are custom built data types that are designed by the programmer as

Page
11
and when needed. Eg: unions, structures, user-defined functions, enumerations.

Integers:
Keyword –int
Memory occupied –4 bytes
Data type specifier used --%d
Range ---2,147,483,648 to 2,147,483,647
The integer data type can also be used as
unsigned int: Unsigned int data type in C is used to store the data values from zero to positive numbers
but it can’t store negative values like signed int. Range is 0 to 2^32-1
short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to 32,767.
long int:Larger version of the int data type so can store values greater than int.
unsigned short int: Similar in relationship with short int as unsigned int with int. Range is 0 to 65535
Note : The size of an integer data type is compiler-dependent. We can use sizeof operator to check the
actual size of any data type.

Floating point:
Keyword – float
Range:1.2E-38 to 3.4E+38
Size:4 bytes
Format Specifier:%f

Double :
Keyword – double
Range:1.7E-308 to 1.7E+308
Size:8 bytes
Format Specifier:%lf

Character:
Keyword – char
Range : signed char -- -128 to +127, unsigned char – 0 to 255
Size : 1 byte
Format specifier : %c

Page
12
9.What is meant by type conversion? Explain about Implicit and Explicit type conversion with
examples.
Ans: Type conversion means converting data of one type into another.
Its of two types --implicit and explicit.
Implicit - happens automatically/naturally by the compiler.
Implicit conversion without data loss when smaller type goes into bigger type. Eg: int I=5; float f; f = I ;
Here , f will get 5.0 as integer will get converted into floating point.
Implicit conversion with data loss when bigger type goes into smaller type. Eg: int I; float f = 5.5; I = f;
Here, I will get the value 5 as the data loss of 0.5 occurs when floating point values goes into integer
type.
Explicit -this is forcefully done by programmer using the (type) cast operator.
Page
13
Explicit conversion without data loss when smaller type goes into bigger type. Eg. Char c= ‘a’ ; float f; f =
(float) c; Here, c gets explicitly type casted to float.
Explicit type conversion with data loss is when bigger type goes into smaller type. Eg: char c; float f=3.5;
c = (char) f; Here, 3.5 gets explicitly converted into character and data loss is there as c is assigned value
3.
Following is the waterfall model for implicit type conversions:

10. What are operators? Illustrate the Concept of Operator Precedence and Associativity with example.
An Operator is a symbol that tells the compiler to perform specific task.
Operands are data elements on which operator acts.
Let’s take an example sum = 10 + 20; Here
the '+' ( Plus ) is an Addition Operator and numbers 10 and 20 are the operands.
Precedence: The concept of operator precedence helps in determining which operators will be given
priority when there are multiple operators in the expression.
Associativity: Operator associativity is used when two operators of the same precedence appear in an
expression. The associativity of operators determines the direction in which an expression is evaluated.
Associativity can be either from Left to Right or Right to Left.
int main()
{
int a;
a=2*3+4%5–3/2+6;
printf(“%d”,a); //15
return 0;
}
Explanation:
a=6+4%5-3/2+6
a=6+4-3/2+6
a=6+4-1+6
Page
14
a=10-1+6
a=9+6
a=15
int main()
{
int a=3,b=2,c=1,d;
d=a<b<c-1;
printf(“%d”,d); //0
return 0;
}

Explanation: Out of =, < and – operators, – operator has the highest precedence. < is left to right
associative
Output will be 0.

11. Explain different types of operators in C with precedence and associativity.

Ans: C has a wide range of built-in operators that can be classified into various types according to their
functionality.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Conditional Operator
6. Miscellaneous Operator

Arithmetic Operators:
These operators perform basic mathematical operations like addition, subtraction, multiplication, and division.
Operator Name of the Operator Syntax
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus (remainder) x%y
++ increment x++ or ++x
-- decrement x-- or --x

Relational Operators
These are used for the comparison of the values of two operands.
Ex: <, <=, >, >=, = = and !=
Page
15
Logical Operator
Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the
original condition in consideration. The result of the operation of a logical operator is a Boolean value
either true or false.
Ex: &&, | | and !

Bit-wise Operators
The Bit-wise operators are used to perform bit-level operations on the operands. The operators are first converted to
bit-level and then the calculation is performed on the operands.
Ex: &, |, ~, ^, << , >> etc.

Conditional Operator:
It takes three operands: a condition followed by a question mark (?), a result if the condition is true, and a result if the
condition is false. It's used as a compact way to express simple conditional statements.
Syntax: condition ? value_if_true : value_if_false
Example:
int a = 5, b = 10;
int max = (a > b) ? a : b; // max will be assigned the greater of a or b

Miscellaneous operators: comma, sizeof, & (address of) etc.

Operator
Precedence Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement


2 Right-to-Left
+/– Unary plus, minus

Page
16
Operator
Precedence Description Associativity

!,~ Logical NOT, Bitwise complement

(type) Cast Operator

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to

6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

Page
17
Operator
Precedence Description Associativity

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

^= , |= Bitwise exclusive, inclusive OR assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

12. Define Conditional Operator with an example.


The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm
as of if-else statement but the conditional operator takes less space and helps to write the if-else
statements in the shortest way possible. It is also known as the ternary operator in C as it operates on
three operands. Syntax of Conditional/Ternary Operator in C
variable = (condition) ? Expression1 : Expression2;
Here, if the condition is true or nonzero expression1 will be assigned to the variable.
Otherwise, expression2 will be assigned.
#include <stdio.h>
int main()
{
int m , n ,large;
Printf(“enter value for m and n”);
Scanf(“%d %d”, &m,&n);
large= (m > n) ? m:n;
printf("large=%d",large);
return 0;
}
enter value for m and n 10 20
large=20

Page
18
13. Explain various Bit-wise operators in C Language with help of an example.
Bitwise operators do not consider operand as one entity and operate on the individual bits of operands.
They can be applied on operands of type char, short, int, long whether signed or unsigned.The various
bitwise operators in C are:
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.

2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two numbers.
The result of OR is 1 if any of the two bits is 1.

3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of two numbers.
The result of XOR is 1 if the two bits are different.

4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and the
second operand decides the number of places to shift.

5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and the second
operand decides the number of places to shift.

6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

Example : Assume A = 60 and B = 13 in binary format, they will be as


A = 0011 1100
B = 0000 1101
A&B = 0000 1100 =12
A|B = 0011 1101=61
A^B = 0011 0001=49
~A = 1100 0011
A << 2 = 1111 0000=240
A >> 2 = 0000 1111=15

14. What are different conditional statements in C programming? Explain with proper example of each.
In C programming, conditional statements allow the program to execute different blocks of code
based on certain conditions. These conditions evaluate to either true or false. The major types of
conditional statements in C are:
1. if Statement
The if statement evaluates a condition. If the condition is true (non-zero), the code inside the if block is
executed.

Page
19
#include <stdio.h>
int main()
{
int x = 10;
if (x > 5)
{
printf("x is greater than 5\n");
}
return 0;
}
In this example, since x is 10, which is greater than 5, the condition evaluates to true, and the
statement "x is greater than 5" is printed.

2. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.

#include <stdio.h>
int main()
{
int x = 3;
if (x > 5)
{
printf("x is greater than 5\n");
}
else
{
printf("x is less than or equal to 5\n");
}
Page
20
return 0; }
In this case, since x is 3, the condition x > 5 is false, so the program executes the else block, printing
"x is less than or equal to 5".

3. if-else Ladder
The if-else if-else ladder is used when you have multiple conditions to check. Each if or else if
checks a condition, and if one condition is true, the associated block of code is executed. If none of
the conditions are true, the final else block will execute.
#include <stdio.h>
int main()
{
int x = 15;
if (x > 15)
{
printf("x is greater than 15\n");
}
else if (x == 15)
{
printf("x is equal to 15\n");
}
else
{
printf("x is less than 15\n"); } return 0; }
Since x is 15, the second condition x == 15 is true, so the output is "x is equal to 15".

4. switch Statement
The switch statement is used when you need to compare a single variable against a list of constant
values (cases). Each case is tested, and if a match is found, the corresponding block of code is
executed. The break statement is typically used to exit the switch after a case is executed.
#include <stdio.h>
int main()
{
int day = 3;
switch(day)
{
case 1: printf("Monday\n");
break; // Exits the switch block after case 1
case 2: printf("Tuesday\n");
break; // Exits the switch block after case 2
case 3: printf("Wednesday\n");
break; // Exits the switch block after case 3
case 4: printf("Thursday\n");
break; // Exits the switch block after case 4
default: printf("Invalid day\n");
}
return 0;
Page
21
}
Since day is 3, the program will execute the case 3, printing "Wednesday"

15. Explain the use of break in switch statement with example.


The break statement in a switch statement is used to terminate the execution of a particular case. When a
break is encountered, the control is transferred outside of the switch statement, and no further cases are
executed. If the break is omitted, the control "falls through" to the next case, which means that the code
will continue executing subsequent cases until it encounters a break or the end of the switch block.

Purpose of break:

 Exit the switch block: The break ensures that once a matching case is found and executed, the program
doesn't execute other cases unintentionally.
 Prevent fall-through: Without break, the program would continue executing the next case, even if it
wasn't a match.

#include <stdio.h>
int main()
{
int day = 3;
switch(day)
{
case 1: printf("Monday\n");
break; // Exits the switch block after case 1
case 2: printf("Tuesday\n");
break; // Exits the switch block after case 2
case 3: printf("Wednesday\n");
break; // Exits the switch block after case 3
case 4: printf("Thursday\n");
break; // Exits the switch block after case 4
default: printf("Invalid day\n");
break; // Exits the switch block after default case
}
return 0;
}
Input 3
Output Wednesday

Page
22
16. Differentiate between switch and if-else with examples.

Using switch case


#include <stdio.h>
int main() {
// Day number
int day = 2;
// Switch statement to print the name of the day
// on the basis of day number
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");

Page
23
break;
default:
printf("Invalid Input");
break;
}
Using If else
#include <stdio.h>
int main()
{
// Day number
int day = 2; // Using if-else statements to print the name of the day
if (day == 1)
{
printf("Monday");
}
else if (day == 2)
{
printf("Tuesday");
} else if (day == 3)
{
printf("Wednesday");
}
else if (day == 4)
{
printf("Thursday");
}
else if (day == 5)
{
printf("Friday");
}
else if (day == 6)
{
printf("Saturday");
}
else if (day == 7)
{
printf("Sunday");
}
else
{
printf("Invalid Input");
}
Page
24
return 0; // Indicating successful completion of the program
}

17. Differentiate between entry controlled and exit controlled loop with suitable examples.
In an entry controlled loop, the condition to enter the loop is evaluated before the loop body is
executed. This means that the loop is only entered if the condition evaluates to true initially. If the
condition is false from the outset, the loop is bypassed entirely. The condition is evaluated at the
beginning of each iteration, and if it becomes false at any point, the loop terminates.
An exit controlled loop evaluates its condition after executing the loop body. This means that the loop
body is executed at least once, regardless of the condition. After each iteration, the condition is
evaluated, and if it becomes false, the loop terminates.

Entry Controlled Loop Entry Controlled Loop

Condition is evaluated before body of loop Condition is evaluated after body of loop is
is executed. executed.

Loop body may not execute if condition is Loop body executes at least once before condition
false initially. evaluation.

while (condition)
do {
{
// Loop body
// Loop body
} while (condition);
}

Used when the loop may not need to


Used when the loop body must execute at least
execute at all if the condition is initially
once before evaluating the condition.
false.

#include <stdio.h>
int main()
{ int i = 1;
// Entry-controlled loop (while)
while (i <= 5)
{
printf("This is iteration %d of the entry-controlled loop\n", i);
i++; // Increment the value of i
}
return 0;
}
Page
25
In the while loop, the condition i <= 5 is checked before the loop body executes.
The loop will continue as long as the condition is true.
If the condition is false at the first check, the loop body will not execute at all.

#include <stdio.h>
int main()
{ int i = 1;
// Exit-controlled loop (do-while)
do { printf("This is iteration %d of the exit-controlled loop\n", i);
i++; // Increment the value of i
} while (i <= 5);
return 0; }
in the do-while loop, the body of the loop is executed first, and then the condition i <= 5 is checked.
The loop will run at least once, even if the condition is false initially.

18. Differentiate between break and continue with examples.

int main()
{
int i, number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf(“enter number”);
scanf("%d", &number);
Page
26
if (number < 0)
{
break;
}
sum += number;
}
printf("Sum = %d", sum);
return 0;
}

The program prompts the user to enter a number.


If a negative number is entered, the loop will terminate early because of the break statement.
Otherwise, the number is added to the sum.
After the loop finishes, the program prints the sum of the entered numbers.

int main()
{
int i, number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf(“enter number”);
scanf("%d", &number);
if (number < 0)
{
continue;
}
sum += number;
}
printf("Sum = %d", sum);
return 0;
}
The program asks the user to input a number.
If the user enters a negative number, the continue statement causes the program to skip the current
iteration (the negative number is not added to sum) and prompts the user for another number.
If the number is positive, it gets added to the sum.
The program keeps asking for numbers until 10 iterations are completed.

Page
27
19. What are functions? What are advantages of using multiple functions in a program?
ANS: Function: A function in C is a set of statements that when called perform some specific task. It is
the basic building block of a C program that provides modularity and code reusability.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1.Function Declaration
2.Function Definition
3.Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the number and
type of its parameters. A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.
Syntax: return_type name_of_the_function (parameter_1, parameter_2);

Example
int sum(int a, int b);
int sum(int , int);

Function Definition
The function definition consists of actual statements which are executed when the function is called
(i.e. when the program control comes to the function).
Syntax:
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}

Function Call
A function call is a statement that instructs the compiler to execute the function. We use the function
name and parameters in the function call.
Syntax: function_name (para1_type para1_name, para2_type para2_name);

Example of C Function

Page
28
Using multiple functions in a program can have many advantages, including:
 Reusability: Functions can be called multiple times in a program or even in different programs,
without having to rewrite the same code.
 Modularity: Functions break a large program into smaller, more manageable pieces.
 Readability: Functions can make code easier to understand and manage.
 Reduced redundancy: Functions can reduce redundancy by avoiding rewriting the same code.
 Top-down modular programming: Functions allow for top-down modular programming, where the
high-level logic of the problem is solved first, followed by the details of each lower-level function.
 Source program length: Functions can reduce the length of the source program.
 Faulty function location: Functions make it easier to locate and separate a faulty function for
further study.
 Use by other programs: Functions can be used by many other programs, allowing programmers to
use functions written by others.

28. What is a pointer in C? Discuss pointer arithmetic.


Ans. A pointer is a variable that stores the memory address of another variable, instead of a
value. Pointer arithmetic is the set of mathematical operations that can be performed on pointers to
navigate through memory.
some pointer arithmetic operations:
 Incrementing a pointer: The ++ operator adds an offset to the current memory address. For example,
if p is a pointer to an integer array, p + 1 points to the next integer in the array.
 Subtracting an integer from a pointer: Moves the pointer backward.

Page
29
 Subtracting two pointers of the same type: Finds the number of elements between them.
 Comparing pointers: A valid operation in C.
 Pointer arithmetic is dependent on the data types and pointer types. The amount of increment
performed on a pointer depends on the size of the data type it is pointing to. This behavior is known as
pointer scaling.

29. Discuss dynamic memory allocation. Explain calloc(), malloc(), realloc() and free() functions with
suitable examples.
Ans.C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like
Array) is changed during the runtime. C provides some functions to achieve these tasks. There are 4 library
functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any
form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default
garbage value initially.
Syntax of malloc() in C
Ptr=(cast-type*)malloc(byte-size)
For Example:
ptr=(int*)malloc(100*sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr
holds the address of the first byte in the allocated memory.

Page
30
If space is insufficient, allocation fails and returns a NULL pointer.

C calloc() method

“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of
blocks of memory of the specified type. it is very much similar to malloc() but has two different points and
these are:

It initializes each block with a default value ‘0’.


It has two parameters or arguments as compare to malloc().

Syntax of calloc() in C

ptr=(cast-type*)calloc(n,element-size);

here, n is the no. of elements and element-size is the size of each element.

For Example:

ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the float.

Page
31
C free() method

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the
dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax of free() in C
free(ptr);

C realloc() method

“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously
allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the
already present value and new blocks will be initialized with the default garbage value.

Syntax of realloc() in C

ptr=realloc(ptr,newSize);

where ptr is reallocated with new size 'newSize'.

Page
32
30. Differentiate between malloc() and calloc() functions

S.No. malloc() calloc()

Page
33
S.No. malloc() calloc()

calloc() is a function that assigns a specified


malloc() is a function that creates one
number of blocks of memory to a single
block of memory of a fixed size.
1. variable.

2. malloc() only takes one argument calloc() takes two arguments.

3. malloc() is faster than calloc() calloc() is slower than malloc()

4. malloc() has high time efficiency calloc() has low time efficiency

malloc() is used to indicate memory calloc() is used to indicate contiguous memory


5. allocation allocation

6. Syntax: void* malloc(size_t size); Syntax: void* calloc(size_t num, size_t size);

malloc() does not initialize the memory


calloc() initializes the memory to zero
7. to zero

malloc() does not add any extra


calloc() adds some extra memory overhead
8. memory overhead

Page
34
31. What are structures? Write the syntax of structure. Discuss various ways to access the members of structure.
The structure in C is a user-defined data type that can be used to group items of possibly different types into a
single type. The struct keyword is used to define the structure in the C programming language. The items in
the structure are called its member and they can be of any valid data type. Additionally, the values of a
structure are stored in contiguous memory locations.

C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we specify its
member variables along with their datatype. We can use the struct keyword to declare the structure in C using
the following syntax:
Syntax
Struct structure_name
{
data_type member_name1;
data_type member_name1;
....
....
};
Accessing Structure Members
We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access the
members.

Page
35
32. Differentiate between structure and union.

Parameter Structure Union

A structure is a user-defined
data type that groups A union is a user-defined data type that allows storing
different data types into a different data types at the same memory location.
Definition single entity.

The keyword struct is used to


The keyword union is used to define a union
Keyword define a structure

The size is the sum of the


The size is equal to the size of the largest member, with
sizes of all members, with
possible padding.
Size padding if necessary.

Each member within a


structure is allocated Memory allocated is shared by individual members of
Memory unique storage area of union.
Allocation location.

Data No data overlap as members


Full data overlap as members shares the same memory.
Overlap are independent.

Accessing Individual member can be


Only one member can be accessed at a time.
Members accessed at a time.

Page
36
33. What do you mean by C pre-processor? Define the function of a C pre-processor. Explain any
three pre- processor directives.

Preprocessors are programs that process the source code before compilation.

The C preprocessor has several functions, including:


 Defining macros
The preprocessor allows you to define macros, which are brief abbreviations for longer constructs.
 Including header files
The preprocessor can include header files, which are files that contain declarations.
 Conditional compilation
The preprocessor can control whether the compiler includes or excludes parts of the code based on conditions
evaluated at compile time.
 Line control
The preprocessor can handle line numbers on errors and warnings. It can also change the line number and
source files while generating output during compile time.
 Concatenation
The preprocessor can join two strings into one. In the context of macro expansion, concatenation joins two
lexical units into one longer one.
There are 3 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
1.Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is

Page
37
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
Syntax of Macro Definition
#define token value
where after preprocessing, the token will be expanded to its value in the program.

2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program.
The #include preprocessor directive is used to include the header files in the C program.
There are two types of files that can be included by the user in the program:
Standard Header Files
The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc.
Syntax
#include <file_name>
where file_name is the name of the header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler
to look for the file in the standard directory.
User-defined Header Files
When a program becomes very large, it is a good practice to divide it into smaller files and include them
whenever needed. These types of files are user-defined header files.
Syntax
#include "filename"
The double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory.

3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of the
program or to skip the compilation of some specific part of the program based on some conditions.
There are the following preprocessor directives that are used to insert conditional code:
1. #if Directive
2. #ifdef Directive
3. #ifndef Directive
4. #else Directive
5. #elif Directive
6. #endif Directive
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the
preprocessing of these directives is completed.

34. What is macro? How is it substituted? Explain various types of macros with suitable examples.
Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is encountered by
the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to

Page
38
define a macro.
Syntax of Macro Definition
#define token value
where after preprocessing, the token will be expanded to its value in the program.
Macros With Arguments
We can also pass arguments to macros. Macros defined with arguments work similarly to functions.
Example
#define foo(a,b) a+b
#define func(r) r * r

35. Define file. Explain the different file opening modes in C. Discuss basic file handling functions.
File is a collection of data or information that can be created, read, written, updated, deleted, or closed
using file-handling functions in C. The different modes for opening a file in C are:
 r: Opens a file in read mode
 w: Opens or creates a text file in write mode
 a: Opens a file in append mode
 r+: Opens a file in both read and write mode
 a+: Opens a file in both read and write mode
 w+: Opens a file in both read and write mode
The mode determines how the program interacts with the file's content.
Here are some basic file handling functions in C:
 fopen( ): Opens a file
The fopen( ) function can not only open a file but also can create a file if it does not exist already. For that,
we have to use the modes that allow the creation of a file if not found such as w, w+, wb, wb+, a, a+, ab,
and ab+.

 fprintf( ): Writes to a file


 fscanf( ): Reads from a file
 fclose( ): Closes a file
 fgetc( ): Returns a single character from the file

36. Write short note on Linked list.


A linked list is a sequence of nodes where each node contains two parts:
 Data: The value stored in the node.
 Pointer: A reference to the next node in the sequence.

Unlike arrays, linked lists do not store elements in contiguous memory locations. Instead, each node
points to the next, forming a chain-like structure and to access any element (node), we need to first
sequentially traverse all the nodes before it.
In C, linked lists are represented as the pointer to the first node in the list. For that reason, the first
Page
39
node is generally called head of the linked list
 Each node of the linked list is represented by a structure that contains a data field and a pointer of
the same type as itself. Such structure is called self-referential structures.

Page
40

You might also like