0% found this document useful (0 votes)
25 views54 pages

CCE PPS Lab Manual

CCE PPS lab manual

Uploaded by

RUPESH KUMAR
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)
25 views54 pages

CCE PPS Lab Manual

CCE PPS lab manual

Uploaded by

RUPESH KUMAR
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/ 54

PRACTICAL-1

Practical Name: To explain parts of computer system such as system unit, input devices, output devices
connected to the computer. To explore the outside view of system unit that includes the panels on front and
ports on the rear view.

Objectives: Demonstrate about outer view of computer.

A computer is an electronic device, which mainly performs the four functions as reading, processing,
displaying and storing on data. These functions of a computer system can be carried out by using the three
main units namely input unit, system unit and output unit. The block diagram of a computer system is as
follows:

Fig 1: Block Diagram of a Computer


Notations:
Data and Results flow
Control instructions to other units from control unitInstructions from memory unit to control unit

System or Central Processing Unit (CPU): is commonly known as “processor” that executes the instructions
of a computer program. It has Control Unit (CU) and Arithmetic & Logical Unit (ALU). These two units
perform the basic arithmetic, logical, and input/output operations.

a) Input unit: is used to enter data and information into a computer. The devices like keyboard, mouse
and scanner are commonly used input devices.
A keyboard is used to enter alphanumeric characters and symbols.
The mouse is used to pick or select a command from the monitor screen. A scanner is used to scan an image or
read a barcode and so on.

Page 1 of 54
b) Arithmetic and Logic Unit (ALU): is a digital circuit that perform arithmetic (Add, Sub,
Multiplication, Division) and logical (AND, OR, NOT) operations. It helps in fast computation of scientific
calculations on floating-point number.

c) Control unit (CU): is the circuitry that controls the flow of information through the processor and
coordinates the activities of the other units within the processor.

Functions of Control unit

 Accessing data & instructions from memory unit.


 Interpreting instructions
 Controlling input and output units
 Overall supervision of a Computer system

d) Memory Unit (MU): is the unit where all the input data and results are stored either temporarily or
permanently. The CPU memory is also called as memory register. The memory of a computer has two types:

Main Memory / Primary Memory units


Random Access Memory (RAM) Read Only Memory (ROM)
Secondary Memory / Auxiliary Memory

e) Output Unit: It is used to display or print results from a computer. Monitor, printer and plotters are
commonly used output devices.

Printer
f) Bus: A bus is a collection of wires that carries data/Instructions. It connects physical components
suchas cables, printed circuits, CPU, Memory, Peripherals etc., for sharing of Information and communication
with one another. The purpose of buses is to reduce the number of "pathways" needed for communication
between the components, by carrying out all communications over a single data channel.

Page 2 of 54
Types of Buses:

1. System Buses: The system buses are used to transfer the data and instructions between Main
memory(Random Access Memory) and CPU. These are classified into following three types.

Data Bus Address Bus Control Bus


It is used to transfer the data It is used to transfer the It is used to transfer the

between Processor, Memory addresses of data and control signals between CPU,

and I/O devices Instructions stored in memory. Memory and I/O devices.

Bidirectional in nature Unidirectional in nature Unidirectional or

Bidirectional in nature

Fig 2: Types of Buses

2. I/O Buses: The buses which are used to connect all I/O devices with CPU and Memory are called I/O
buses. These are classified into following three types.
Main Board or Mother Board: Mother Board is a set of Integrated Chips (ICs) which are designed to work
together. It controls the flow of data/instructions within our computer. It is the main board on which other hardware
components are connected to enable the computer system to work as an integrated unit. It consists of sockets, slots,
power connectors and bus.

Page 3 of 54
Chip sets: Chip set is the set of integrated chips that are designed to work together. These set of chips controls the flow of
information on computer. The chips may be controllers for memory, cache, hard drive, key board and peripherals.

Related Short Questions:


What is CPU?
What do you understand by memory ?
Define system bus.
What do you understand by cache memory?
What is IC’s?
Define RAM.
Define ROM
What do you understand by Data Bus and Control Bus?

Page 4 of 54
PRACTICAL-2

Practical Name: To explore the inside view of the system unit that includes the motherboard, processor,
expansion slots, various add-on-cards, storage devices, power supply, fans.

