Course File
Course File
Bareilly
Course File
Programming for Problem Solving
BCS-201
Submitted By:
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):
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.
1(c):
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.
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
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.
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;
}
== Equal to 5 == 3 is evaluated to 0
Operator Meaning of Operator Example
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.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
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];
int main()
{
int arr[100], size, i, sum = 0;
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 −
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.
#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.
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.
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.
// Macro definitions
#define IS_UPPER(x) (x >= 'A' && x <= 'Z')
#define IS_LOWER(x) (x >= 'a' && x <= 'z')
int main()
{
char ch;
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
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
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
return 0;
}
t = x;
x = y;
y = t;
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++
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
return 0;
}
t = *x;
*x = *y;
*y = t;
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]);
}
}
/* function declaration */
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
#include <stdio.h>
int main() {
int n, m, revnum = 0, r;
printf("Enter the number = ");
scanf("%d", & n);
m = n;
if (m == revnum)
printf("%d is a palindrome!", m);
else
printf("%d is not a palindrome!", m);
return 0;
}
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.