Programming For Problem Solving Using C and C++
Programming For Problem Solving Using C and C++
Ans. A computer can process data, pictures, sound and graphics. They can solve highly
complicated problems quickly and accurately.
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, floppy disk drive, magnetic tape, 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:
Block Diagram of Computer
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.
1. Primary Storage:
2. Secondary Storage:
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 floppy disk drive, hard disk drive, and magnetic
tape drive.
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 it's working.
The control unit and 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.
A PC may have CPU-IC such as Intel 8088, 80286, 80386, 80486, Celeron, Pentium, Pentium
Pro, Pentium II, Pentium III, Pentium IV, Dual Core, and AMD etc.
Technical Characteristics
(a) Capacity, representing the global volume of information (in bits) that the memory can
store
(b) Access time, corresponding to the time interval between the read/write request and
the availability of the data
(c) Cycle time, representing the minimum time interval between two successive accesses
(d) Throughput, which defines the volume of information exchanged per unit of time,
expressed in bits per second
(e) Non-volatility, which characterizes the ability of a memory to store data when it is not
being supplied with electricity
The ideal memory has a large capacity with restricted access time and cycle time, a high
throughput and is non-volatile.
However, fast memories are also the most expensive. This is why memories that use
different technologies are used in a computer, interfaced with each other and organised
hierarchically.
The fastest memories are located in small numbers close to the processor. Auxiliary
memories, which are not as fast, are used to store information permanently.
Types of Memories
Random access memory, generally called RAM is the system's main memory, i.e. it is a
space that allows you to temporarily store data when a program is running.
Unlike data storage on an auxiliary memory such as a hard drive, RAM is volatile, meaning
that it only stores data as long as it supplied with electricity. Thus, each time the computer
is turned off, all the data in the memory are irremediably erased.
Read-Only Memory
Read-only memory, called ROM, is a type of memory that allows you to keep the
information contained on it even when the memory is no longer receiving electricity.
Basically, this type of memory only has read-only access. However, it is possible to save
information in some types of ROM memory.
Flash Memory
Flash memory is a compromise between RAM-type memories and ROM memories. Flash
memory possesses the non-volatility of ROM memories while providing both read and
writes access However, the access times of flash memories are longer than the access times
of RAM.
Main Features:
1) The computers of this generation used vacuum tubes.
2) These computers used machine language for giving instructions.
3) They used the concept of stored program.
4) These computers were 5000 times faster than the MARK-I.
5) The first generation computers were welcomed by Government and Universities.
Limitations:
1) These computers were very big in size. The ENIAC machine was 30 x 50 feet in size and
30 tons in weight. So, these machines required very large space for their workings.
2) Their power consumption was very high.
3) These computers had slow operating speed and small computing capacity.
4) These computers had a very small memory.
Main Features:
1) The computers of this generation replaced vacuum tubes with transistors.
2) Magnetic cores were invented for storage.
3) Different magnetic storage devices were developed in this generation.
4) Commercial applications were developed during this period. Eighty percent of these
computers were used in business and industries.
Main Features:
· The third generation computers replaced transistors with Integrated Circuits . These
Integrated Circuits are also known as chips.
· The size of main memory was increased and reached about 4 megabytes.
· Magnetic disk technology had been improved and drive having capacity upto 100
MBPS came into existence.
· The CPU becomes more powerful with the capacity of carrying out 1 million instructions
per second.
· This generation computers were relatively inexpensive and faster.
· The application area also increased in this generation. The computers were used in other
areas like education, small businesses survey, analysis along with their previous usage
areas.
Main Features:
i . The fourth generation computers replaced small scale integrated circuits and medium
scale integrated circuits with the microprocessors chip.
ii. Semiconductor memories replaced magnetic core memories.
iii. The hard-disks are available of the sizes upto 200 GB. The RAID technology
(Redundant Array of Inexpensive Disks) gives storage upto thousands of GB. iv. Computer
cost came down rapidly in this generation.
v. Application of computers is increased in various areas like visualization, parallel
computing, multimedia etc.
All C compilers support a variety of data base . This enables the programmer to
select the appropriate data type as per data need of application.
They are used to represent whole numbers which are having sequence of digits .
* Signed Integer:- This data type is used to represent both positive and negative integer
numbers.
* signed short int :- the data type is used to represent the values which are less than
signed integer.
Format specifier : %d
* signed long integer :- the data type is used to represent the longer values than integer.
Format specifier : % Id
* Unsigned datatypes:- This data type is used to represent unsigned integer values.
* Unsigned integer :-
Range : 0 to 65535
Format specifier : %u
unsigned short int :- the data type is used to represent the values of small range without
sign.
Format specifier : %u
* signed long integer :- It is used to represent the longer values than which are not having
any sign.
Range : 0 to 4294967295
Format specifier : %u
These data types are used to represent floating point values or real numbers.
Keyword : float.
Format specifier : %f
*double :- this is used to represent point values of more range than float data type.
Keyword : double.
Format specifier : %f
* long double :- the range of long double is more than the double.
Format specifier : % Lf
Format specifier : %c
* Unsigned Chartacter :- It is used to represent characters with unsigned numbers .
keyword : Unsigned char (or) char
Range : 0 to 255
Format specifier : %c
5Q. What is Operator ? List various types of Operators available in C ? Explain any three
Operators with example ?
Ans. An Operator is a symbol that tells the compiler to perform specific mathematical or
logical functions .
1)Arithmetic Operators
2)Relational Operators
3)Logical Operators
4)Assignment Operators
5)Conditional Operators
6)Bitwise Operators
7)Increment and decrement operator
8)Others Operators
Arithmetic Operators
C provides five arithmetic operators, they are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example
/*Program to demonstrate arithmetic operators*/
#include<stdio.h>
int main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d %d", &a, &b);
printf("Sum =%d",(a+b));
printf("Difference=%d",(a-b));
printf("Product=%d",(a*b));
printf("Division=%d",(a/b));
printf("Modulus=%d",(a%b));
return0;
}
Output:
Entertwonumbers:2510
Sum =35Difference=15Product=250Division=2Modulus=5
Relational Operators
C supports following 6 relational operators
Operator Meaning
Example
Example
In the monolithic program the sequences of instructions are executed in the same order
as they appear in the program. In practical applications, there are a number of situations
where one has to change the order of the execution of statements based on the
conditions. This involves decision making condition to see whether a particular
condition is satisfied or not
.The conditions can be placed in the program using decision – making
statements. C Language supports the control statements as listed below
i) If statements
ii) Switch statements
i)If statements
It has 3 forms
I. The simple if Statement
II. The if–else Statement
III. The nested if Statement
I. Simple if
Simple if has only one option. The set of statements are executed when
the logical condition is true, Otherwise the if statement is skipped.
syntax:
if(condition)
{statements;}
Example:
1. /* Program to find discount */
#include<stdio
.h> int main()
{
float p,d = 0,t;
printf("Enter the purchased
amount:"); scanf("%f",&p);
if(p>=5000)
{
d = p*(10.0/100);
}
t = p - d;
printf("Discount =
%.2f",d); printf("\nTotal
amount = %.2f",t); return
0;
}
Output
Enter the purchased
amount:6000 Discount =
600.00
Total amount = 5400.00
If...Else Statement
If else is two way decision making statement. It has two options.
One choice will be selected out of two options. It has two blocks. One block
is for if and other block is for else. If the condition is true, the if block
statements are executed, and if the condition is false, else block statements
are executed
syntax:
if(condition)
{
Statements A;
}
else
{
Statements B }
1./*Program to verify whether given character is vowel or not*/
#include<stdio.h>
int main()
{
char ch;
printf("Enter an alphabet(a-z):");
scanf("%c",& ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("Vowel");
else
printf("consonants");
}
Output
Enter an alphabet(a-z):e
Vowel
if(condition1)
{
if(condition2)
{
statements;
}
else if(condition3)
{
statements;
}
}
else
{
statements;
}
Switch case
Syntax:
switch(expression)
{
case constant_ value: statement;
break;
case constant_ value: statement;
break;
case constant _value: statement;
break;
default :statement;
}
Syntax:
switch(expression)
{
case constant_ value: statement;
break;
case constant_ value: statement;
break;
case constant _value: statement;
break;
default :statement;
}
8Q. What is loop? Differentiate between while and do..while loop ?Write a Simple
program to demonstrate the while Operation?
Ans. Loop:
Loop is used to execute the block of code several times according to the condition given in
the loop. It means it executes the same code multiple times so it saves code and also helps
to traverse the elements of an array.
There are 3 types of loop –
while loop
do – while loop
for loop
WHILE DO-WHILE
Condition is checked first then statement(s) is Statement(s) is executed at least once,
executed thereafter condition is checked.
It might occur statement(s) is executed zero At least once the statement(s) is executed.
times, If condition is false.
No semicolon at the end of while. Semicolon at the end of while.
while(condition) while(condition);
If there is a single statement, brackets are not Brackets are always required.
required
Variable in condition is initialized before the variable may be initialized before or within
execution of loop. the loop.
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition) do { statement(s); }
{ statement(s); } while(condition);
while Loop –
While loop execute the code until condition is false.
while(condition){
//code
}
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
while( i <=20 ) {
printf ("%d " , i );
i++;
}
getch();
}
Output
20
Ans.
while loop
do – while loop
for loop
1. while Loop –
While loop execute the code until condition is false.
while(condition){
//code
}
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
while( i <=20 ) {
printf ("%d " , i );
i++;
}
getch();
}
Output
20
2. do – while loop
It also executes the code until condition is false. In this at least once, code is executed
whether condition is true or false but this is not the case with while. While loop is executed
only when the condition is true.
Syntax
do{
//code
}while(condition);
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
do{
printf ("%d " , i );
i++;
}
while( i < =20 );
get ch();
}
Output
20
21
3. for Loop
It also executes the code until condition is false. In this three parameters are given that is
Initialization
Condition
Increment/Decrement
Syntax
for(initialization ;condition ;increment/decrement)
{
//code
}
It is used when number of iterations are known where while is used when number of
iterations are not true.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for( i = 20; i < 25; i++) {
printf ("%d " , i);
}
getch();
}
Output
20
21
22
23
24
10Q. what is Array? explain various typed of Array in C language ? with suitable example.
Ans. An array is defined as the collection of similar types of data items stored at
contiguous memory locations.
* Multi dimensional array (two dimensional array ,three dimensional array, four
dimensional array ...etc).
during compilation ,5 contiguous memory locations are reserved by the compiler for the
variable a and all these locations are initialized as shown in Fig.
a[0] a[1] a[2] a[3] a[4]
12 14 16 17 18
5000 5002 5004 5006 5008
If the size of integer is 2bytes,10bytes will be allocated for the variable a.
Option2initializationwithoutsize
If we omit the size of your array ,but specify an initial set of data ,the compiler
will automatically determine the size of your array. This way is referred as initialization
without size.
int a[]={75,79,82,70,68};
In this declaration, even though we have not specified exact number of elements to be
used in array a ,the array size will be set of the total number of initial values specified.
Here, the compiler creates an array of 5 elements.
Option 3 Partial Array Initialization
If the number of values to be initialized is less than the size of the array ,then the
elements are initialized in the order from 0th location. The remaining locations will be
initialized to zero automatically.
int a[5]={75,79,82}
a[0] a[1] a[2] a[3] a[4]
75 79 82 0 0
5000 5002 5004 5006 5008
Even though compiler allocates 5 memory locations ,using this declaration statement,
the compiler initializes first three locations with 75 ,70 and 82,the next set of memory
locations are automatically initialized to 0‟s by the compiler
Option4: initialize all elements to zero
If you do not know any data ahead of time ,but you want to initialize everything to 0, just
use 0 within{}.
For example: int a[5]={0};
This will initialize every element within the array to 0
a[0] a[1] a[2] a[3] a[4]
0 0 0 0 0
5000 5002 5004 5006 5008
The total number of elements in two dimensional array is product of no. of rows and no. of
columns.
Example: int a[3][2];stores3x2=6valuesconceptuallystoredinmatrixform.
/*Program to read elements of two-dimensional array and print them in matrix format*/
void main()
{
int a[3][2],i ,j;
printf("Enterelementsof3x2matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf("%d" ,&a[i][j]);
}
}
printf("Given Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
Output
Enterelementsof3x2matrix:
152637
Given elements
1 5
2 6
3 7