0% found this document useful (0 votes)
12 views

Course File

The document discusses different types of operating systems including batch, multiprogramming, multiprocessing, and multitasking operating systems. It provides details on the key characteristics, advantages, and disadvantages of each type of operating system.

Uploaded by

pramodmauryapk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Course File

The document discusses different types of operating systems including batch, multiprogramming, multiprocessing, and multitasking operating systems. It provides details on the key characteristics, advantages, and disadvantages of each type of operating system.

Uploaded by

pramodmauryapk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Rajshree Group of Institutions,

Bareilly

Department of Computer Science & Engineering

Course File
Programming for Problem Solving
BCS-201

Submitted By:

Pramod Kumar Maurya


Assistant Professor

Rajshree Group of Institutions, Bareilly


Mission
“To emerge as a “Centre for Excellence” offering quality education and research
opportunities of high standards to students, develop the total personality of the
individual, and instil high level of discipline and strive to set global standards,
making our students professionally fit.”

Vision
“To emerge as one of the world`s leading educational groups by achieving the
highest academic standards, developing strong industry academic bonds and
providing world-class education, consultancy and outreach services.”
Solution Unit test-2
Programming for Problem Solving (BCS-201)
1(a):

Parameter Compiler Interpreter

Program Compilers scan the entire The program is interpreted/translated one


scanning program in one go. line at a time.

Error detection As and when scanning is One line of code is scanned, and errors
performed, all the errors are encountered are shown.
shown in the end together, not
line by line.

Object code Compilers convert the source Interpreters do not convert the source code
code to object code. into object code.

Execution time The execution time of compiler is It is not preferred due to its slow speed.
less, hence it is preferred. Usually, interpreter is slow, and hence takes
more time to execute the object code.

Need of source Compiler doesn’t require the It requires the source code for execution
code source code for execution later. later.

Programming Programming languages that use Programming languages that uses interpreter
languages compilers include C, C++, C#, include Python, Ruby, Perl, MATLAB, etc.
etc..

Types of errors Compiler can check syntactic and Interpreter checks the syntactic errors only.
detected semantic errors in the program
simultaneously.

Size Compiler are larger in size. Interpreters are smaller in size.

Flexibility Compilers are not flexible. Interpreters are relatively flexible.

Efficiency Compilers are more efficient. Interpreters are less efficient.


1(b): #include <stdio.h>
int main()
{
int year;

printf("Enter any year: ");


scanf("%d", &year);
(year%4==0 && year%100!=0) ? printf("LEAP YEAR") :
(year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON
YEAR");
return 0;
}

1(c):

Parameter Entry Control Exit Control

Flow of loop The condition is tested at the beginning The condition is tested at the end of the Loop
of the Loop before the loop body after the loop body is executed at least once.
executes.

The number of times The loop body may not be run if the The loop body runs at least once, even if the
the loop is executed condition is false. condition is false.

Example loops While Loop, For are some popular Entry Do-while is usually used as Exit Controlled
Controlled Loops. Loop.

Efficiency Since the condition is tested at the Exit-controlled loops consistently execute the
beginning of the Loop, the loop body's loop body at least once, which can be less
code can be skipped if it is false. efficient if the condition is false.

Application It is mostly used when we know how It is used when the loop body’s code needs
many iterations are required and the to be executed at least once.
loop condition is always met.

1(d): COMPUTER SYSTEM


Definition: Is a collection of entities (hardware, software and liveware) that are designed to receive,
process, manage and present information in a meaningful format.

COMPONENTS OF COMPUTER SYSTEM

 Computer hardware - Are physical parts/ intangible parts of a computer. eg Input devices,
output devices, central processing unit and storage devices

 Computer software - also known as programs or applications. They are classified into two
classes namely - system software and application software

A computer system is a set of integrated devices that input, output, process, and store data and
information. Computer systems are currently built around at least one digital processing device.
There are five main hardware components in a computer system: Input, Processing, Storage, Output
and Communication devices.
1. INPUT DEVICES Are devices used for entering data or instructions to the central processing
unit. Are classified according to the method they use to enter data.

i) keyboard
ii) Mouse
iii) Joystick
iv) Scanner
v) Microphone
vi) MICR
vii) OCR

2.Output Devices:

I. Monitor
II. Speaker
III. Printer
IV. Plotter

1(e): Volatile memory, in contrast to non-volatile memory, is computer memory that


requires power to maintain the stored information; it retains its contents while powered on but
when the power is interrupted, the stored data is quickly lost.
Volatile memory has several uses including as primary storage. In addition to usually being faster
than forms of mass storage such as a hard disk drive, volatility can protect sensitive information,
as it becomes unavailable on power-down. Most general-purpose random-access
memory (RAM) is volatile.

2(b): Types of Operating Systems (OS)


An operating system is a well-organized collection of programs that manages the computer
hardware. It is a type of system software that is responsible for the smooth functioning of the
computer system.

Batch Operating System


In the 1970s, Batch processing was very popular. In this technique, similar types of jobs were
batched together and executed in time. People were used to having a single computer which was
called a mainframe.
In Batch operating system, access is given to more than one person; they submit their respective
jobs to the system for the execution.
The system put all of the jobs in a queue on the basis of first come first serve and then executes
the jobs one by one. The users collect their respective output when all the jobs get executed.
The purpose of this operating system was mainly to transfer control from one job to another as
soon as the job was completed. It contained a small set of programs called the resident monitor
that always resided in one part of the main memory. The remaining part is used for servicing
jobs.
Advantages of Batch OS
o The use of a resident monitor improves computer efficiency as it eliminates CPU time
between two jobs.
Disadvantages of Batch OS
Multiprogramming Operating System
Multiprogramming is an extension to batch processing where the CPU is always kept busy. Each
process needs two types of system time: CPU time and IO time.
In a multiprogramming environment, when a process does its I/O, The CPU can start the
execution of other processes. Therefore, multiprogramming improves the efficiency of the
system.

Advantages of Multiprogramming OS
o Throughout the system, it increased as the CPU always had one program to execute.
o Response time can also be reduced.
Disadvantages of Multiprogramming OS
o Multiprogramming systems provide an environment in which various systems resources
are used efficiently, but they do not provide any user interaction with the computer
system.
Multiprocessing Operating System
In Multiprocessing, Parallel computing is achieved. There are more than one processors present
in the system which can execute more than one process at the same time. This will increase the
throughput of the system.
In Multiprocessing, Parallel computing is achieved. More than one processor present in the
system can execute more than one process simultaneously, which will increase the throughput of
the system.
Advantages of Multiprocessing operating system:
o Increased reliability: Due to the multiprocessing system, processing tasks can be
distributed among several processors. This increases reliability as if one processor fails,
the task can be given to another processor for completion.
o Increased throughout: As several processors increase, more work can be done in less.
Disadvantages of Multiprocessing operating System
o Multiprocessing operating system is more complex and sophisticated as it takes care of
multiple CPUs simultaneously.
Multitasking Operating System
The multitasking operating system is a logical extension of a multiprogramming system that
enables multiple programs simultaneously. It allows a user to perform more than one computer
task at the same time.
Advantages of Multitasking operating system
o This operating system is more suited to supporting multiple users simultaneously.
o The multitasking operating systems have well-defined memory management.
Disadvantages of Multitasking operating system
o The multiple processors are busier at the same time to complete any task in a
multitasking environment, so the CPU generates more heat.
Network Operating System

An Operating system, which includes software and associated protocols to communicate with
other computers via a network conveniently and cost-effectively, is called Network Operating
System.
Advantages of Network Operating System
o In this type of operating system, network traffic reduces due to the division between
clients and the server.
o This type of system is less expensive to set up and maintain.
Disadvantages of Network Operating System
o In this type of operating system, the failure of any node in a system affects the whole
system.
o Security and performance are important issues. So trained network administrators are
required for network administration.
Real Time Operating System
In Real-Time Systems, each job carries a certain deadline within which the job is supposed to be
completed, otherwise, the huge loss will be there, or even if the result is produced, it will be
completely useless.
The Application of a Real-Time system exists in the case of military applications, if you want to
drop a missile, then the missile is supposed to be dropped with a certain precision.
Advantages of Real-time operating system:
o Easy to layout, develop and execute real-time applications under the real-time operating
system.
o In a Real-time operating system, the maximum utilization of devices and systems.
Disadvantages of Real-time operating system:
o Real-time operating systems are very costly to develop.
o Real-time operating systems are very complex and can consume critical CPU cycles.
Time-Sharing Operating System
In the Time Sharing operating system, computer resources are allocated in a time-dependent
fashion to several programs simultaneously. Thus it helps to provide a large number of user's
direct access to the main computer. It is a logical extension of multiprogramming. In time-sharing,
the CPU is switched among multiple programs given by different users on a scheduled basis.

A time-sharing operating system allows many users to be served simultaneously, so


sophisticated CPU scheduling schemes and Input/output management are required.
Time-sharing operating systems are very difficult and expensive to build.
Advantages of Time Sharing Operating System
o The time-sharing operating system provides effective utilization and sharing of resources.
o This system reduces CPU idle and response time.
Disadvantages of Time Sharing Operating System
o Data transmission rates are very high in comparison to other methods.
o Security and integrity of user programs loaded in memory and data need to be
maintained as many users access the system at the same time.
Distributed Operating System
The Distributed Operating system is not installed on a single machine, it is divided into parts, and
these parts are loaded on different machines. A part of the distributed Operating system is
installed on each machine to make their communication possible. Distributed Operating systems
are much more complex, large, and sophisticated than Network operating systems because they
also have to take care of varying networking protocols.
Advantages of Distributed Operating System
o The distributed operating system provides sharing of resources.
o This type of system is fault-tolerant.
Disadvantages of Distributed Operating System
o Protocol overhead can dominate computation cost.

2(d): #include<stdio.h>
int main(){
char ch;
printf("enter a character:");
scanf("%c",&ch);
if(ch >= 65 && ch <= 90)
printf("Upper Case Letter");
else if(ch >= 97 && ch <= 122)
printf("Lower Case letter");
else if(ch >= 48 && ch <= 57)
printf("Number");
else
printf("Symbol");
return 0;
}

3(a): C Relational Operators


A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0
Operator Meaning of Operator Example

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
C Bitwise Operators
During computation, mathematical operations like: addition, subtraction, multiplication, division,
etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND


Operators Meaning of operators

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

3(b): #include <stdio.h>


int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}
3(c): An array is a variable that can store multiple values. For example, if you
want to store 100 integers, you can create an array for it.
int data[100];

How to declare an array?


dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning,
it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it
is declared.

Access Array Elements


You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], the second
element is mark[1] and so on.
#include<stdio.h>

int main()
{
int arr[100], size, i, sum = 0;

printf("Enter array size\n");


scanf("%d",&size);

printf("Enter array elements\n");


for(i = 0; i < size; i++)
scanf("%d",&arr[i]);

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


sum = sum + arr[i]; // same as sum += arr[i];

printf("Sum of the array = %d\n",sum);

return 0;
}
Solution of PUT(BCS-201) EVEN SEM
1(a): Difference between Compiler and Interpreter
The following table highlights all the significant differences between a Compiler and an Interpreter −

Parameter Compiler Interpreter

Program Compilers scan the entire program in The program is interpreted/translated one line at a
scanning one go. time.

Error detection As and when scanning is performed, One line of code is scanned, and errors
all the errors are shown in the end encountered are shown.
together, not line by line.

Object code Compilers convert the source code to Interpreters do not convert the source code into
object code. object code.

Execution time The execution time of compiler is less, It is not preferred due to its slow speed. Usually,
hence it is preferred. interpreter is slow, and hence takes more time to
execute the object code.

Need of source Compiler doesn’t require the source It requires the source code for execution later.
code code for execution later.

Programming Programming languages that use Programming languages that uses interpreter
languages compilers include C, C++, C#, etc.. include Python, Ruby, Perl, MATLAB, etc.

Types of errors Compiler can check syntactic and Interpreter checks the syntactic errors only.
detected semantic errors in the program
simultaneously.

Size Compiler are larger in size. Interpreters are smaller in size.

Flexibility Compilers are not flexible. Interpreters are relatively flexible.


Efficiency Compilers are more efficient. Interpreters are less efficient.

1(b): C Program to find area and circumference of circle

#include<stdio.h>

int main() {

int rad;
float PI = 3.14, area, ci;
printf("\nEnter radius of circle: ");
scanf("%d", &rad);
area = PI * rad * rad;
printf("\nArea of circle : %f ", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);
return (0);
}
1(c): ANSWER

1. break statement — The break statement takes the flow of control out of the switch statement.
Without the break statement, execution would simply continue to the next case.
2. default statement — When none of the case values are equal to the expression of switch statement
then default case is executed. Default case is optional. If default case is absent and no case values
match then none of the statements from switch are executed.
1(d): The syntax of else if ladder can be represented as:
if( condition-1)
statement-1;

else if (condition-2)
statement-2;

else if (condition-3)
statement-3;

else if (condition-4)
statement-4;

else if (condition-n)
statement-n;

else
default statement;
The syntax of switch case can be represented as:
switch(expression)
{
case constant-1
block-1;
break;

case constant-2
block-2;
break;

case constant-3
block-3;
break;

case constant-n
block-n;
break;

default:
default_block;
}

statement-x;
1(e): Loop

In programming, a loop is a control structure that allows us to execute instructions repeatedly. A Loop tells the
computer to repeat a particular set of instructions continually until a specific condition meets. Several loops are
available in programming languages, but the most common ones are:
 for loop: This Loop iterates over a fixed set of values or a range of values.

 while loop: This Loop repeats instructions if a specific condition is met.

 do-while loop: This Loop is similar to the while loop, but the instructions are executed at least once
before the condition is checked.

Based on the flow of loops in the code, they are generally classified into Entry Controlled loops and Exit
Controlled loops. For more information on Loops, visit this blog.
Entry Control Loop
An entry-controlled loop is a type of Loop in computer programming that tests the loop condition at the Loop's
beginning before executing the Loop's body.

1. As the program flow reaches an entry-controlled loop, the loop condition is tested before the first
iteration of the Loop.

2. If the condition meets, then the loop body will be executed. If it does not, the loop body will be
skipped entirely, and the program will continue execution from the first statement following the Loop.

3. After running the loop for required iterations (when the condition is not met), the program exits the
loop.

Some popular entry-controlled loops are for Loop, while Loop, etc.
Exit Control Loop
An exit-controlled loop is a type of Loop in computer programming that tests the loop condition at the end of
the Loop after executing the body of the Loop at least once.

1. As the program flow reaches an exit-controlled loop, the loop body is executed first, and then the loop
condition is tested.
2. If the condition is met, the Loop will continue to run, and the body's code will perform again. If it does
not, the Loop will exit, and the program will continue execution from the first statement following the
Loop.

3. After running the loop for required iterations (when the condition is not met), the program exits the
loop.

Do-while loop is primarily used in the exit-controlled Loop.


1(f): Difference Between Structure and Union in C
Parameter Structure Union

Keyword A user can deploy the keyword struct to define a A user can deploy the keyword union to define a
Structure. Union.

Internal The implementation of Structure in C occurs In the case of a Union, the memory allocation occurs
Implementation internally- because it contains separate memory for only one member with the largest size among all
locations allotted to every input member. the input variables. It shares the same location
among all these members/objects.

Accessing A user can access individual members at a given A user can access only one member at a given time.
Members time.

Syntax The Syntax of declaring a Structure in C is: The Syntax of declaring a Union in C is:
struct [structure name] union [union name]
{ {
type element_1; type element_1;
type element_2; type element_2;
. .
. .
} variable_1, variable_2, …; } variable_1, variable_2, …;

Size A Structure does not have a shared location for A Union does not have a separate location for every
all of its members. It makes the size of a member in it. It makes its size equal to the size of
Structure to be greater than or equal to the sum the largest member among all the data members.
of the size of its data members.

Value Altering Altering the values of a single member does not When you alter the values of a single member, it
affect the other members of a Structure. affects the values of other members.

Storage of Value In the case of a Structure, there is a specific In the case of a Union, there is an allocation of only
memory location for every input data member. one shared memory for all the input data members.
Thus, it can store multiple values of the various Thus, it stores one value at a time for all of its
members. members.

Initialization In the case of a Structure, a user can initialize In the case of a Union, a user can only initiate the
multiple members at the same time. first member at a time.

1(g): #include <stdio.h>

// Macro definitions
#define IS_UPPER(x) (x >= 'A' && x <= 'Z')
#define IS_LOWER(x) (x >= 'a' && x <= 'z')
int main()
{
char ch;

// Input a character from user


printf("Enter any character: ");
ch = getchar();

if (IS_UPPER(ch))
printf("'%c' is uppercase\n", ch);
else if (IS_LOWER(ch))
printf("'%c' is lowercase\n", ch);
else
printf("Entered character is not alphabet");

return 0;
}
2(a):
1

Block Diagram of Digital computer


A digital computer is considered to be a calculating device that can perform arithmetic operations at enormous
speed. It is defined as a device that operates upon information/data. To be able to process data the computer
is made of various functional units to perform its specified task.

Input Unit:
Computers need to receive data and instruction in order to solve any problem. Therefore, we need to input the
data and instructions into the computers. The input unit consists of one or more input devices. Keyboard is the
one of the most commonly used input device. Other commonly used input devices are the Mouse, Scanner,
Microphone etc. All the input devices perform the following functions.
• Accept the data and instructions from the outside world.
• Convert it to a form that the computer can understand.
• Supply the converted data to the computer system for further processing.

Storage Unit:
The storage unit of the computer holds data and instructions that are entered through the input unit, before
they are processed. It preserves the intermediate and final results before these are sent to the output devices.
It also saves the data for the later use. The various storage devices of a computer system are divided into two
categories.
a) Primary Storage: Stores and provides very fast. This memory is generally used to hold the program being
currently executed in the computer, the data being received from the
2

input unit, the intermediate and final results of the program. The primary memory is temporary in nature. The
data is lost, when the computer is switched off. In order to store the data permanently, the data has to be
transferred to the secondary memory. The cost of the primary storage is more compared to the secondary
storage. Therefore, most computers have limited primary storage capacity.
b) Secondary Storage: Secondary storage is used like an archive. It stores several programs, documents, data
bases etc. The programs that you run on the computer are first transferred to the primary memory before it is
actually run. Whenever the results are saved, again they get stored in the secondary memory. The secondary
memory is slower and cheaper than the primary memory. Some of the commonly used secondary memory
devices are Hard disk, CD, etc.,

Memory Size:
All digital computers use the binary system, i.e. 0’s and 1’s. Each character or a number is represented by an 8-
bit code.
The set of 8 bits is called a byte. A character occupies 1-byte space. A numeric occupies 2-byte space. Byte is
the space occupied in the memory.
The size of the primary storage is specified in KB (Kilobytes) or MB (Megabyte). One KB is equal to 1024 bytes
and one MB is equal to 1000KB. The size of the primary storage in a typical PC usually starts at 16MB. PCs
having 32 MB, 48MB, 128 MB, 256MB memory are quite common.
Output Unit:
The output unit of a computer provides the information and results of a computation to outside world.
Printers, Visual Display Unit (VDU) are the commonly used output devices. Other commonly used output
devices are Speaker, Headphone, Projector etc.
Arithmetic Logical Unit:
All calculations are performed in the Arithmetic Logic Unit (ALU) of the computer. It also does comparison and
takes decision. The ALU can perform basic operations such as addition, subtraction, multiplication, division, etc
and does logic operations viz, >, <, =, ‘etc. Whenever calculations are required, the control unit transfers the
data from storage unit to ALU once the computations are done, the results are transferred to the storage unit
by the control unit and then it is send to the output unit for displaying results.
Control Unit:
It controls all other units in the computer. The control unit instructs the input unit, where to store the data
after receiving it from the user. It controls the flow of data and instructions from the storage unit to ALU. It also
controls the flow of results from the ALU to the storage unit. The control unit is generally referred as the
central nervous system of the computer that control and synchronizes its working.
Central Processing Unit:
The Control Unit (CU) and Arithmetic Logic Unit (ALU) of the computer are together known as the Central
Processing Unit (CPU). The CPU is like brain performs the following functions:
• It performs all calculations.
• It takes all decisions.
•It controls all units of the computer.
2(c): Difference Between Call by Value and Call by Reference

Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally
differentiated by the type of values passed to them as parameters.
The parameters passed to the function are called actual parameters whereas the parameters received by the
function are called formal parameters.
Call By Value
In call by value method of parameter passing, the values of actual parameters are copied to the function’s
formal parameters.
 There are two copies of parameters stored in different memory locations.
 One is the original copy and the other is the function copy.
 Any changes made inside functions are not reflected in the actual parameters of the caller.
Example of Call by Value

// C program to illustrate call by value


#include <stdio.h>

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b);

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Swap functions that swaps


// two values
void swapx(int x, int y)
{
int t;

t = x;
x = y;
y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);


}

Call by Reference
In call by reference method of parameter passing, the address of the actual parameters is passed to the
function as the formal parameters.
 Both the actual and formal parameters refer to the same locations.
 Any changes made inside the function are actually reflected in the actual parameters of the caller.
Example of Call by Reference
The following C program is an example of call by reference method.
 C
 C++

// C program to illustrate Call by Reference


#include <stdio.h>
// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b);

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y)
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}

2(d): #include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
3(b): A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program −
 auto
 register
 static
 extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used within
functions, i.e., local variables.
The register Storage Class
The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT
be stored in a register depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making
local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to
be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be
shared by all the objects of its class.
Live Demo
#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

main() {

while(count--) {
func();
}

return 0;
}

/* function definition */
void func( void ) {

static int i = 5; /* local static variable */


i++;

printf("i is %d and count is %d\n", i, count);


}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files.
When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files,
then extern will be used in another file to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in another file.
4(b): #include<stdio.h>
#include<conio.h>
int main()
{
int a,b;
int op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return 0;
}
5(a): Flowchart to check if a given number is Palindrome or not

#include <stdio.h>

int main() {
int n, m, revnum = 0, r;
printf("Enter the number = ");
scanf("%d", & n);

m = n;

//find the reverse


while (n != 0) {
r = n % 10;
revnum = revnum * 10 + r;
n = n / 10;
}

if (m == revnum)
printf("%d is a palindrome!", m);
else
printf("%d is not a palindrome!", m);

return 0;
}

6(a): #include <stdio.h>

void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}
7(a): The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In
simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-
processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for
readability, a preprocessor directive should begin in the first column. The following section lists down all the
important preprocessor directives −#define-Substitutes a preprocessor macro.
#include-Inserts a particular header from another file.
#undef-Undefines a preprocessor macro.
#ifdef-Returns true if this macro is defined.
#ifndef-Returns true if this macro is not defined.
#if-Tests if a compile time condition is true.
#else-The alternative for #if.
#elif
#else and #if in one statement.
#endif-Ends preprocessor conditional.
#error-Prints error message on stderr.
#pragma-Issues special commands to the compiler, using a standardized method.

Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to
increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file.
The next line tells CPP to get myheader.h from the local directory and add the content to the current source
file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
#endif
Predefined Macros-ANSI C defines a number of macros. Although each one is available for use in programming,
the predefined macros should not be directly modified.

__DATE__
The current date as a character literal in "MMM DD YYYY" format.
__TIME__
The current time as a character literal in "HH:MM:SS" format.
__FILE__
This contains the current filename as a string literal.
__LINE__
This contains the current line number as a decimal constant.
__STDC__
Defined as 1 when the compiler complies with the ANSI standard.

You might also like