Objectives: Demonstrate about internal view of computer system (ports, connectors).

Operating System and its types: An Operating System (OS) is system software that controls and supervCSEs the
hardware components of a computer system and it provides the services to computer users. Also called as
Resource Manager that manages the resources such as CPU, Memory, I/O devices, Job/Task/Process etc., a
computer cannot run without it. The major functions of OS includes: CPU Management, Memory Management,
File Management, Device Management, Process/Task/Job Management and Security Management.

The primary goal of an OS is to make the computer system convenient and efficient to use. An OS ensures that
the system resources (such as CPU, memory, I/O devices, etc) are utilized efficiently. For example, there may be
many programs residing in the main memory. Therefore, the system needs to determine which programs are
active and which need to wait for some I/O operation.
Some of the examples of Operating Systems:

Windows –XP is an O.S. is used for Personal Computers (PCs) Unix and XENIX are the OSs used for multi-
user computers. Windows 7, Windows 8, Macintosh OS, Fedora, and Android, etc.
Types of Operating Systems: The operating systems are classified into 7 types based on their capability and
usage.

Fig 3: Types of Operating System

Page 5 of 54
Batch Processing Tasking OS: The data is collected into a group called batch and provides only one batch (one
after another) of jobs as input to the computer system at a time. The jobs in a batch are processed on first come
first serve basis. In this type, the process takes place at specified time intervals
i.e. weekly or monthly without user interaction. E.g. Punch cards were using to store the data in batch processing
and in payroll preparation in a business batch processing was helpful.

Single user and single tasking OS: The OS that allows only one program to execute at a time is called single
user single tasking operating system. Using this operating system user can do only one task at a time. E.g. DOS
(Disk Operating System).

Single user and multi tasking OS: The OS that allows a single use to perform more than one task at a time is
called single user multi tasking operating system. While working with the Ms-Word user can perform other work
like print a document, listen music.E.g. Windows-XP, Windows Vista, Windows –7, etc.

Multi user and multitasking OS: The O.S. that allows two or more users to use a main computer system to do
more than one task is called multiuser and multitasking operating system.E.g. UNIX is a multiuser and
multitasking operating system.

Multiprocessing OS: The OS that allows multiple programs to be executed by multiple CPUs(Processors) is
called multiprocessing operating system. Super and main frame computers have more than one CPU and
multiprocessing operating system.

Real Time Operating System (RTOS): The OS that is used for real time applications and to carry out certain
calculations within the specified time constraint. This OS is used in applications such as mobile phones,
supporting systems in hospitals, nuclear power plants, oil refining, chemical processing, environmental applications and air-
traffic control systems, disaster management etc.,

Virtual machine OS: Allows several users of a computer system to operate as if each has the only terminal
attached to the computer.
Random Access Memory (RAM): RAM is basically main memory of the computer. RAM is a semiconductor
memory made up of small memory chips that form a memory module. These modules are installed in the RAM
slots on the motherboard of computer. Every time you open a program, it gets loaded from the hard drive into the
RAM. This is because reading data from the RAM is much faster than reading data from the hard drive.

Fig 4: Random Access Memory

Page 6 of 54
Synchronous Dynamic Random Access Memory (SDRAM): It is an improvement to standard DRAM because
it retrieves data alternately between two sets of memory. This eliminates the delay caused when one bank of
memory addresses is shut down while another is prepared for reading. It is called "Synchronous" DRAM because
the memory is synchronized with the clock speed that the computer's CPU bus speed is optimized for. The faster
the bus speed, the faster the SDRAM can be. SDRAM speed is measured in Megahertz.
FLASH memory: Flash memory is a type of Electrically Erasable Programmable Read-Only Memory
(EEPROM). The name comes from how the memory is designed -- a section of memory cells can be erased in a
single action or in a "flash.” Flash memory cards used for digital cameras, cellular phones, networking hardware,
and PC cards.
Hard disks: Hard disk is prime unit of storage of the computer. Huge amount of data can be stored and accessed
in few millCSEconds. The hard disk consists of more number of disks arranged in the cylindrical order, one
above another on a spindle. The read/write heads are attached to single access mechanism so that they cannot
move independently. All read/write heads are moved together to position that heads on the required track. The
hard disks available today ranges from 200 GB to 2TB and so on. The present day hard disk ranges from 3600
rpm to more than 10000 rpm and so on.

