Itcp Lab Manual
Itcp Lab Manual
Itcp Lab Manual
Lab # 01 .......................................................................................................................................... 6
Basic Computer Hardware, Networking terminologies and Network Devices .............................. 6
1.1 Objective: .............................................................................................................................. 6
1.2 Scope: .................................................................................................................................... 6
1.3 Useful Concepts: ................................................................................................................... 7
1.4 Exercises for lab .................................................................................................................. 10
1.5 Home Work ......................................................................................................................... 10
Lab # 02 ........................................................................................................................................ 11
Microsoft Word Document ........................................................................................................... 11
2.1 Objective ............................................................................................................................. 11
2.2 Scope ................................................................................................................................... 11
2.3 Useful Concepts .................................................................................................................. 11
Create a Document ................................................................................................................ 11
Saving Documents ................................................................................................................ 14
Formatting Text .................................................................................................................... 15
Header Footer and Page Number .......................................................................................... 17
Pictures and Text Wrap ......................................................................................................... 20
Tables .................................................................................................................................... 24
2.4 Exercises for Lab ................................................................................................................ 29
2.5 Home Work ......................................................................................................................... 29
Lab # 02(continued) ...................................................................................................................... 31
Microsoft PowerPoint Document ................................................................................................. 31
2.1 Objective ............................................................................................................................. 31
2.2 Scope ................................................................................................................................... 31
2.3 Useful Concepts .................................................................................................................. 31
Introduction to PowerPoint Presentation .............................................................................. 31
Create a Presentation............................................................................................................. 31
Saving presentation ............................................................................................................... 32
Slides and Layout .................................................................................................................. 33
Lab # 01
1.1 Objective:
To computer hardware architecture
1.2 Scope:
This document includes information under the following main topics
2. Introduction to Networking
3. Types of Networks
6. Network Topologies
Introduction to Networking
A computer network consists of a collection of computers, printers and other equipment that is
connected together so that they can communicate with each other.
Broadly speaking, there are two types of network configuration, peer-to-peer networks and
client/server networks.
Types of Networks
Peer-to-peer networks are more commonly implemented where less than ten computers are involved
and where strict security is not necessary. All computers have the same status, hence the term
'peer', and they communicate with each other on an equal footing. Files, such as word processing or
spreadsheet documents, can be shared across the network and all the computers on the network
can share devices, such as printers or scanners, which are connected to any one computer.
Client/Server Networks:
Hub or Switch
A hub is a device used to connect a PC to the network. The function of a hub is to direct
information around the network, facilitating communication between all connected devices. However
in new installations switches
should be
Router
Server
The Internet
This is the largest computer network in the world! It is a constantly growing connection of
computers and networks around the world, and is used to communicate and share information in
many ways.
This is the organization or company that connects an individual computer or a computer network to
the Internet, therefore allowing for communication and collaboration with millions of other
computers and their users.
Firewall
An Internet protocol (IP) address is a four part number, written with decimal points (full stops)
separating each part. An example IP address is 192.168.0.200. An IP address is rather like a ‗phone
number‘ for a computer or networking equipment. Computers on the Internet that know each other‘s
IP addresses can communicate with each other.
MAC Address
The Media Access Control (MAC) address is also known as the physical address for any device (such
as a network interface card or a wireless network adapter) that connects a computer to a network.
Every network device has its own unique MAC address that (like a serial number) cannot be changed
and is useful for identifying that device when it is a part of a network.
TCP/IP
TCP/IP is short for Transmission Control Protocol/Internet Protocol. These protocols (or rules) de-
fine how devices (such as computers and routers) communicate with each other. TCP/IP determines
the best path for information (data) to travel from one device to another. TCP/IP will break up
data into small packets that are sent separately and then reassembled upon arrival.
DHCP
The Dynamic Host Configuration Protocol (DHCP) is a set of rules used by a DHCP server (a server
computer, a firewall, a modem or a router) to allocate IP addresses to computers on a local network
or the Internet. It also keeps track of assign and available IP addresses. In most small networks
the router acts as the DHCP server.
2.1 Objective
2.2 Scope
Word files are called documents. Whenever you start a new project in Word, you'll need to create
a new document, which can either be blank or from a template. You'll also need to know how to open
an existing document.
In addition to creating new documents, you'll often need to open a document that was previously
saved.
1. Navigate to Backstage view, then click Open.
3. The Open dialog box appears. Locate and select your document, then click Open
Whenever you create a new document in Word, you'll need to know how to save in order to access
and edit it later. As in previous versions of Word, you can save files to your computer.
Word offers two ways to save a file: Save and Save As. These options work in similar ways, with a
few important differences:
Save: When you create or edit a document, you'll use the Save command to save your changes.
You'll use this command most of the time. When you save a file, you'll only need to choose a file
name and location the first time. After that, you can just click the Save command to save it with
the same name and location.
Save As: You'll use this command to create a copy of a document while keeping the original. When
you use Save As, you'll need to choose a different name and/or location for the copied version.
To save a document:
It's important to save your document whenever you start a new project or make changes to an
existing one. Saving early and often can prevent your work from being lost. You'll also need to pay
close attention to where you save the document so it will be easy to find later.
1. Locate and select the Save command on the Quick Access toolbar.
2. If you're saving the file for the first time, the Save As pane will appear in backstageview.
4. The Save As dialog box will appear. Select the location where you wish to save the document.
5. Enter a file name for the document, then click Save.
6. The document will be saved. You can click the Save command again to save your changes as you
modify the document.
Formatting Text
Formatted text can draw the reader's attention to specific parts of a document and emphasize
important information. In Word, you have many options for adjusting the font of your text,
Introduction to Computers and Programming Lab Manual – Page 15|222
including size, colour, and inserting special symbols. You can also adjust the alignment of the text to
change how it is displayed on the page.
By default, the font of each new document is set to Calibri. However, Word provides a variety of
other fonts you can use to customize text and titles.
1. Select the text you wish to modify.
2. On the Home tab, click the drop-down arrow next to the Font box. A menu of font styles will
appear.
3. Move the mouse over the various font styles. A live preview of the font will appear in the
document. Select the font style you wish to use.
The header is a section of the document that appears in the top margin, while the footer is a
section of the document that appears in the bottom margin. Headers and footers generally contain
additional information such as page numbers, dates, an author's name, and footnotes, which can help
keep longer documents organized and make them easier to read. Text entered in the header or
footer will appear on each page of the document.
Word has a variety of preset headers and footers you can use to enhance your document's design
and layout. In our example, we'll add a preset header to our document.
1. Select the Insert tab, and then click the Header or Footer command. In our example, we'll
click the Header command.
2. In the menu that appears, select the desired preset header or footer. In our example, we'll
select a header.
5. When you're finished, click Close Header and Footer. Alternatively, you can press the Esc key.
Adding pictures to your document can be a great way to illustrate important information or add
decorative accents to existing text. Used in moderation, pictures can improve the overall
appearance of your document.
If you have a specific image in mind, you can insert a picture from a file. In our example, we'll
insert a picture saved locally on our computer.
1. Place the insertion point where you want the image to appear.
2. Select the Insert tab on the Ribbon, and then click the Pictures command.
3. The Insert Picture dialog box will appear. Select the desired image file, and then click Insert.
Predefined text wrapping allows you to move the image to a specific location on the page.
1. Select the image you want to move. The Format tab will appear on the right side of the Ribbon.
A table is a grid of cells arranged in rows and columns. Tables are useful for various tasks such as
presenting text information and numerical data. In Word, you can create a blank table, convert
text to a table, and apply a variety of styles and formats to existing tables.
1. Place your insertion point where you want the table to appear, and then select the Insert
tab.
2. Click the Table command.
4. Click the mouse, and the table will appear in the document.
Hover the mouse near the location where you wish to add a row or column, you will see a plus sign
that appear, click it and new row will appear.
1. Place a insertion a point in the row or column that you want to delete
2. Right Click the mouse button, then select Delete Cells from the menu the appears
1. Click anywhere on the table, then click the Design tab on the right side of the Ribbon.
Formatting Text
1. Open an existing Word 2013 document.
2. Change the font style of some text.
3. Change the font size of some text. Change the font colour of some text.
4. Highlight some text.
5. Try bolding, italicizing, or underlining some text.
6. Change the case of some text.
7. Centre aligns some text.
Tables
2.1 Objective
To familiarize the students with the importance of MS PowerPoint, creating the presentation from
scratch and learning different basic features of the PowerPoint presentation. Gives overview about
the different tool bars and explains how to apply new themes, transitions, animations and smart art.
2.2 Scope
The student should know the following at the end of this lab:
1. Create presentation from scratch.
2. Saving your presentation.
3. Add new slides and changing its layout.
4. Adding new themes
5. Adding transition to slides
6. Adding animation to slides
7. Add smart Art Graphics
2.3 Useful Concepts
Introduction to PowerPoint Presentation
PowerPoint files are called presentations. Whenever you start a new project in PowerPoint, you'll
need to create a new presentation, which can either be blank or from a template.
Create a Presentation
1. Select the File tab to go to backstage view.
2. Select New on the left side of the window, then click Blank Presentation or choose a
theme.
Whenever you create a new presentation in PowerPoint, you'll need to know how to save in order to
access and edit it later.
1. Locate and select the Save command on the Quick Access Toolbar.
2. If you're saving the file for the first time, the Save As pane will appear in backstage view.
3. You'll then need to choose where to save the file and give it a file name. To save the
presentation to your computer, select Computer, and then click Browse.
6. The presentation will be saved. You can click the Save command again to save your changes
as you modify the presentation.
Slides contain the information you will present to your audience. This might include text, pictures,
charts, and more. Before you start creating presentations, you'll need to know the basics of
working with slides and slide layouts.
When you insert a new slide, it will usually have placeholders. Placeholders can contain different
types of content, including text and images. Some placeholders have placeholder text, which you can
Slides have several different layouts for placeholders, depending on the kind of information you
want to include. Whenever you create a new slide, you'll need to choose a slide layout that fits your
content.
Whenever you start a new presentation, it will contain one slide with the Title Slide layout. You can
insert as many slides as you need from a variety of layouts.
1. From the Home tab, click the bottom half of the New Slide command.
2. Choose the desired slide layout from the menu that appears.
3. The new slide will appear. Click any placeholder and begin typing to add text. You can also
click an icon to add other types of content, like a picture or a chart.
A theme is a predefined combination of colours, fonts, and effects. Different themes also use
different slide layouts. You've already been using a theme, even if you didn't know it: the default
Office theme. You can choose from a variety of new themes at any time, giving your entire
presentation a consistent, professional look.
Theme elements
Theme Colours
Themes Fonts
Theme effects
As you can see from the two different Title Slides above, themes can also change various slide
layouts. Some themes, like the Wisp theme in the example below, even include additional layouts.
Applying Transitions
A transition can be as simple as fading to the next slide, or it can be a flashy, eye-catching effect.
PowerPoint makes it easy to apply transitions to some or all of your slides, giving your presentation a
polished, professional look.
To apply a Transition
Introduction to Computers and Programming Lab Manual – Page 36|222
1. Select the desire slide from the Slide Navigation pane. This is the slide that will appear
after the transition.
4. Click the Transition to apply it. This will automatic preview the transition.
You can also apply to all command to apply the transition to all group .
Applying Animation
You can animate different element in PowerPoint such as picture, shapes and text etc.
3. Select the desire animation effect. The effect will apply to the element.
Extra
Some of the effects have options, which can be changed using effect options in Animation group.
Introduction to Computers and Programming Lab Manual – Page 41|222
Smart Art Graphics
1. When you select Smart Art. The Smart Art pane will appear on side as shown above.
2. Enter the text on each bullet on the task pane. It automatically re-size a shape.
Slide Basics
Applying Animation
Applying Themes
Applying Transitions
2.1 Objective
To familiarize student with Excel environment.
To familiarize students with plotting charts.
Excel 2013 is a worksheet that allows you to store, organize, and analyze information. We will learn
how to use Excel‘s powerful features.
Name Box
Worksheets
Excel files are called workbooks. You can create a Excel workbook in many ways such as with a new
workbook either Blank workbook or predefine template.
1. Select File Tab and Click New then Click Blank Workbook.
Sheet Basic
Whenever you work on Excel, you will use cell to enter information.
Cells Basic
A rectangle that was appear in sheet is known as cell. A cell is consist of Row and Column. Columns
are identified by Letters (A, B, C) while rows by Number (1, 2, 3). Cell Address is appear in Name
Box. Such as E5 means Column E and Row 5.
Introduction to Computers and Programming Lab Manual – Page 49|222
Cell Name or
Address appears
Fill Handle
1. Select a cell(s) you wish to use. The fill handle will appear as a small dot at the right-bottom
corner of selected cells.
Fill Handle
2. Hold and drag a fill handle to desire number of cells and release it.
If all cells are of same format then it is very difficult to read a workbook and extract an
information. Basic customization will allow you to draw an attention to specific section and
understand to information.
Text Alignment
The default text alignment is bottom left of the cell. You can change the alignment of the cell
horizontally or vertically from Home Tab.
1. Select the cell you want to modify
2. Select any one of the six horizontal or vertical alignment.
Conditional Formatting
Conditional formatting allows you to automatically apply formatting—such as colours, icons, and data
bars—to one or more cells based on the cell value. To do this, you'll need to create a conditional
formatting rule.
1. Select a cells for a conditional formatting rule.
2. From Home Tab select, Click Conditional Formatting command. A drop down menu will appear.
3. Hover the mouse over the desired conditional formatting type, and then select the desired
rule from the menu that appears.
One of the most powerful features in Excel is the ability to calculate numerical information using
formulas. Just like a calculator, Excel can add, subtract, multiply, and divide. In this lesson we will
also show you how to use cell reference.
Cell Reference
While you can create simple formulas in Excel manually (for example, =2+2 or =5*5), most of the
time you will use cell addresses to create a formula. This is known as making a cell reference. Using
cell references will ensure that your formulas are always accurate because you can change the value
of referenced cells without having to rewrite the formula.
By combining a mathematical operator with cell references, you can create a variety of simple
formulas in Excel. Formulas can also include a combination of cell references and numbers, as in the
examples below.
Excel includes several tools that make it easier to view content from different parts of your
workbook at the same time, such as the ability to freeze panes and split your worksheet.
To freeze rows
You may want to see certain rows or columns all the time in your worksheet, especially header cells.
By freezing rows or columns in place, you'll be able to scroll through your content while continuing
to view the frozen cells.
1. Select the row below the row(s) you wish to freeze. In our example, we want to freeze rows
1, 2and 3, so we'll select row 4.
4. The rows will be frozen in place, as indicated by the thin gray line.
It can often be difficult to interpret Excel workbooks that contain a lot of data. Charts allow you
to illustrate your workbook data graphically, which make it easy to visualize comparisons and trends.
Insert a chart
1. Select a cells you want to chart including columns titles and row labels. These cells will be
source data of the Chart.
2. From Insert Tab, Click the desire chart command. We select columns.
3. Choose the desire chart type from the drop down list.
Cell formatting
1. Create a new Excel workbook.
2. Select a cell and change the font style, size and colour of the text.
3. Applying bold, italics or underline to a cell.
4. Try using Vertical or Horizontal text alignment.
5. At a border to cell range.
6. Change the fill colour of cell range.
Simple Formulas
1. Create a new Excel workbook and enter some data in it.
2. Create a simple formula using cell reference.
3. Try modifying the value of cell referenced in a formula.
4. Edit the formula using the formula bar, change the sign to division (/) and minus (-).
Conditional Formatting
1. Create a new Excel workbook and enter some data in it.
2. Apply conditional formatting to a range of cells with numerical values.
3. Apply a second conditional formatting rule to the same set of cells.
4. Clear all conditional formatting rules from workbook.
Freezing pane
1. Create a new Excel workbook and enter some data in it.
2. Try freezing a row or column in place. E-g: freeze top 3 rows or columns.
Charts
How to install Dev C++ Compiler, Edit, compile and Run a C++
Program.
3.1 Objective:
1. Learn basic components of a C program.
3.2 Scope:
The student should know the following at the end of this lab:
1. Problem solving
2. How to install run and compile.
A C-program:
o #include command will include header files that have the definition of a function
used in the program like getche() function that is in stdio.h file.
o Note: #include <file> tells the compiler to look for file where system include files
are held
o #include "file" tells the compiler to look for file in the current directory where
the program was run from.
o #define is used to replace a text with a value, e.g. #define PI 3.141593
A function is a block of statements that make a specific kind of processing. Every C program
has a main() function. The execution starts from main().
Variables / identifiers
These are used to store data in a program. You must declare a variable before you use it.
{ int main(void)
declarations {
} getche();
Compilatio
n
Successful
Unsuccessf
ul
Error Object
Message Code
Linking Other
Object
Code
Executable
File
12. If you did not have a syntax error on your code, you will get this output.
/* Volume of a sphere */
#include <iostream.h>
#include <stdio.h>
#include<math.h>
#define PI 3.14159
int main(void)
cin>>radius;
getche();
return 0;
}
3.5 Home Work
1) Launch TurboC++ in your computer and run the above programs.
4.1 Objective:
To familiarize the students with the use of single line comment, multi line comment cout and cin
statements.
4.2 Scope:
The student should know the following at the end of this lab:
1. Problem Solving
printf()
Instructs computer to perform an action
o Specifically, used to print the ―character, string, float, integer, octal and
hexadecimal values‖ onto the output screen.
Escape character (\)
Scanf()
When executing the program the user responds to the scanf statement by typing in
a character from keyboard, then pressing the enter (return) key
The format specifier %d is used in scanf() statement. So that, the value entered is
received as an integer and %s for string.
Ampersand is used before variable name in scanf() statement i.e. ch is written as
&ch.
4.4 Examples
Example -2:- This program illustrates the use of single line (//text) and multi line comments (\* text *\).
Example-3:- This program illustrates the use of nested multi line comments.
# include <conio.h>
void main()
{
printf("This is my first program in C language");
/* this is not /* allowed nested comments */ */
getch();
Example-4:- This program illustrates the use of nested multi line comments in printf statement.
# include <conio.h>
void main()
Example-5:- This program illustrates the use of scanf() for integer value.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
printf("Enter a value");
scanf("%d",&i);
printf( "\nYou entered: %d",i);
getch();
}
#include <stdio.h>
int main()
{
char ch;
Introduction to Computers and Programming Lab Manual – Page 75|222
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
Exercise 2:- Write a program that prints the following diagram using printf statement.
*********
* *
* *
*********
4.5 Home Work:
1) Write a program that take six subjects marks from user and display the sum of all marks.
Data Types
5.1 Objective:
Learn the Problem Solving and Basics C Language
5.2 Scope:
The student should know the following:
Problem Solving
Different data types of C and their Use.
Declaring Variables
Standard Input and Output
Writing Complete Programs
5.3 Useful Concept:
An useful List of basic data type of C , number of bytes used to store these data types in memory
of computer system:
unsigned char 1
float 4
double 8
long double 10
Variables
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
5.4 Examples:
}
Introduction to Computers and Programming Lab Manual – Page 78|222
Here‘s the program‘s output:
void main()
char ch = 'A';
char str[20] = "Comsats";
int no = 150;
getch();
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
# include <conio.h>
void main()
{
float radius,area;
printf( "Enter radius of circle: ");
scanf( "%f", &radius) ;
area = 3.14*radius*radius;
printf( "Area of the circle is: %f \n", area);
getch();
}
# include <conio.h>
void main()
{
char x, y ;
int z ;
x = 'a' ;
y = 'b' ;
z=x+y; //Add the assci value of 'a' with assci value of 'b' and store in z.
printf("Sum of the characters : %d \n", z);
}
Introduction to Computers and Programming Lab Manual – Page 81|222
Example - 6:- This program illustrates the use of sizeof() function which is used to find the
memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
int a;
char b;
float c;
double d;
return 0;
}
Exercise 2:-Write a program that takes any ASCII value from user and display next five char after
that ASCII value.
Hints: - if user enters 95, your program should display the char against the ASSCII value
96,97,98,99 and 100.
5.6 Home Work
1. Write a program converts a temperature from Celsius to Fahrenheit. Use the following formula:
F = 1.8 x C + 32 .
2. Write a program that reads three integers representing hours, minutes, and seconds of a time.
Then it calculates the equivalent time in seconds.
6.1 Objective
Learn using operators, expressions and math functions.
6.2 Scope
The student should know the following at the end of this lab:
1. Arithmetic Operators
2. Arithmetic Expressions
3. Math Functions
If the operands are of different types, the one with weaker type will be raised to the level of the
other type, then the operation will be performed. The order is char, int, long, float, double.
The division between two integer numbers results in an integer result (as you can see 5/2 gives 2
not 2.5).
The division by zero is undefined. Either you get a compilation warning or a run time error.
The remainder operator % is related to the division one. This operator will give the remainder
produced by dividing the two numbers (5 % 2 = 1). Therefore, this operator is not used with double
values. If one of the operand or both are double, you will get an error message from the compiler
saying:
Illegal use of floating point
Arithmetic Expressions:
Arithmetic expressions contain a combination of the arithmetic operations including brackets:
x = z – (a + b / 2) + w * -y
To evaluate the expression, we need to follow the precedence rule which is as follows:
6.4 Examples:
Example1: Program illustrates how to input two variables from the user and display their sum. Both
variables are integers.
#include<stdio.h>
#include<conio.h>
int main ()
{
int val1,val2, result=0;
scanf("%d", &val1);
result=val1+val2;
getch();
}
#include<stdio.h>
#include<conio.h>
int main ()
{
int a=4, b, c;
printf("a= %d b= %d c= %d",a,b,c);
b=6;
c=a+b;
printf("\na= %d b= %d c= %d",a,b,c);
printf("\na= %d b= %d c= %d",a,b,c);
b *= ++a; //a=a+1;, b=b*a;
printf("\na= %d b= %d c= %d",a,b,c);
c /= a++; //c=c/a;, a=a+1;
printf("\na= %d b= %d c= %d",a,b,c);
getch();
}
#include<conio.h>
#include<stdio.h>
int main ()
{
char val1,val2;
int sum=0;
val1='a';
val2='b';
sum=val1+val2;
printf("\nThe sum of the values entered is: %d",sum);
getch();
}
The output for the above given program is
int main ()
{
int n,a,b;
printf("Enter the 3 digit value to be reversed:");
scanf("%d", &n);
a=n/100;
n=n%100;
b=n/10;
n=n%10;
getch();
}
Math function:
To do some advanced mathematical functions in C, there is a header file called <math.h> that has
different trigonometric and algebraic functions. Here are some frequently used functions:
log 10 x
log10(x) (x > 0) log10(5) = 0.698970
exp(x) ex exp(2) = 7.3891
Note that you have to include the header file math.h before you use any of these functions. Also,
the return type of these functions is double.
Example1: Input the values for base and exponent and calculate its power using the pow(x,y) built
in function.
#include<conio.h>
#include<stdio.h>
#include<math.h>
int main ()
{
int base,expo,result=0;
scanf("%d",&expo);
result= pow(base,expo);
printf("the result is: %d", result);
getch();
}
The output for the given program is
area s s a s b s c
abc
s
2
Exercise 2: Write a program taking two values as inputs from the user and display the results for
all the basic arithmetic operations performed on them
Addition
Subtraction
Multiplication
Division
Modulus
Exercise 3: Write a program that inputs a 4 digit value from the user (for example 6382) and
displays a result with an increment of 1 in each digit (i.e. 7493)
6.6 Home Task
1. Write a program that takes any ASCII value from user and display next five char after
that ASCII value.
2. Write a program that reads a four digit number from user, then the program separates
digits of the number e.g. 4567 to be displayed as:
4
5
7.1 Objective
The student should practice the following statements:
1. if statemets
2. if-else statements
3. Nested if/if-else
5. Switch statement¨
7.2 Scope
By the end of this lab a student should know:
7.4 Examples
#include<conio.h>
#include<stdio.h>
int main ()
{
int marks,total,percent=0;
printf("Enter the marks obtained in itcp:");
scanf("%d", &marks);
printf("Enter the total marks of the subject:");
scanf("%d",&total);
percent= (marks*100)/total;
if (percent>=50)
Introduction to Computers and Programming Lab Manual – Page 91|222
printf("Congragulations you have passed this subject");
getch();
}
Output for the above program is
If you want to execute more than one statement based on that condition, then your statements
should be enclosed with brackets. For example
#include<conio.h>
#include<stdio.h>
int main ()
{
int marks,total,percent=0;
scanf("%d", &marks);
scanf("%d",&total);
percent= (marks*100)/total;
if (percent>=50)
{
printf("Congragulations you have passed this subject");
printf(―Well done‖);
}
getch();
}
If-else statements
#include<conio.h>
#include<stdio.h>
int main ()
{
int marks,total,percent=0;
scanf("%d", &marks);
printf("Enter the total marks of the subject:");
scanf("%d",&total);
percent= (marks*100)/total;
if (percent>=50)
{
printf("Congratulations you have passed this subject");
else
printf(" Sorry you did not pass this course, Better luck next time");
getch();
The output for the above program in case the condition is not satisfied (else part is executed) is
shown below
Here, if the condition is true, the if-part will be executed and the else-part is ignored. But if the
condition is false, the if-part is ignored and the else-part is executed.
#include<conio.h>
#include<stdio.h>
int main ()
{
int value;
printf("Enter a number ");
scanf("%d", &value);
if (value>0)
else
#include<stdio.h>
#include<conio.h>
int main ()
{
int a,b,c,d,e;
printf("enter 1st number: ");
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
printf("enter 4th number: ");
scanf("%d",&d);
scanf("%d",&e);
if(a>b&&a>c&&a>d&&a>e)
printf("%d is greatest",a);
}
else
if(b>a&&b>c&&b>d&&b>e)
printf("%d is greatest",b);
else
if(c>a&&c>b&&c>d&&c>e)
}
else
if(d>a&&d>b&&d>c&&d>e)
{
printf("%d is greatest",d);
}
else
if(e>a&&e>b&&e>c&&e>d)
printf("%d is greatest",e);
}
getch();
Example: Prompt the user to enter the salary and grade of an employee. If the employee has a
grade greater than 15 then add 50% bonus to the employee‘s salary. Otherwise if the employee‘s
grade is less than 15 then add 25% bonus to the employee‘s salary.
#include<stdio.h>
#include<conio.h>
int main()
{
int grad,sal,bonus;
printf("enter salary");
scanf("%d",&sal);
scanf("%d",&grad);
if (grad>15)
{
bonus=sal*(50.0/100.0);
printf("total salary with 50 percent bonus %d",bonus+sal);
}
else if (grad<=15)
getch();
Here each condition is tested one by one starting from the first one. If one of them is true, then
the statement associated with that condition is executed and the rest are ignored.
Nested if structure:
An if statement within an if statement is called nested if statement. In nested structure, the
control enters into the inner if only when the outer condition is true. Only one block of statements
are executed and the remaining blocks are skipped automatically.
The user can use as many if statements inside another is statements as required. The increase in
the level of nesting increases the complexity of nested if statement.
Example: Prompt the user to input three values so as to display them in ascending order.
#include<stdio.h>
int main ()
{
int a,b,c;
scanf("%d",&a);
printf("Enter the first number:");
scanf("%d",&b);
scanf("%d",&c);
if(a<b && a<c)
if (b<c)
if (a<c)
else
printf("%d %d %d", b,c,a);
}
if (b<a)
getch();
}
Switch statement:
Another useful statement in C is the switch statement. This statement is somehow similar
to if statement in giving you multiple options and do actions accordingly. But its behaviour is
different. This statement tests whether an expression matches one of a number of constant
integer values labelled as cases. If one matches the expression, execution starts at that case. This
is the general structure of the switch statement:
switch (expression)
break;
case constant: statements
case constant: statements;
break;
default: statements
The default clause is optional. If it is not there and none of the cases matches, no action is taken.
The break keyword is used to skip the switch statement. For example if a case matches the
#include<stdio.h>
#include<conio.h>
int main ()
{
char grade;
switch(grade)
case 'A':
case 'B':
break;
case 'C':
break;
case 'D':
printf("You have scored 60% marks");
break;
case 'F':
break;
default:
printf("You have entered an invalid grade");
break;
getch();
}
7.5 Exercise for Lab
Exercise1: Prompt the user to input 5 values and display the minimum number amongst them.
Exercise2: Input 5 values from the user and display the number of positives, the number of
negatives and the number of zeros amongst the 5 values.
Exercise3: Prompt the user to input a character and display whether it is a vowel or consonant
using switch statement.
7.6 Home Task
1. Ask the user to enter marks obtained in a course and the total marks of the course. Then
display a menu
If the user presses 1 then percentage should be displayed and if the user presses 2 the
grade against the marks should be displayed. (Hint: use switch statement for menu selection
and else if to display the grade).
2. Prompt the user to enter 3 values. For any equal values, the program should display the
numbers that are equal. (For example user input 34,6,34 the program should display the
message that the 1st and 3rd values are equal).
LOOPS
8.1 Objective:
Learn about theprimary mechanism for telling a computer that a sequence of tasks needs to be
repeated a specific number of times.
8.2 Scope:
The student should know the following:
1. Requirement to add a number to itself ten times.
2. To execute a statement or group of statements multiple times.
8.3 Useful Concepts:
Loop statements are the primary mechanism for telling a computer that a sequence of tasks needs
to be repeated a specific number of times. Suppose, for example, that you have a requirement to
add a number to itself ten times. A loop statement allows us to execute a statement or group of
Loops are relatively easy to implement, yet they can save you a lot of coding.
LOOPS can be of different types:
LOOPS can be divided as:
1. While Loop:
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2. Do while Loop:
Like a while statement, except that it tests the condition at the end of the loop body.
3. For Loop:
Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
4. Nested Loop:
You can use one or more loops inside any another while, for or do. While loop.
For loop:
The for() loop is basically three statements in one line. Within the parentheses following
the ―for‖, you have the initial expression, condition, and the loop expression. These are
separated by semicolons.
Syntax:
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
// statements to be executed
}
The initializer typically initializes a counter variable. Traditionally the variable name i is
used for this purpose, though any valid variable name will do.
Example:
i = 0;
The conditional expression specifies the test to perform to verify whether the loop has
been performed the required number of iterations. For example, if we want to loop 10
times:
i < 10;
While Loop:
The while() loop is better suited for cases where the program does not know how many times it is to
be run, and instead checks for a different condition.
Syntax:
while (input >= 0) { // "Greater-than or equal to zero" is the same as "not negative"
}
o
D0 While Loop:
In a regular for() or while() loop, the condition is checked first, then the loop is executed. This
means that if the initial condition was false to begin with, the body of the loop would never ever get
executed; the code would skip directly over the loop. The do-while loop is guaranteed to perform
one iteration of the loop first, before checking the condition. From that point on, as long as the
condition remains true, the loop will continue to execute.
Syntax:
int n = 1;
do {
sum = sum + n;
n = n + 1;
} while (n <= 5)
There are two statements (break; and continue ;) built in C programming to alter the normal flow of
program. Loops are used to perform repetitive task until test expression is false but sometimes it
is desirable to skip some statement/s inside loop or terminate the loop immediately with checking
It is sometimes necessary to skip some statement/s inside the loop. In that case, continue;
statement is used in C++ programming.
Syntax:
continue;
Working Body:
Syntax:
8.4 Examples
Example – 1:- Write a program Show all odd numbers using a for loop.
#include <iostream>
int main()
{
for (int count = 1; count <= 41; count += 2)
{
cout << count << ", ";
}
cout << endl;
return 0;
Output:
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41,
Example – 2:- Write a program using do-while loop to display following output.
# include <stdio.h>
# include<conio.h>
int main()
printf("%d\n", j);
j = j + 1;
}
return 0;
}
Output:
int main()
{
// variables for counter…
int i = 15, j;
// outer loop, execute this first...
while(i>0)
// display i==
printf("%d==", i);
// then, execute inner loop with loop index j,
while(j>0)
// display #
printf("#");
// decrement j by 1 until j>10, i.e j = 9
j = j - 1;
}
return 0;
}
Output:
Example – 4:- Write a program that contains nested loops to display pyramid as shown in output.
# include <stdio.h>
# include<conio.h>
int main()
int i, j;
// display i
printf("%d", i);
// display ==j
printf("==%d", j);
j = j - 1;
// go to new line
printf("\n");
i = i + 1;
return 0;
Output:
int main(void)
{
int i, j;
// for loop
printf("This is a for loop\n");
printf("\n");
}
printf("\nBoth constructs generate same result...\n");
return 0;
}
1. Read in 10 integers.
Exercises -2) Write a three-letter acronym-generating program. The program‘s output lists all
three-letter combinations from AAA through ZZZ, spewed out each on a line by itself.
8.6 Home Work
1) Write a program that calculate the factorial of a number using while loop.
2) Write a program that inputs a number from a user and display its multiples using for loop.
3) Write a program that inputs a number and length from a user and display its table.
Arrays
9.1 Objective:
Learn how to declare, initialize and use one-dimensional arrays.
9.2 Scope:
The student should know the following:
3. Syntax of array declaration
4. assigning and processing and elements
9.3 Useful Concepts:
An array is a collection of two or more adjacent memory cells, called array elements that
are associated with a particular symbolic name. Arrays are very useful construct to store related
values together instead of declaring several variables for each value.
To set up an array in memory, we must declare both the name of the array and the number of cells
associated with it.
The following declaration will instruct the compiler to allocate eight memory cells with the name x;
these memory cells will be adjacent to each other. Each element may contain a value of type double.
double x[8];
0 1 2 3 4 5 6 7
As you can see; the name of the array x points to the first element of the array.
We can define a constant for array size and use it whenever we declare an array.
int id[NUM_STUDENTS];
double gpa[NUM_STUDENTS];
To access the data stored in an array, we reference each individual element by specifying the array
name and identifying the element desired.
x[0] the value of the first element
NOTE: The indices of the elements start from 0 not from one.
Array initialization:
We can initialize an array directly by specifying each cell value individually as follows:
Hence here we do not need to specify the size of the array or how many elements this array should
have. This number can be deduced from the initialization list.
We can also use for loop which is the common way to deal with arrays in general. The following code
initializes array square to squares of the indices:
square[i] = i * i;
0 1 4 9 16 25 36 49
Array Processing:
Elements of the array are dealt as normal variables, the only difference here is to specify
the index desired. These statements are examples of using array elements:
We can apply any expression to specify the index as well. Consider these statements:
i = 5;
cout<< x[i+1]; display 14.0 (value of x[6])
Example – 1:-Write a program that contains an array of ten elements, take ten values from user,
assign the value to each element of array and display the all array elements.
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
return 0;
}
Output:-
void main()
{
int a[5];
clrscr();
printf("Enter the array elements\n");
for (i=0; i<5; i++)
scanf("%d",&a[i]);
Output:-
Example – 3:- Write a program that takes an integer value from user and search it in array, If
found then display message ‗Number Found‘ else ‗Number Not Found.
#include <stdio.h>
int main()
{
int array[100], search, c, n;
return 0;
}
Output:-
int main()
{
int array[100], maximum, size, c, location = 1;
maximum = array[0];
printf("Maximum element is present at location %d and it's value is %d.\n", location, maximum);
return 0;
}
Output:-
return 0;
}
Output:-
int main()
Output:-
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
return 0;
}
Output:-
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
return 0;
Output:-
Example – 9:- Write a program that passes an array containing age of person to a function. This
function should find average age and display the average age in main function
#include <stdio.h>
float average(float a[]);
int main(){
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]){
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}
Output:-
#include<stdio.h>
#include<conio.h>
void modify(int b[3]);
void main()
{
int arr[3] = {1,2,3};
modify(arr);
for(i=0;i<3;i++)
printf("%d",arr[i]);
getch();
}
Output:-
64 36 56 47 40 54 61 60 58 64 54
48 59 45 63 54 50 49 51 60 58 59
Initialize an array with above grades and find the following things about the above data.
2-D Arrays
10.1 Objective:
Learn how to declare, assign and manipulate two dimensions array.
10.2 Scope:
The student should know the following:
1. What is 2-D array?
2. Declaring 2-D arrays and bound checking.
int myarray[2][3];
The name of the array to be‖ myarray‖, type of the array elements to be ―int‖, dimension to be 2
(two pairs of brackets [])
The number of elements or size to be 2*3 = 6
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
int c[ ][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
In this way by increasing the index value of the array the elements can be entered in a 2d
array
{
cin<a[i][j];
}
The output of two-dimensional arrays should be in the form of rows and columns for
readability. Nested for loops are used to print the rows and columns in row and column
order.
By increasing the index value of the array the elements stored at that index value are
printed on the output screen.
{
for(j=0 ; j<3 ; j++)
cout<<a[i][j];
} cout<<endl;
}
int array[10][10];
// ...
passFunc(array);
2. The parameter is an array containing pointers
int *array[10];
// ...
passFunc(array);
3. The parameter is a pointer to a pointer
int **array;
// ...
passFunc(array);
10.4 Examples
Example -1:- A program to input elements in a two dimensional array and print it.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3];
int i,j;
scanf(―%d‖,&a[i][j]);
}
{
for(j=0 ; j<3 ; j++)
printf(―%d‖,a[i][j]);
} printf(―\n‖);
}
getch();
Output:-
#include<stdio.h>
#include<conio.h>
void main()
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
{
scanf(―%d‖,&a[i][j]);
}
}
for(i=0 ; i<3 ; i++)
scanf(―%d‖,&b[i][j]);
}
Introduction to Computers and Programming Lab Manual – Page 131|222
}
{
c[i][j]=a[i][j]+b[i][j];
printf(―%d‖,c[i][j]);
}
printf(―\n‖);
getch();
}
Output:-
#include<stdio.h>
#include<conio.h>
void main()
int i,j;
clrscr();
printf(―enter the elements in the array‖);
scanf(―%d‖,&a[i][j]);
}
for(j=0 ; i<3 ; i++)
{
printf(―%2d‖,&b[j][i]);
getch();
}
Output:-
#include<conio.h>
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
Introduction to Computers and Programming Lab Manual – Page 134|222
}
Output:-
10.5 Exercises for lab
Exercises-1) Declare and initialize a 2D arrays with different methods.
Exercises-3) Write a program that will sort 2d array in ascending order and descending
order.
Exercises-5) A program to input a matrix and find its determent(by using function).
A program to input a matrix and find its singular or non-singular(by using function).
A program to input a matrix and find its mean ,median ,standard deviation(write separate
function).
Structures in C
11.1 Objective:
To familiarize the students with the use of structure and nested structure
11.2 Scope:
The student should know the following at the end of this lab:
4. Array of structures
5. Passing structures to the function
This declares a structure with user_record as tag. Again, memory is not allocated until a variable
is declared.
A variable with the above structure can be declared as:
Introduction to Computers and Programming Lab Manual – Page 136|222
struct user_record user;
We can simplify the variable declaration above, if we use typedef in the declaration.
The above can then be defined as:
typedef struct {
int id_no;
STRING name;
STRING dept;
int no_of_books;
USER_STATUS status;
} USER_RECORD;
We can combine declarations and declare structure variables at the same time that the structure
type is declared. For example:
struct date
{
int day, month, year;
} arrival_date, departure_date;
or without a structure tag
structure { int day, month, year;} arrival_date, departure_date;
Structure Initialization:
main()
{
USER_RECORD user;
user.no_of_books=0;
printf("Enter user details:\n");
printf ("ID_NO: ");
scanf(“%d”, user.id_no);
printf("NAME: ");
fflush(stdin);
gets(user.name);
printf("DEPARTMENT: ");
gets(user.dept);
printf("STATUS [0 for student, 1 for staff or 2 for faculty: ");
scanf(“%s”,user.status);
printf("\nThe details you entered are:\n");
printf("\nID_NO: %d , user.id_no);
printf("\nNAME: %s", user.name);
printf("\nDEPARTMENT:%s ", user.dept);
printf("\nSTATUS: %s ", user.status);
printf("\nNO OF BOOKS %d ",user.no_of_books);
return 0;
int month;
int year;
} DATE;
typedef struct {
int bk_no;
STRING author;
STRING title;
STRING publisher;
DATE pub_date;
BOOK_STATUS status;
Notice that we need two dot operators to access the publication date in the variable book as shown below:
book.pub_date.day=2;
book.pub_date.month=5;
book.pub_date.year=1980;
defines an array called dates, which consists of 10 elements. Each element inside the array is
defined to be of type struct date. Referencing a particular structure element inside the array is
done, by using the subscripts as done for normal variables. For example, to set the day of the 4th
structure element of dates array to 25, we write
dates[3].day = 25 ;
Like simple variables, and unlike arrays, it is allowed to assign an entire structure to another
structure of the same type.
book2 = book1.
However, comparison is not allowed on entire structures. It has to be done on field by field
basis.
return samebook;
}
int month ;
int day ;
int year ;
};
The variable date_pointer can be set to point to today with the assignment statement
date_pointer = &today ;
Once such an assignment has been made, we can then indirectly access any of the members of the
date structure pointed to by date_pointer in the following way:
(*date_pointer).day = 21 ;
OR
date_pointer->day = 21 ;
The symbol -> is known as structure pointer operator, which is a minus sign immediately followed by
a greater than sign.
A pointer to a structure identifies its address in the memory, and is created in the same way that a
pointer to a simple data type such as int or char is created.
11.4 Examples
Example -1:- Write a program that updates the record of a user and a book when the user
borrows the book from our small library.
{ (*book).status = BORROWED;
In the above example, the * is necessary since book in the function is a pointer
variable, so we need to dereference it to access the object it is pointing to.
The bracket in (*book).status is also necessary since the dot operator has high
priority than *.
Another way to represent above statement is by using the arrow operator (->).
e.g.
book -> status; is equivalent to (*book).status;
};
int main ( )
input ( &FirstCar ) ;
return 0 ;
}
/* input: This function expects a pointer to a structure of type struct car. It reads
data items from the keyboard and saves them in the structure member
variables.
*/
void input ( struct car * sp )
/*
output: This function expects pointers to two strings and a pointer to an int type variable.
It displays the specified two strings and the integer number.*/
void output ( char * s1, char * s2, int * ip )
void main()
{
struct world
{
int a;
char b;
struct country
char c;
float d;
}p;
};
printf("%d\t%c\t%c\t%f",st.a,st.b,st.p.c,st.p.d);
getch();
Output:
else
cout<<―The time now is ―<<h <<‖:‖<< m <<‖:‖ s<<‖pm‖;
int main ()
{
time t;
cin>>t.hour;
cin>>t.second;
Exercise -2) Write a program that demonstrates the passing of individual structure member to the
function.
Exercise -3) What will be output of following c code?
void main()
struct employee
{
unsigned id: 8;
unsigned age:7;
};
struct employee emp1={203,1,23};
clrscr();
printf("%d\t%d\t%d",emp1.id,emp1.sex,emp1.age);
getch();
}
void main()
{
struct field
int a;
char b;
}bit;
char *p=&bit1;
*p=45;
clrscr();
printf("\n%d",bit1.a);
getch();
}
Exercise -5) what will be output of following c code?
void main()
Struct country
{
char c;
float d;
Introduction to Computers and Programming Lab Manual – Page 146|222
};
struct world
{
int a[3];
char b;
struct country abc;
};
struct world st ={{1,2,3},'P','q',1.4};
clrscr();
printf("%d\t%c\t%c\t%f",st.a[1],st.b,st.abc.c,st.abc.d);
getch();
}
1) Write a program that demonstrates the passing of entire structure as parameters to the
called function.
2) Write a program that demonstrates the passing address of the structure variable to the
called function using pointers.
3) Write a structure that demonstrates the returning of array from a function.
12.1 Objective:
Learn how to write user defined functions which do not return value (void) OR can return single
value.
12.2 Scope:
The student should know the following:
5. Functions which neither accept any argument nor return any value(void)
6. Functions which accept arguments but do not return any value(void)
7. Functions which accept arguments and return a single result.
12.3 Useful Concepts:
A function is a block of code that performs a task. The statements written in a function are
executed when it is called by its name. The functions provide a structured programming approach.
It is a modular way of writing programs. The whole program logic is divided into a number of smaller
modules or functions. The main function calls these function when they are needed to execute.
NOTE: The program should always have a main function whether it has other function or not.
Without the main function the program will not do anything as the program always starts from the
main function.
The program may need to repeat the same piece of code at various places or it may require
repeating same task again and again. The program may become very large and messy if we do not
divide it into sub programs (functions). The piece of code that is executed repeatedly is stored in a
separate function, and is called when and where it is required.
Functions can be of different types:
Functions can be divided as:
1. User- defined Functions:
2. The function alpha accepts a character type argument and returns no value.
3. The function alpha1 accepts a character type argument and returns a char
value.
Function name char indicates
char indicates character character
return type char alpha1 (char ); parameter
4. The function multiple accepts an integer type argument and returns an integer
value.
Function name int indicates
int indicates integer integer
return type int multiple (int ); parameter
5. The function fact accepts an integer type argument and returns a long value.
6. The function sum accepts two integer type arguments and returns an integer
value.
Function name int indicates
int indicates integer integer
return type int sum (int , int); parameters
Functions Definition:
A set of statements that explains what a function does is called function definition. The
function definition can be written at the following places.
o Before main function
o After main function
Function declaration is not required if the function definition is written before main function.
Function declaration is compulsory if function definition is written after main function. The
function definition consists of two parts:
Functions Header:
The first line of function definition is called function header. It is similar to function
prototype except that it is not terminated with semicolon. The number and sequence of parameter
in function header must be same as that of function prototype.
Functions Body:
The set of statements written inside the function are called function body. The body of the
function appears after function header and the statements are enclosed in curly braces { }.
Syntax:
Return-type Function-Name ( Parameters (optional) )
Function header
Statement 1;
Statement 2; Function body
Statement n;
Functions Call:
12.4 Examples
Example – 1:- Write a program that contains a function which displays a message ―Introduction to
Computer Programming‖.
# include <stdio.h>
# include<conio.h>
void main( )
{
clrscr( );
{
printf(― Introduction to Computer Programming‖);
Output:
4. ―printf‖ command prints the message on the screen (as shown in image above).
5. Control is thrown back to the main ( ) function. Since there are no more statements in main ( )
function the output screen stays until user presses any key from keyboard.
Example – 2:- Write a program that contains a function which takes two numbers from user and
displays their difference.
# include <stdio.h>
# include<conio.h>
void diff ( );
void main( )
{
clrscr ( );
diff();
getch ( );
}
void diff ( )
int x;
Output:
#include <stdio.h>
int main()
{
int x;
int y;
mult(x,y);
getch ();
}
{
printf( "The product of your two numbers is %d\n", x*y);
}
Output:
Example – 4:- Write a program that contains a function which takes two integer types of
arguments and display their quotient.
# include <stdio.h>
# include<conio.h>
void main()
int num1,num2,result;
scanf("%d %d",&num1,&num2);
getch();
printf("===========================\n");
printf("Quotient: \n\n");
Output:
# include <stdio.h>
# include<conio.h>
{
clrscr();
int a,b;
printf("b = %d\n",b);
swap(a,b);
printf("\nValues after swapping\n\n");
printf("a = %d\n",a);
printf("b = %d\n",b);
getch ();
}
int t;
t=x;
x=y;
y=t;
# include <stdio.h>
# include<conio.h>
float calculate_area(int);
void main()
{ clrscr();
int radius;
float area;
scanf("%d",&radius);
area = calculate_area(radius);
getch(); }
float calculate_area(int r)
float areaOfCircle;
areaOfCircle = 3.14 * r * r;
return areaOfCircle;
# include <stdio.h>
# include<conio.h>
void main()
clrscr();
int number1,number2,sum;
scanf("%d", &number2);
add(number1,number2,sum);
printf("\n\n%d + %d = %d", number1, number2, sum);
getche();
}
void add(int x,int y,int &r)
{
r=x+y;
Example – 8:- Write a program that contains a function which takes one integer type of argument
and calculate the factorial of the number.
# include <stdio.h>
# include<conio.h>
long factorial(int);
void main()
{
clrscr();
printf("\n\nFactorial of %d = %d",num,fact);
getch();
}
long factorial(int x)
temp=temp*i;
return temp;
Exercises -2) Write a program that contains a function which takes one integer type of argument,
calculate the factorial of the number and display result in main function without returning any value
from function.
12.6 Home Work
1) Write a program that contains a function which takes one integer type of argument and confirm
that number is prime or not.
2) Solve question one but confirmation about prime number should be in main function. Your
function prototype should be look like this:
Recursion in C
13.1 Objectives:
This lab reviews even more basic C programming with an emphasis on recursive algorithms. You will:
1. Learn basic idea of recursion in C program.
2. Learn how to make a recursive function
3. Use programs to aid your understanding of recursion.
4. To know about importance, working & use of recursive functions.
13.2 Scope:
The student should know the following at the end of this lab:
1. Understand the idea of recursion
2. Trace a recursive function
3. The student should know how to write a recursive function
4. Should be able to convert any program written using loops into a recursive one
Mathematical Definition:
RunningSum(1) = 1
RunningSum(n) =
n + RunningSum(n-1)
Recursive Function:
int RunningSum(int n) {
if (n == 1)
Introduction to Computers and Programming Lab Manual – Page 163|222
return 1;
else
return n + RunningSum(n-1);
}
power(int x, int y)
}
Any problem which we can solve using recursion, we can also solve that problem using iteration.
Generally, a recursive solution is slightly less efficient, in terms of computer time, than an
iterative one because of the overhead for the extra function calls. In many instances, however,
recursion enables us to specify a natural, simple solution to a problem that otherwise would be
difficult to solve. For this reason, recursion is an important and powerful tool in problem solving and
programming. Recursion is used widely in solving problems. That is not numeric, such as proving
mathematical theorems, writing compilers, and in searching and sorting algorithms.
In iterative method we use for, while, do-while for achieving iteration for problem solving. In
recursive method of problem solving we replace for, while, do-while statement by if statement that
selects between the recursive case and the base case (i.e terminating condition).
Mathematical Definition:
Fibonacci: C Code:
int Fibonacci(int n)
{
if ((n == 0) || (n == 1))
return 1;
else
If we are debugging this program, we might want to trace all the calls of Fibonacci.
• Note: A trace will also contain the arguments passed into the function.
Fibonacci(2)
Fibonacci(1)
Fibonacci(0)
Fibonacci(1)
13.4 Examples
Example – 1:- Write a program that takes value from user and Sum all number using recursion in c
#include<stdio.h>
int n,sum;
printf("Enter the value of n: ");
scanf("%d",&n);
sum = getSum(n);
printf("Sum of n numbers: %d",sum);
return 0;
}
int getSum(n){
if(n>0){
sum = sum + n;
getSum(n-1);
return sum;
}
Output:
Example – 2:- Write a program that multiple two Matrixes using recursion in c
#include<stdio.h>
#define MAX 10
int c[MAX][MAX];
int main(){
scanf("%d %d",&o,&p);
if(n!=o){
else{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is: \n");
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<n;j++){
printf("%d\t",a[i][j]);
}
for(i=0;i<o;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",b[i][j]);
Introduction to Computers and Programming Lab Manual – Page 167|222
}
}
multiplyMatrix(a,b);
}
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",c[i][j]);
}
return 0;
if(k<n){
sum=sum+a[i][k]*b[k][j];
k++;
multiplyMatrix(a,b);
c[i][j]=sum;
sum=0;
k=0;
j++;
multiplyMatrix(a,b);
j=0;
i++;
multiplyMatrix(a,b);
Introduction to Computers and Programming Lab Manual – Page 168|222
}
Output:
#include<stdio.h>
int main(){
int a,b,product;
product = multiply(a,b);
}
int multiply(int a,int b){
i++;
}
return product;
}
Output:
#include<stdio.h>
int lcm(int,int);
int main(){
int a,b,l;
l = lcm(a,b);
else
l = lcm(b,a);
printf("LCM of two integers is %d",l);
return 0;
temp++;
lcm(a,b);
return temp;
}
Output:
Example – 5:- Write a program that find largest element in an array using recursion in c.
#include<stdio.h>
int size;
int main(){
int arr[MAX],max,i;
printf("Enter the size of the array: ");
scanf("%d",&size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
max=getMaxElement(arr);
}
int getMaxElement(int arr[]){
static int i=0,max =-9999;
max=arr[i];
i++;
getMaxElement(arr);
return max;
}
Output:
Example – 6:-Write a program that identifies the number is prime or not using recursion in c.
#include<stdio.h>
int main(){
int num,prime;
printf("Enter a positive number: ");
scanf("%d",&num);
prime = isPrime(num,num/2);
return 0;
}
if(num%i==0)
return 0;
else
isPrime(num,i-1);
}
}
Output:
Example – 7:- Write a program that convert decimal to binary using recursion in c.
#include<stdio.h>
using namespace std;
long toBinary(int);
int main(){
long binaryNo;
int decimalNo;
printf("Enter any decimal number: ");
binaryNo = toBinary(decimalNo);
printf("Binary value is: %ld",binaryNo);
return 0;
}
long toBinary(int decimalNo){
remainder = decimalNo % 2;
return binaryNo;
Output:
Void printFibonacci(int);
int main(){
int k,n;
long int i=0,j=1,f;
return 0;
}
if(n>0){
first = second;
second = sum;
printf("%ld ",sum);
printFibonacci(n-1);
}
}
Output:
Example – 9:-Write a program that takes string from user and print it in reverse using recursion in
c.
#include<stdio.h>
char* getReverse(char[]);
int main(){
char str[MAX],*rev;
scanf("%s",str);
rev = getReverse(str);
printf("Reversed string is: %s",rev);
return 0;
}
if(*str){
getReverse(str+1);
rev[i++] = *str;
return rev;
Output:
#include<stdio.h>
using namespace std;
int fact(int);
int main(){
int num,f;
return 1;
else
return(n*fact(n-1));
Output:
Pointers
14.1 Objective:
a. Declaring pointers.
b. Storing addresses of different data type variables.
14.2 Scope:
The student should know the following at the end of this lab:
and can be used to access and manipulate data stored at the address to which it is pointing.
Declaring pointers:
Just like other variables, pointers have to be declared before their usage.
Syntax:
int x=5;
int *p;
p=&x;
Data type of variable and pointer must be same like in this case int x and int *p.
The & or address operator, is a unary operator that returns the address of its operand.
14.4 Examples
Example -1:-// showing pointer application
#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%d\n",pc);
c=11;
printf("Address of pointer pc:%d\n",pc);
printf("Value of c:%d\n\n",c);
return 0;
}
Output:-
#include <stdio.h>
int main()
p = &first;
q = &second;
sum = *p + *q;
return 0;
Introduction to Computers and Programming Lab Manual – Page 181|222
}
Output:-
Example -3:-
#include <stdio.h>
int main()
int num=123;
int *pr2;
int **pr1;
pr2 = #
return 0;
}
Output:-
A program to declare a pointer of 2D array and check its address is even or odd(using
functions).
Strings
15.1 Objective:
Learn how to declare, initialize and use one-dimensional character arrays (string).
15.2 Scope:
The student should know the following:
1. What is string?
2. How to Read and Print Strings.
3. Some important built-in string functions. How to use them?
15.3 Useful Concepts:
What is String?
A string is any sequence of characters enclosed in double quotes. There is no separate data
type for strings as integer, float or double. The string data type can be considered as a char array.
The difference is that a character variable can hold only one character but a string can have more
than one character in a character array. For example, a string called name with 9 characters can be
declared as:
Check for the double quotes, the char array size 9. Here the name can be considered as one string
or as an array of characters. That is if you refer name it is ―I like C‖ and if you refer name[0] it is
‗I‘, name[1] is ‗ ‗ (a blank), name[2] is ‗l‘, name[3] is ‗i‘, and so on. The last character name[8] is ‗\0‘
which indicates a NULL character which is not displayed but is stored as last character of the
string to indicate its end.
Note: Strings are stored as arrays of characters and have a special ‗\0‘ termination character
called NULL appended (attached) to them to signify the end of the string.
Note that if the number of characters including the ‘\0’ is more than the size of the array
the results will be unpredictable. However, if the size of the array is more than the number of
characters the extra spaces after the last ‘\0’ character are kept blank and not referred because
the string ends at ‘\0’. So, always make sure that the size of the array is sufficient for the string.
For example, the above declaration would be wrong if we write
The size can be ignored also. In that case the size is considered as that of the number of
characters specified in the declaration.
and presses the enter key the string variable str has the characters ―Rafiqul Zaman Khan‖ with ‗\0‘
appended at the end but is not displayed.
Similarly, there is an output function puts ( ) which prints or displays the value of the string
variable. Unlike the cout, which stays on the same line after printing puts automatically advances
the output to the next line after displaying it.
puts (str) ;
The strcat function concatenates or joins the string1 and string2. A copy of string2 is put
at the end of the string1. Make sure that string1 size is long enough to hold the resulting string
(string1 + string2).
Example: char string1[ 81] = ―abc‖, string2 [ ] = ―def‖ ;
The strcpy function copies string2 into string1. Again make sure that string1 size is long
enough to hold the resulting string.
The strcmp function compares the string1 to string2 and returns an integer value to show
the status of the comparison. A value of 0 indicates that the two strings are identical. A value of
less than 0 shows that string1 is lexicographically (according to alphabetic ordering) less than
string2. A value of greater than 0 shows that string1 is lexicographically (according to alphabetic
ordering) greater than string2.
See example 6
strlen( string1 ) :
The strlen function returns an integer equal to the length of the stored string including
blanks, not including the termination character.
strchr ( string, ch ) :
The strchr function searches string for the first occurrence of ch. This function only tells
whether the string contains ch or not and it will not tell the position of the ch in the string if found.
15.4 Examples:
Example1:- Write a program that prints a string. String can be printed by using various functions
such as printf, puts.
#include <stdio.h>
int main()
{
char array[20] = "Hello World";
printf("%s\n",array);
return 0;
Introduction to Computers and Programming Lab Manual – Page 187|222
}
#include <stdio.h>
int main()
{
char array[100];
printf("Enter a string\n");
scanf("%s", array);
int main()
{
char a[80];
gets(a);
printf("%s\n", a);
return 0;
}
//Note that scanf can only input single word strings, to receive strings containing spaces use gets
function.
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
gets(s);
l = strlen(s);
return 0;
}
int main()
{
char a[100];
int length;
length = strlen(a);
return 0;
}
Output:-
if (strcmp(a,b) == 0)
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
Output:-
int main()
{
char source[1000], destination[1000];
printf("Input a string\n");
gets(source);
strcpy(destination, source);
Output:-
int main()
{
char a[1000], b[1000];
strcat(a,b);
return 0;
}
Output:
int main()
{
char arr[100];
strrev(arr);
return 0;
}
Output:-
Exercise -2) Write a Program number that reads a string and print upper case and number of lower
case letters.
Exercise -3) Write a program that reads a string and print the string with the first letter
capitalized and the remaining in lower case.
Hints: - Use two arrays of same size. One is used to take value from user and other is used to store
reverse string.
File handling in C
16.1 Objective:
Often it is not enough to just display the data on the screen. This is because if the data is large,
only a limited amount of it can be stored in memory and only a limited amount of it can be displayed
on the screen. It would be inappropriate to store this data in memory for one more reason. Memory
is volatile and its contents would be lost once the program is terminated. So if we need the same
data again it would have to be either entered through the keyboard again or would have to be
regenerated programmatically.
Obviously both these operations would be tedious. At such times it becomes necessary to store the
data in a manner that can be later retrieved and displayed either in part or in whole. This medium is
usually a ‗file‘ on the disk
16.2 Scope:
The student should know the following:
8. To create, read, write and update the files
9. Copy the file, writing into file from consoles etc
There are different operations that can be carried out on a file. These are:
1. Creation of a new file
2. Opening an existing file
3. Reading from a file
4. Writing to a file
5. Moving to a specific location in a file (seeking)
6. Closing a file
Let us now write a program to read a file and display its contents on the screen. We will first list
the program and show what it does, and then dissect it line by line.
File Opening:Modes:
#include<stdio.h>
#include<conio.h>
main( )
{
char ch;
fp = fopen ( "printingHistogram.c", "r" );
while( 1 )
{
ch = fgetc ( fp );
if ( ch = = EOF )
break;
printf ( "%c", ch );
fclose ( fp );
getche();
Output:-
fgetc() function
fgetc( )reads the character from the current pointer position, advances the pointer position so
that it now points to the next character, and returns the character that is read, which we collected
in the variable ch. Note that once the file has been opened, we no longer refer to the file by its
name, but through the file pointer fp.
End of file:-
1. We have used the function fgetc( )within an indefinite while loop.
2. There has to be a way to break out of this while. When shall we break out... the moment we
reach the end of file.
3. But what is end of file? A special character, whose ASCII value is 26, signifies end of file.
4. This character is inserted beyond the last character in the file, when it is created.
5. In our program we go on reading each character from the file till end of file is not met. As
each character is read we display it on the screen. Once out of the loop, we close the file.
#include <stdio.h>
main( )
{
FILE *fp;
fp = fopen ( "PR1.C", "r" );
if ( fp == NULL )
{
exit( );
}
}
Output:
Closing File:
1. When we have finished reading from the file, we need to close it.
2. This is done using the function fclose( )through the statement,
a. fclose ( fp ) ;
3. Once we close the file we can no longer read from it using getc( ) unless we reopen the file.
4. Note that to close the file we don‘t use the filename but the file pointer fp.
5. On closing the file the buffer associated with the file is removed from memory.
6. When we attempt to write characters into this file using fputc( ) the characters would get
written to the buffer.
7. When we close this file using fclose( ) three operations would be performed:
8. The characters in the buffer would be written to the file on the disk.
9. At the end of file a character with ASCII value 26 would get written.
Example -3:- Write a Program to create a file and write some data the file.
#include<stdio.h>
Introduction to Computers and Programming Lab Manual – Page 198|222
#include<conio.h>
#include<string.h>
Void main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
Output:
Example -4:- Write a Program that counts chars, spaces, tabs and new lines in a file.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
main( )
{
FILE *fs, *ft ;
char ch ;
fs = fopen ( "Array1.c", "r" ) ;
if ( fs == NULL )
exit(0) ;
}
ft = fopen ( "array2.c", "w" ) ;
if ( ft == NULL )
}
while ( 1 )
{
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ;
fclose ( fs ) ;
fclose ( ft ) ;
getche();
Output:
It copies the contents of array1.c to array2.c, the file is open below with the contents of array1.c
Example -6:- Write a Program that receives strings from keyboard and writes them to file.
#include<conio.h>
#include<string.h>
main( )
{
FILE *fp ;
char s[80] ;
{
puts ( "Cannot open file" ) ;
exit(0) ;
Introduction to Computers and Programming Lab Manual – Page 203|222
}
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
fclose ( fp ) ;
Output:
Important Points
The key to this program is the function
fprintf(), which writes the values in the
structure variable to the file.
} //end of main
Output:
Graphics in C
17.1 Objective:
To start with graphics programming, Turbo C is a good choice. Even though DOS has its own
limitations, it is having a large number of useful functions and is easy to program.
17.2 Scope:
To implement graphics algorithms,
To give graphical display of statistics,
#include<graphics.h>
#include<conio.h>
void main()
Introduction to Computers and Programming Lab Manual – Page 207|222
{
getch();
closegraph();
}
Output:
Firstly let me tell you what the output of this program is.
1. This program initializes graphics mode and then closes it after a key is pressed.
2. To begin with we have declared two variables of int type gd and gm for graphics driver and
graphics mode respectively.
4. Then we have passed three arguments to initgraph function 1 st is the address of gd, 2 nd is
the address of gm and 3rd is the path where your BGI files are present ( you have to adjust
this accordingly where you turbo compiler is installed).
5. getch helps us to wait until a key is pressed, closegraph function closes the graphics mode
and finally return statement returns a value 0 to main indicating successful execution of
your program
6. After you have understood initgraph function then you can use functions to draw shapes
such as circle, line , rectangle etc, then you can learn how to change colors and fonts using
suitable functions, then you can go for functions such as getimage, putimage etc for doing
animation.
Example -2:- Write a program that prints text in Graphics using Outtestxy function.
#include<graphics.h>
#include<stdio.h>
int main(void)
{
}
Output:
outtextxy(x,y,"Hello World");
Syntax:
outtextxy(x,y,"Hello World");
#include<conio.h>
void main()
{
circle(200,100,150);
getch();
closegraph();
Output:
2. Declaration: void far initgraph(int far *graphdriver, int far *graphmode, char far
*pathtodriver);
3. Remarks: To start the graphics system, you must first call initgraph.
4. initgraph initializes the graphics system by loading a graphics driver from disk (or validating
a registered driver) then putting the system into graphics mode.
5. initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to
their defaults, then resets graphresult to 0.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
closegraph();
Output:
#include<graphics.h>
main() {
int gd=DETECT,gm,maxx,maxy,x,y,button;
line(80,150,200,150);
line(80,150,80,50);
settextstyle(1,HORIZ_DIR,1);
outtextxy(100,153,"<-X axis");
settextstyle(1,VERT_DIR,1);
outtextxy(60,50,"<-Y axis");
bar(100,100,120,150);
bar(130,120,150,150);
getch();
closegraph();
}
Output:
#include<conio.h>
#include<graphics.h>
void main() {
getch();
closegraph();
Output:
Important Functions:
cleardevice();
Delay the program, so that users can see what is happening…sending in the number of msec
delay(milliseconds);
getch();or,kbhit();
3) setcolor(color);
5) setbkcolor(color);
8) setfillstyle(pattern, color)
2. linerel(from_x, from_y,
3. Drawing a Circle
1. Text Formatting
5. settextjustify(horizontal, vertical)
7. Font: (0-11)
BLACK: 0
BLUE: 1
GREEN: 2
CYAN: 3
RED: 4
MAGENTA: 5
BROWN: 6
LIGHTGRAY: 7
DARKGRAY: 8
LIGHTBLUE: 9
LIGHTGREEN: 10
LIGHTCYAN: 11
LIGHTRED: 12
LIGHTMAGENTA:13
YELLOW: 14
WHITE: 15
Introduction to Computers and Programming Lab Manual – Page 215|222
Important Function --- Messages:
1. Text Output
2. Set Text color (index ranges 0-15)
3. setcolor(index);
4. Output a message on the graphics window at the current position
5. outtext(―messages on graphics window‖);
6. Output a message on the graphics window at the given x,y coordinate
7. outtextxy(x,y,‖message‖);
#include <graphics.h>
int main()
circle(x, y, radius);
getch();
closegraph();
return 0;
}
Example -8:- Write a program that implements basic shapes and colours.
#include<graphics.h>
#include<conio.h>
void main()
circle(100,100,50);
outtextxy(75,170, "Circle"); rectangle(200,50,350,150);
line(100,250,540,250);
outtextxy(300,260,"Line");
drawpoly(6, poly);
getch();
closegraph();
}
Output:
Example -9:- Write a program that implements the code of moving car.
#include <graphics.h>
#include <dos.h>
int main()
{
int i, j = 0, gd = DETECT, gm;
initgraph(&gd,&gm,"C:\\TC\\BGI");
settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
getch();
for( i = 0 ; i <= 420 ; i = i + 10, j++ )
{
rectangle(50+i,275,150+i,400);
rectangle(150+i,350,200+i,400);
Introduction to Computers and Programming Lab Manual – Page 218|222
circle(75+i,410,10);
circle(175+i,410,10);
setcolor(j);
delay(100);
if( i == 420 )
break;
if ( j == 15 )
j = 2;
getch();
closegraph();
return 0;
Output:
#include "conio.h"
#include "stdlib.h"
void main()
{
int gd,gm;
gd=DETECT;
setcolor(3);
setfillstyle(SOLID_FILL,RED);
while(!kbhit())
{
putpixel(random(439)+101, random(279)+101,random(16));
setcolor(random(16));
circle(320,240,random(100));
}
getch();
closegraph();
}