Fig 5: Hard Disk Drive

Page 7 of 54
Advantages:
High storage capacity, high data accessing rate and permanent storage medium.
Disadvantages:
It is not portable.
Optical media: An optical storage media is kind of storage, which is coated with thin metal on which bits are
stored. The data can be stored in to optical storage media or read form the optical storage media.
The devices which perform read or write operation on optical storage media are called optical storage media. The
laser technology is used to read the data or write the data onOptical storage devices.
Examples: CD-ROM, DVD etc.
Compact Disc Read-Only-Memory (CD-ROM): It is a type of optical disc that uses laser technology to read
and write data on the disc. The information stored on CDROM becomes permanent and cannot be altered. This
means that the stored information can only be read for processing. A CD-ROM uses the round shaped optical
disk to store data, applications, games and audio files. It can store up to 700 MB of data. It has become integral
part of every organization due to its features like reliability, reasonable, storage capacity and easy to use of
carry. CD-Drive will be with motor to rotate the disks to perform read and write operations. A will consists of
the components like Disc drive, disk drive motor, laser pick up assembly tracking drive and tracking motor and
so on.

Fig 6: Compact Disk Drive


Compact Disk Recordable (CD-R): The CD-R allows you to create your own CD.CD-R drives have the ability
to create CDs but they can write data on the disk only once.CD-R technology also called as Write Once-Read
much (WORM) technology. Laser technology is used to write the data on the compact disk.CD-R drives come in
IDE, SCSI and USB models.

Page 8 of 54
Compact Disc Rewritable (CD-RW): CD-RW is an erasable optical disk which is used to write data multiple
times on a disk, CD-RW disks are good for data backup, data archiving or data distribution on CDs. The disk
normally holds 700MB of data. Technology to write data multiple times on a CD was known as the Phase change
Dual (PD) technology. The reflective properties of a CD-RW are different than regular CD-ROM disks.
Disk or Digital Versatile Disc (DVD-ROM): A DVD is a small optical disk having high density medium and
capable of storing a full-length movie on a single disk. The high density is achieved by using both sides of the
disk, special data-compression technology, and extremely small tracks to store the data.
Advantages: Storage capacity is more compared to CDs.
Flash Drives (Pen drives): USB flash drives are removable, rewritable, and physically much smaller drives
weighing even less than 30 g. A flash drive consists of a small printed circuit board carrying the circuit elements
and a USB connector, insulated electrically and protected inside a plastic, metal, or rubberized case which can be
carried in a pocket or on a key chain.

Fig 7: Pen Drive


Advantages of Flash Drives
 Data stored on flash drives is impervious to scratches and dust Mechanically very robust
 Easily portable
 Have higher data capacity than any other removable media. Compared to hard drives, flash
drivesuse little power
 Flash drives are small and light-weight devices
 Flash drives can be used without installing device drivers

Disadvantages
 Can sustain only a limited number of write and erase cycles before the drive fails. Most
flashdrives do not have a write-protect mechanism

Page 9 of 54
 Flash drives are very small devices that can easily be misplaced, left behind, or otherwise lost.
Thecost per unit of storage in a flash drive is higher than that of hard disks
Keyboard: A keyboard is the primary input device used in all computers. Keyboard has a group of switches
resembling the keys on an ordinary typewriter machine. Normally keyboard has around 101 keys. The keyboard
includes key that allows us to type letters, numbers and various special symbols such as *, /, [, % etc.

Fig 8: Keyboard
Mouse: The mouse is the key input device to be used in a Graphical User Interface (GUI). The users can use
mouse to handle the cursor pointer easily on the screen to perform various functions like opening a program or
file. With mouse, the users no longer need to memorize commands, which was earlier a necessity when working
with text-based command line environment such as MS-DOS.

Fig 9: Mouse
Advantages:
 Easy to use
 Cheap

Page 10 of 54
 Can be used to quickly place the cursor anywhere on the screen Helps to quickly and easily
draw figures
 Point and click capabilities makes it unnecessary to remember certain commands
Disadvantages:
 Needs extra desk space to be placed and moved easily
 The ball in the mechanical mouse needs to be cleaned very often for smooth movements

Printers: The printer is an output device, which is used to get hard copy of the text displayed on the screen. The
printer is an external optional device that is connected to the computer system using cables. The printer driver
software is required to make the printer working. The performance of a printer is measured in terms of Dots Per
Inch (DPI) and Pages Per Minute (PPM) produced by the printer.

Plotters: A plotter is similar to printer that produces hard-copy output with high-quality color graphics. Plotters
are generally more expensive than printers, ranging from about $1000 to $75000.

Related Short Questions:


Define Printer?
Define Input Devices?
Define CD-R and CD-RE.
Explain SDRAM.
Define USB Flash Drives with their advantages and disadvantages.
Define Plotter.
Explain DVD ROM
Define Multitasking.

Page 11 of 54
PRACTICAL-3

Practical Name: Familiarization with programming .environment

Objectives: Define and implement use of flowchart and algorithms for solving problems and familiarization
with C editor.

The process of working through details of a problem to reach a solution. There are three approaches to problem
solving:
1. Algorithm
2. Flowchart
3. Pseudo Code

Algorithm: The algorithm is a step-by-step procedure to be followed in solving a problem. It provides a scheme
to solve a particular problem in finite number of unambiguous steps. It helps in implementing the solution of a
problem using any of the programming languages. In order to qualify as an algorithm, a sequence of instructions
must possess the following characteristics:

Definiteness: Instructions must be precCSE and unambiguous i.e. each and every instruction should be clear and
should have only one meaning.

Finiteness: Not even a single instruction must be repeated infinitely. i.e., each instruction should be performed in
finite time.

Termination: After the algorithm gets executed, the user should get the desired result

Key features of an algorithm:


Any algorithm has a finite number of steps and some steps may involve decision making, repetition.
Broadly speaking, an algorithm exhibits three key features that can be given as:

Sequence: Sequence means that each step of the algorithm is executed in the specified order.

Decision: Decision statements are used when the outcome of the process depends on some condition.

Repetition: Repetition which involves executing one or more steps for a number of times can be implemented
using constructs like the while, do-while and for loops. These loops executed one or more steps until some
condition is true.

Page 12 of 54
Flowcharts: A flowchart is a graphical or symbolic representation of an algorithm. They are basically used to
design and develop complex programs to help the users to visualize the logic of the program so that they can gain
a better understanding of the program and find flaws, bottlenecks, and other less- obvious features within it.
Basically, a flowchart depicts the “flow” of a program. The following table shows the symbols used in flowchart
along with its descriptions

Advantages of Flowcharts:
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be performed to
solve a problem. They are usually drawn in the early stages of formulating computer solutions to facilitate
communication between programmers and business people.
Flowcharts help programmers to understand the logic of complicated and lengthy problems.
They help to analyze the problem in a more effective manner Flowchart can be used to debug programs that have
error(s).
E.g.: To compute the Area of Rectangle

SYMBOL SYMBOL NAME

TERMINAL

PROCESSE

DECISION

INPUT/OUTPUT

CONNECTOR

FLOW LINE

Fig 10: Flowchart symbols

Page 13 of 54
Limitations of using Flowcharts:

 Drawing flowcharts is a laborious and a time consuming activity.


 Flowchart of a complex program becomes, complex and clumsy.
 At times, a little bit of alteration in the solution may require complete re- drawing of the
flowchart Essentials of what is done may get lost in the technical details of how it is done.
 There are no well-defined standards that limits the details that must be incorporated in a flowchart

Pseudo code:
 It is a form of structured English that describes algorithms. It facilitates the designers to focus on
the logic of the algorithm without getting bogged down by the details of language syntax.
 Pseudocode is a compact and informal high-level description of an algorithm that uses the
structuralconventions of a programming language.
 It is meant for human reading rather than machine reading, so it omits the details that are
not essential for humans.
 Such details include keywords, variable declarations, system-specific code and subroutines.
Thereare no standards defined for writing a pseudocode because it is not an executable program
 Flowcharts can be considered as a graphical alternative to pseudocode, but are more spacious
onpaper.

E.g.: To compute the area of Rectangle

Begin
Input length, breadthArea=length*breadthPrint Area
End

Page 14 of 54
Laboratory Program-1
Familiarization with computer hardware and programming environment, concept of naming the program
files, storing, compilation, execution and debugging. Taking any simple C- code.

Working with TurboC

Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.

Step 2: File > New (as shown in the below picture) and then write your C program

Page 15 of 54
Step 3: Write a Program

Step 4: Save the program using F2 (OR file > Save), remember the extension should be “.c”. In thebelow
screenshot I have given the name as summ.c.

Page 16 of 54
Step 5: Compile the program using Alt + F9 OR Compile > Compile (as shown in the belowscreenshot).

Step 6: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.

Step 7: Alt+F5 to view the output of the program at the output screen.

Page 17 of 54
GCC Compilation Process

Related Short Questions:


What is an algorithm?
Define flowchart.
In C programming binary operator needs operand.
Define PSEUDO Code
Why we use main () function?
Write full form of clrscr().
Define preprocessor directives

Page 18 of 54
PRACTICAL-4
Practical Name: Simple computational problems using arithmetic expression

Objectives: Implementation of use of variables, constants and operators for solving arithmeticproblems
Laboratory Program-2:
// Illustrate the use of various arithmetic operators

#include <stdio.h>int main (void)


{
int a = 100;int b = 2; int c = 25; int d = 4; int result;
result = a - b; // subtraction printf ("a - b = %i\n", result); result = b * c;
// multiplicationprintf ("b * c = %i\n", result); result = a / c; //
division
printf ("a / c = %i\n", result); result = a + b * c; // precedence printf ("a + b * c = %i\n", result);
printf ("a * b + c * d = %i\n", a * b + c * d);return 0;
}
Program Implementation:

Page 19 of 54
Output of the Program:

Related Short Questions:


Q.1.What are the various arithmetic operators?Q.2.Define relational operators
Explain logical operators.
Define variables and constants.
What are the various opearators used in C programming?

Page 20 of 54
PRACTICAL-5
Practical Name: Problems involving if-then-else structures

Objectives: Identify and implementation of use of various control statements

Laboratory Program-3:

Lab 3: Problems involving if-then-else structures


// Program to display a number if user enters negative number

#include <stdio.h> int main()


{
int number;

printf("Enter an integer: ");scanf("%d", &number);


// Test expression is true if number is less than 0if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");return 0;
}

// Program to check whether an integer entered by the user is odd or even

#include <stdio.h> int main()


{
int number;
printf("Enter an integer: ");scanf("%d",&number);
// True if remainder is 0 if( number%2 == 0 )
printf("%d is an even integer.",number);else
printf("%d is an odd integer.",number);return 0;
}

Page 21 of 54
Program Implementation:

Output of Program

// Program to relate two integers using =, > or <

#include <stdio.h> int main()


{
int number1, number2; printf("Enter two integers: ");

Page 22 of 54
scanf("%d %d", &number1, &number2);

//checks if two integers are equal. if(number1 == number2)


{
printf("Result: %d = %d",number1,number2);

}
//checks if number1 is greater than number2. else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
// if both test expression is falseelse
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}

// Program to find largest of three numbers

#include <stdio.h> int main()


{
double n1, n2, n3;
printf("Enter three numbers: "); scanf("%lf %lf %lf", &n1, &n2, &n3);if (n1>=n2)
{
if(n1>=n3)
printf("%.2lf is the largest number.", n1);else
printf("%.2lf is the largest number.", n3);
}
else
{
if(n2>=n3)
printf("%.2lf is the largest number.", n2);else

Page 23 of 54
printf("%.2lf is the largest number.",n3);
}
return 0;
}

Related Short Questions:

Define if else statement?

Differentiate between If else and switch statement. Q.3.Write a program to find largest of three numbers

Q.4.Write a program to relate two integers usin =, > or <

Write a program to check whether an integer entered by the user is odd or even

Write a program to display a number if user enters negative number.

Page 24 of 54
PRACTICAL-6
Practical Name: Iterative problems e.g. sum of series

Objectives: Apply loops and control statements for solving

Laboratory Program-4

// Program to print n natural numbers

#include <stdio.h> int main () {

/* local variable definition */int a = 10;

/* while loop execution */while( a < 20 ) {


printf("value of a: %d\n", a);a++;
}

return 0;
}
Program Implemetation:

Page 25 of 54
Output of the Program

// Program to calculate the sum of first n natural numbers


// Positive integers 1,2,3...n are known as natural numbers#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");scanf("%d", &num);

// for loop terminates when n is less than count for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

return 0;
}

Example 1: Program to print half pyramid using *


*
**
***
****
*****

Page 26 of 54
Source Code

#include <stdio.h> int main()


{
int i, j, rows;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1; i<=rows; ++i)


{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Program Implementation:

Page 27 of 54
Output of the Program:

Example 2: Program to print half pyramid a using numbers


1
12
123
1234
12345
Source Code

#include <stdio.h> int main()


{
int i, j, rows;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1; i<=rows; ++i)


{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

Page 28 of 54
Example 3: Program to print half pyramid using alphabets
ABB
CCC
DDDDEEEEE

Source Code

#include <stdio.h> int main()


{
int i, j;
char input, alphabet = 'A';

printf("Enter the uppercase character you want to print in last row: ");scanf("%c",&input);

for(i=1; i <= (input-'A'+1); ++i)


{
for(j=1;j<=i;++j)
{
printf("%c", alphabet);
}
++alphabet;

printf("\n");
}
return 0;
}
Programs to print inverted half pyramid using * and numbersExample 4: Inverted half pyramid using *
*****
****
***
**
*
Source Code

#include <stdio.h> int main()


{

Page 29 of 54
int i, j, rows;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=rows; i>=1; --i)


{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}

return 0;
}

Example 5: Inverted half pyramid using numbers

12345
1234
123
12
1

Source Code #include <stdio.h> int main()


{
int i, j, rows;
printf("Enter number of rows: ");scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}

Page 30 of 54
Programs to display pyramid and inverted pyramid using * and digits

Example 6: Program to print full pyramid using *


*
***
*****
*******
*********

Source Code

#include <stdio.h> int main()


{
int i, space, rows, k=0;

printf("Enter number of rows: ");scanf("%d",&rows);

for(i=1; i<=rows; ++i, k=0)


{
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}

while(k != 2*i-1)
{
printf("* ");
++k;
}

printf("\n");
}

return 0;
}

Page 31 of 54
Program Implementation:

Output of the Program:

Page 32 of 54
Example 7: Program to print pyramid using numbers

1
232
34543
4567654
567898765

Source Code

#include <stdio.h> int main()


{
int i, space, rows, k=0, count = 0, count1 = 0;printf("Enter number of rows: "); scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(space=1; space <= rows-i; ++space)
{
printf(" ");
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
printf("%d ", i+k);
++count;
}
else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;printf("\n");
}
return 0;
}

Page 33 of 54
Related Short Questions:

Define recursion?

Write a program to print Pyramid using numbers.

Write a program to print full Pyramid using * Q.4.Write a program Inverted half Pyramid using numbers.

Page 34 of 54
PRACTICAL-7

Practical Name: 1 D Array manipulation

Objectives: Will learn declaration and implementation of arrays in C Programs

Laboratory Program-5:

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element mark[3] = 9;

// take input from the user and insert in third element scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element scanf("%d", &mark[i]);

// print first element of an arrayprintf("%d", mark[0]);

// print ith element of an arrayprintf("%d", mark[i-1]);

// Program to find the average of n (n < 10) numbers using arrays


#include <stdio.h> int main()
{
int marks[10], i, n, sum = 0, average;printf("Enter n: ");
scanf("%d", &n);for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);scanf("%d", &marks[i]);
sum += marks[i];
}

Page 35 of 54
average = sum/n; printf("Average = %d", average);return 0;
}

Program Implementation:

Output of the Program:

Page 36 of 54
//Source Code to Calculate Average Using Arrays
#include <stdio.h> int main()
{
int n, i;
float num[100], sum = 0.0, average; printf("Enter the numbers of elements: ");scanf("%d", &n);
while (n > 100 || n <= 0)
{
printf("Error! number should in range of (1 to 100).\n");printf("Enter the number again: ");
scanf("%d", &n);
}
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);return 0;
}

Related Short Questions:


Explain one dimensional array?
Write a program to calculate average using arrays.
Write a program to find the average of n (n<10) numbers using array. Q.4.Write a program to calculate average
using array.

Page 37 of 54
PRACTICAL-5
Practical Name: Matrix problems, String operation

Objectives: Will learn to identify, demonstrate and operate 2-D array, strings and various operators for it in
programs.

Laboratory Program-6

//Matrix problems, String operation


//Program for subtraction of two matrices#include <stdio.h>
#define N 4
// This function subtracts B[][] from A[][], and stores
// the result in C[][]
void multiply(int A[][N], int B[][N], int C[][N])
{ int i, j;
for (i = 0; i < N; i++) for (j = 0; j < N; j++)
C[i][j] = A[i][j] - B[i][j]; }
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int C[N][N]; // To store result int i, j;
multiply(A, B, C); printf("Result matrix is \n");for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++) printf("%d ", C[i][j]);
printf("\n");
}

return 0; }

Page 38 of 54
//Program for addition of two matrices
#include <stdio.h>#define N 4
// This function adds A[][] and B[][], and stores
// the result in C[][]
void add(int A[][N], int B[][N], int C[][N])
{
int i, j;
for (i = 0; i < N; i++) for (j = 0; j < N; j++)
C[i][j] = A[i][j] + B[i][j];
}
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int C[N][N]; // To store result int i, j;
add(A, B, C);
printf("Result matrix is \n");for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++) printf("%d ", C[i][j]);
printf("\n");
}
return 0;
}

// Find the Frequency of Characters


#include <stdio.h> int main()
{
char str[1000], ch; int i, frequency = 0;

Page 39 of 54
printf("Enter a string: ");gets(str);
printf("Enter a character to find the frequency: ");scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
printf("Frequency of %c = %d", ch, frequency);return 0;
}

//Example: Calculate Length of String without Using strlen() Function


#include <stdio.h> int main()
{
char s[1000];int i;
printf("Enter a string: ");scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i); printf("Length of string: %d", i);return 0;
}

Related Short Questions:

Write a program to calculate length of string without using strlen() function?

Write a program to find the Frequency of the Characters.

Write a program for subtraction of two matrices. Q.4.Write a program for addition of two matrices. Q.5.Write a

program to find the Frequency of Characters.

Page 40 of 54
PRACTICAL-5
Practical Name: Simple functions

Objectives: Demonstrate declaration, definition and calling and different methods to use functions.

Laboratory Program-7:

#include<stdio.h>
// function prototype, also called function declarationfloat square ( float x );
// main function, program starts from here int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p = x * x ; return ( p ) ;
}

//EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):


#include<stdio.h>
// function prototype, also called function declarationvoid swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);swap(m, n);
}
void swap(int a, int b)
{

Page 41 of 54
int tmp;tmp = a;a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}

//EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):


#include<stdio.h>
// function prototype, also called function declarationvoid swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp; tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

Related Short Questions:

What is the difference between call by value and call by reference?

Write a program for C function using call by value.

What do you understand by functions?Q.4.Define function prototyping.

Q.5.Write a program for calling swapo function by reference.

Page 42 of 54
PRACTICAL-10

Practical Name: Programming for solving Numerical methods problems

Objectives: Implementation of logics using various C concepts for solving Numerical Methods.

Laboratory Program-8, 9:

//Programming for solving Numerical methods problems


#include<stdio.h> #include<conio.h>#include<math.h>void main()
{
float a,b,c;
float root1,root2;
float determinant,real,imaginary;clrscr();
printf("Enter the Co-efficient of Quadratic Equation\n");scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;if(a==0 && b==0)
{
printf("INVALID INPUTS\n");getch();
}
else if(a==0)
{
printf("LINEAR EQUATION\n");
root1=-c/b; printf("ROOT=%f\n",root1);
}
else if(determinant==0)
{
printf("ROOTS ARE REAL AND EQUAL\n");
root1=-b/(2*a);root2=-b/(2*a);
printf("Root1=%f\n Root2=%f",root1,root2);
}
else if(determinant>0)

Page 43 of 54
{
printf("ROOTS ARE REAL AND DISTINCT\n");
root1=(-b+(sqrt(fabs(determinant))))/(2*a); root2=(-b-(sqrt(fabs(determinant))))/(2*a); printf("ROOT1=%f\n
ROOT2=%f",root1,root2);
}
else
{
printf("ROOTS ARE IMAGINARY\n");
real=-b/(2*a); imaginary=sqrt(fabs(determinant))/(2*a); printf("ROOT1=%f+i%f\n",real,imaginary);
printf("ROOT2=%f-i%f\n",real,imaginary);getch();
}

Program Implementation:

Page 44 of 54
Output of the Program:

Related Short Questions:

Q. 1. Write a program to define Numerical methods problems?

What type of inputs are accepted by mathematical functions.

What will be the output of the following c code?#include<stdio.h>


#include<stdio.h>int main()
{
int i=10;
printf(“%f\n”, log10(i));return 0;
}

Is function fabs defined math.h header file takes the argument of type integer?

Page 45 of 54
PRACTICAL-11
Practical Name: recursive Function.

Objectives: formulate recursive methods to solve problems in C program.

Laboratory Program-10:

//Recursive functions

//Calculates the factorial of a given number using a recursive function


#include <stdio.h>
unsigned long long int factorial(unsigned int i) { if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() { int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));return 0;
}
Program Implementation:

Page 46 of 54
//Calculates the fibbonacci series using a recursive function
#include <stdio.h> int fibonacci(int i) {
if(i == 0) {return 0;
}
if(i == 1) {return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() { int i;
for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i));
}
return 0;
}

Related Short Questions:

Q. 1. How to calculate the factorial of a given number using a recursive function?

Q. 2. How to calculate the fibbonacci series using a recursive function.

Q. 3. Which keyword used to transfer control from a function back to the calling function

Q. 4.Is a function cannot be defined inside another function.

Q. 5.In C all functions except main() can be called recursively?

Q. 6.Functions can be called either by value or reference.

Page 47 of 54
PRACTICAL-12

Practical Name: Pointers and Structures

Objectives: Learn to implement pointers for dynamic allocation in C and how to define and usestructures
in programs.
Laboratory Program-11:

//Pointers
#include <stdio.h> int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

//Structures #include <stdio.h>struct person


{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;personPtr = &person1;

printf("Enter age:"); scanf("%d", &personPtr->age);

printf("Enter weight:"); scanf("%f", &personPtr->weight);

Page 48 of 54
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age); printf("weight: %f", personPtr->weight);

return 0;
}

Program Implementation:

Output of the Program:

Page 49 of 54
Related Short Questions:

Q. 1. What do you understand by pointers?

Q. 2. Define structures.

What is the difference between a string copy (strcpy) and memory copy (memcpy) ?

How can I remove the trailing spaces from a string?

How can I remove the leading spaces from a string?

Q. 6. How to rep[resent a string.

Q. 7. What is a null character in strings?

Page 50 of 54
PRACTICAL-13
Practical Name: File operations.
Objectives: Learn implementation for opening, closing or editing files in C programming.
Laboratory Program-12:
//File operations: //Write to a text file
#include <stdio.h> #include <stdlib.h>

int main()
{
int num; FILE *fptr;
// use appropriate location if you are using MacOS or Linuxfptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");exit(1);
}
printf("Enter num: ");scanf("%d",&num);
fprintf(fptr,"%d",num); fclose(fptr);
return 0;
}
Program Implementation:

Page 51 of 54
//Read from a text file#include <stdio.h> main() {

FILE *fp;
char buff[255];

fp = fopen("/tmp/test.txt", "r");fscanf(fp, "%s", buff);


printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);printf("3: %s\n", buff ); fclose(fp);


}
Program Implementation:

Page 52 of 54
Related Short Questions:

What are the various file operators?

Why we use strlen () function?

Howe strlen () works?

What is the difference between printf () and put ()?Q.5.Define pointer variable?

Q.6.What is the use of the stremp () function?Q.7.What is the use of strcat () function?

Page 53 of 54
Chandigarh Engineering College Jhanjeri
Mohali-140307
Department of Applied Sciences

You might also like