Programming Fundamentals: Laboratory Workbook
Programming Fundamentals: Laboratory Workbook
Programming Fundamentals
Name _____________________
Roll No ___________________
Date ______________________
Signature___________________
Lab Details
Lab Marks
Lab Objective Signature CLO
No. Obtained
Mapping
Introduction to C 4
Objective: Getting familiar with the IDE and working with
1 Turbo C & Microsoft Visual Studio.Installing and copying
the compiler, changing directory settings.Making first
program in C.
Student Feedback:
Student Feedback:
Loops 1,2,4
6 Objective:Studying loops. For loops, nested for loops, while
loops, nested while loops, do while loops, nested do while
loops.Studying loops with cross combination.
Student Feedback:
Functions 1,3,4
8 Objective:User defined functions, passing values to function,
and returning values from functions.
Student Feedback:
Arrays 1,3,4
9 Objective:Arrays, array index, single and multi-dimensional
arrays. Arrays and loops. Sorting data in arrays.
Student Feedback:
Structures 1,3,4
10 Objective:Studying Structures, different ways to declare define
and initialize structures.
Student Feedback:
Pointers 1,3,4
11 Objective:Learnhow Pointers access data using memory
address.
Student Feedback:
Graphics 1,3,4
12 Objective:Graphics, basic applications of graphics by making
buttons and animations.
Student Feedback:
Filing 1,3,4
14 Objective:Learn to create, open, write and close text files for
data storage With C language.
Student Feedback:
Note: Students are advised to write their comments about whether the objective of the lab was achieved or
not in Student Feedbacksection.
Course Name (Course Code) Programming Fundamentals Lab (CS104)
Semester II Batch _______
Name of Student: ___________________________________Roll No. ______________
Prerequisites: None
Objectives:
This lab work introduces students to the basics of C language and getting them familiar with the IDE of like
Turbo C & Microsoft Visual Studio. Students will learn about the basic concepts of programming like console
input/output, data types, operators, loops, condition statements, functions, arrays, and structures etc. Students
can learn to code different problem-solving programs in order to solve different problems.
Contents:
Introduction to C , Console Output, Data Types & Variables, Console Input, Operators in C & Math functions,
Loops ,Selection Statements, Functions, Arrays,Structures,Pointers,Graphics,Charts – Graphics, Filing and
Hardware Programming
Learning Outcomes:
Mapping of CLOs and PLOs
Sr. No Course Learning Outcomes Domain Blooms PLO
Taxonomy
1 Implement various programming concepts to Psychomotor 3 3
perform logical and computational tasks.
2 Justify time and resource allocation to complete Affective 3 11
the assigned task
3 Report the outcome of an experiment/task in Affective 2 10
standard format.
4 Demonstrate knowledge about the practical Cognitive 2 1
aspects of Programming Fundamentals Lab
Course
5 Work effectively as an individual or in team to Affective 3 9
solve real world problems.
Grading Policy
Lab Manual 25%
Midterm Exam + Viva 25%
Final Exam + Viva 50%
Recommended Book:
• The C Programming Language, 2nd Edition by Brian W. Kernighan, Dennis M. Ritchie
• Object Oriented Programming in C++ by Robert Lafore
• C How to Program, 7th Edition by Paul Deitel & Harvey Deitel
• Problem Solving and Program Design in C++, 7th Edition by Jeri R. Hanly & Elliot B. Koffman
General Laboratory Procedure
While there is no specific document to be submitted at the beginning of the Lab –unless your instructor advises
you otherwise-, you are expected to read the experiment fully before you come to the laboratory? Interestingly,
you can even try parts of the experiment at home. Here is a list of programs that will equip you with a virtual lab
at your home:
Troubleshooting
Things will not always go as expected; this is the nature of the learning process. While conducting the
Experiment think before you do anything. If you do so you will avoid wasting time going down dead-end
streets. Be logical and systematic. First, look for obvious errors that are easy to fix. Is your measuring device
correctly set and connected? Are you looking at the proper scale? Is the power supply set for the correct voltage?
Is the signal generator correctly set and connected? How are the variables in the code set? Is there a syntax
error? And so on. Next, check for obvious misconnections or broken connections, at least in simple circuits.
As you work through your circuit, use your Lab Manual record tests and changes that you make as you go along;
don't rely on your memory for what you have tried. Identify some test points in the system at which you know
what the signal should be and work your way backwards from the output through the test points until you find a
good signal. Neatness
When you have finished for the day, return all modules to their proper storage bins, return all test leads and
probes to their storage racks, return all equipment to its correct location, and clean up the lab station. If
appropriate switch off the unneeded equipment. Save your files in the Computer and on any USB device for
your records because you might not get the same PC System again for the next experiment. Also email your file
contents to your email address as a backup.
Laboratory Safety
Always pay attention to what you are doing and you’re surrounding during the experiments, notify the Instructor
for any unlikely event or mishap, and leave the Laboratory with the permission of Instructor immediately.
All students must read and understand the information in this document with regard to laboratory safety and
emergency procedures prior to the first laboratory session.
Your personal laboratory safety depends mostly on YOU. Efforts have been made to address situations that
may pose a hazard in the lab but the information and instructions provided cannot be considered allinclusive.
Students must adhere to written and verbal safety instructions throughout the academic term. Since additional
instructions may be given at the beginning of laboratory sessions, it is important that all students arrive at each
session on time. With good judgment, the chance of an accident in this course is very small. Nevertheless,
research and teaching workplaces (labs, shops, etc.) are full of potential hazards that can cause serious injury and
or damage to the equipment. Working alone and unsupervised in laboratories is forbidden if you are working
with hazardous substances or equipment. With prior approval, at least two people should be present so that one
can shut down equipment and call for help in the event of an emergency. Safety training and/or information
should be provided by a faculty member, teaching assistant, lab safety contact, or staff member at the beginning
of a new assignment or when a new hazard is introduced into the workplace.
Emergency Response
1. It is your responsibility to read safety and fire alarm posters and follow the instructions during an
emergency
2. Know the location of the fire extinguisher, eye wash, and safety shower in your lab and know how to
use them.
3. Notify your instructor immediately after any injury, fire or explosion, or spill.
4. Know the building evacuation procedures.
Common Sense
Good common sense is needed for safety in a laboratory. It is expected that each student will work in a
responsible manner and exercise good judgment and common sense. If at any time you are not sure how to
handle a particular situation, ask your Teaching Assistant or Instructor for advice DO NOT TOUCH
ANYTHING WITH WHICH YOU ARE NOT COMPLETELY FAMILIAR!!! It is always better to ask
questions than to risk harm to yourself or damage to the equipment.
Personal and General laboratory safety
1. Never eat, drink, or smoke while working in the laboratory.
2. Read labels carefully.
3. Do not use any equipment unless you are trained and approved as a user by your supervisor.
4. Wear safety glasses or face shields when working with hazardous materials and/or equipment.
5. Wear gloves when using any hazardous or toxic agent.
6. Clothing: When handling dangerous substances, wear gloves, laboratory coats, and safety shield or
glasses. Shorts and sandals should not be worn in the lab at any time. Shoes are required when working
in the machine shops.
7. If you have long hair or loose clothes, make sure it is tied back or confined.
8. Keep the work area clear of all materials except those needed for your work. Coats should be hung in
the hall or placed in a locker. Extra books, purses, etc. should be kept away from equipment that
requires air flow or ventilation to prevent overheating.
9. Disposal - Students are responsible for the proper disposal of used material if any in appropriate
containers.
10. Equipment Failure - If a piece of equipment fails while being used, report it immediately to your lab
assistant or tutor. Never try to fix the problem yourself because you could harm yourself and others.
11. If leaving a lab unattended, turn off all ignition sources and lock the doors.
12. Never pipette anything by mouth.
13. Clean up your work area before leaving.
14. Wash hands before leaving the lab and before eating.
15. Unauthorized person(s) shall not be allowed in a laboratory for any reason Electrical safety
1. Obtain permission before operating any high voltage equipment.
2. Maintain an unobstructed access to all electrical panels.
3. Wiring or other electrical modifications must be referred to the Electronics Shop or the Building
Coordinator.
4. Avoid using extension cords whenever possible. If you must use one, obtain a heavy- duty one that is
electrically grounded, with its own fuse, and install it safely. Extension cords should not go under
doors, across aisles, be hung from the ceiling, or plugged into other extension cords.
5. Never, ever modify, attach or otherwise change any high voltage equipment.
6. Always make sure all capacitors are discharged (using a grounded cable with an insulating handle)
before touching high voltage leads or the "inside" of any equipment even after it has been turned off.
Capacitors can hold charge for many hours after the equipment has been turned off.
7. When you are adjusting any high voltage equipment or a laser which is powered with a high voltage
supply, USE ONLY ONE HAND. Your other hand is best placed in a pocket or behind your back. This
procedure eliminates the possibility of an accident where high voltage current flows up one arm,
through your chest, and down the other arm.
8. Discard damaged cords, cords that become hot, or cords with exposed wiring.
9. Before equipment is energized ensure, (1) circuit connections and layout have been checked by a
Teaching Assistant (TA) and (2) all colleagues in your group give their assent.
10. Know the correct handling, storage and disposal procedures for batteries, cells, capacitors, inductors
and other high energy-storage devices.
11. Experiments left unattended should be isolated from the power supplies. If for a special reason, it must
be left on, a barrier and a warning notice are required.
12. Equipment found to be faulty in any way should be reported to the Lab Engineer immediately and taken
out of service until inspected and declared safe.
13. Voltages above 50 V rms AC and 120 V DC are always dangerous. Extra precautions should be
considered as voltage levels are increased.
14. Never make any changes to circuits or mechanical layout without first isolating the circuit by switching
off and removing connections to power supplies.
15. Know what you must do in an emergency.
16. Emergency Power Off: Every lab is equipped with and Emergency Power Off System.
17. Only authorized personnel are permitted to reset power once the Emergency Power Off system has been
engaged.
Electrical Emergency Response
The following instructions provide guidelines for handling two types of electrical emergencies:
1. When someone suffers serious electrical shock, he or she may be knocked unconscious. If the victim is
still in contact with the electrical current, immediately turn off the electrical power source. If you cannot
disconnect the power source, depress the Emergency Power Off switch.
2. Do not touch a victim that is still in contact with a live power source; you could be electrocuted.
3. Have someone call for emergency medical assistance immediately. Administer first-aid, as appropriate.
4. If an electrical fire occurs, try to disconnect the electrical power source, if possible. If the fire is small
and you are not in immediate danger; and you have been properly trained in fighting fires, use the
correct type of fire extinguisher to extinguish the fire. When in doubt, push in the Emergency Power
Off button.
5. NEVER use water to extinguish an electrical fire. Mechanical safety
1. When using compressed air, use only approved nozzles and never direct the air towards any person.
2. Guards on machinery must be in place during operation.
3. Exercise care when working with or near hydraulically- or pneumatically-driven equipment. Sudden or
unexpected motion can inflict serious injury. Additional Safety Guidelines 1.
Never do unauthorized experiments.
2. Never work alone in laboratory.
3. Keep your lab space clean and organized.
4. Do not leave an on-going experiment unattended.
5. Always inform your instructor if you break a thermometer. Do not clean mercury
yourself!!
6. Never taste anything. Never pipette by mouth; use a bulb.
7. Never use open flames in laboratory unless instructed by TA.
8. Check your glassware for cracks and chips each time you use it. Cracks could cause the glassware to
fail during use and cause serious injury to you or lab mates.
9. Maintain unobstructed access to all exits, fire extinguishers, electrical panels, emergency showers, and
eye washes.
10. Do not use corridors for storage or work areas.
11. Do not store heavy items above table height. Any overhead storage of supplies on top of cabinets
should be limited to lightweight items only. Also, remember that a 36" diameter area around all fire
sprinkler heads must be kept clear at all times.
12. Areas containing lasers, biohazards, radioisotopes, and carcinogens should be posted accordingly.
However, do not post areas unnecessarily and be sure that the labels are removed when the hazards are
no longer present.
13. Be careful when lifting heavy objects. Only shop staff may operate forklifts or cranes.
14. Clean your lab bench and equipment, and lock the door before you leave the laboratory. Clothing
1. Dress properly during a laboratory activity.
2. Long hair, dangling jewelry, and loose or baggy clothing are a hazard in the laboratory.
3. Long hair must be tied back, and dangling jewelry and baggy clothing must be secured.
4. Shoes must completely cover the foot.
5. No sandals allowed on lab days.
6. A lab coat or smock should be worn during laboratory experiments. Accidents and Injuries 1. Do not
panic.
2. Report any accident (spill, breakage, etc.) or injury (cut, burn, etc.)
to the teacher immediately, no matter how trivial it seems.
3. If you or your lab partner is hurt, immediately (and loudly) yell out
the teacher's name to get the teacher's attention.
Theory
IDE
An integrated development environment (IDE) is a software suite that consolidates the basic too ls developers need
to write and test software. Typically, an IDE contains a code editor, a compiler or interpreter and a debugger that the
developer accesses through a single graphical user interface (GUI). An IDE may be a standalone application, or it
may be included as part of one or more existing and compatible applications.
There are different IDE’s to write C program. Following are the two most common;
1. Turbo C
2. Microsoft Visual Studio
1. Turbo C
Turbo C is a discontinued Integrated Development Environment and compiler for the C programming language from
Borland. First introduced in 1987, it was noted for its integrated development environment, small size, fast compile
speed, comprehensive manuals and low price.In May 1990, Borland replaced Turbo C with Turbo C++.
The use of this IDE on latest OS has become very difficult as a lot of libraries are not supported any more. The use of
this IDE is depreciated.
A new window will open. From there right click on the folder named as TC3 and select copy. Now Paste in it in your C
or D partition or your USB drive. As a good approach C drive is normally not recommended for C compiler as C drive is a
windows system partition.
Assuming that the folder has been copied in the root of D drive, open D: p artition - TC3 folder - BIN –
Double click and open any one of the two TC.exe icons (as shown on right).
The window that opens is the known as the IDE of Turbo C (as shown below)
10
This IDE window further contains two more windows and a standard tool bar. The blue window is known as the text editor
which is used to write the programs. And the Light bluish green window at the bottom is the message box which will
display the error or other messages.
Before using the IDE there are few parameters and checks which need to be reviewed every time the IDE of windows is
used. Make sure that the folder of TC3 (also known as compiler) has been copied in the root drive i.e. in the first
window of any partition and not in sub folders. e.g.
Setting Directory Paths (to be checked each time the Turbo IDE is opened)
Once you have opened and saved a new file some directories need to be changed according to the location of your
compiler in your computer otherwise the compiler make not work properly.
On the standard toolbar click on options then directories. Set the first letter of the first two paths (i.e. Include Directories
and Library Directories) according to the location of the compiler or say the letter of the directory where you copied your
compiler. The other two paths (i.e. Output Directories and Source Directories) will remain blank. e.g.
11
2. Microsoft Visual Studio
Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer
programs for Microsoft Windows, as well as web sites, web applications and web services. Visual Studio uses Microsoft
software development platforms.
Visual Studio includes a code editor supporting IntelliSense as well as code refactoring. The integrated debugger works
both as a source-level debugger and a machine-level debugger. Visual Studio supports different programming
languages and allows the code editor and debugger to support nearly any programming language. Built-in languages
include C, C++, VB.NET, C# and F#.
Open Microsoft Visual Studio by double clicking on the Icon. The icon similar to the following (depending upon the version)
should be available on your desktop.
We first have to create a project. To create a new project, click on “New Project” option present on the left side. A
Window similar to the one shown below will appear. Expand the template option present on left side of the window.
Select “Visual C++” and under this, select “General” option. Select first option “Empty Project” from the middle
section. Provide name for the project as “Lab1” and press OK.
12
Figure 1.6: Create new project
After you click OK, following screen will be displayed which has a Solution Explorer on the right hand side. This panel will be used to
access all the files of the project.
Now right click on your project “Lab1, and go to Add and then select New item, refer to the screenshot below.
13
Figure 1.8: Add new item
A window similar to one given below will appear. Select Visual C++ and code from the left panel. Select C++ file from
the middle panel. Give a name to your source file. This will by default create a file with .cpp extension which
represents(C++) but we have to create a C file. Change the extension to .c and click Add.
Your file will appear in solution explorer under folder Source Files.
14
Figure 1.10: File created under Source Files
Now you can simply add a C program and execute the file.
First C Program
#include<stdio.h>
#include<conio.h>
The first line of this program is #include<stdio.h> . Here #include tells the compiler to include something and stdio means
Standard Input/Output where as .h means that it is a header file or in short we are including standard input/output header
file. In the same way the next line is similar to the first one but it has conio.h in it where conio means the black colour
console screen where we see our output and .h tells us that this is a header file. In other words we tell the compiler that
we are including two files and the code we will write will be of c language as the compiler also supports C++ code.
void main(void)
This is third line. The first word in this is void which means any thing that has no value or is useless. The next word is
main which is the brain function and is the only function readable in most programming languages. All the other functions
are called within the main function. The third word within brackets is also void. The first void means that the main function
won’t return any value while the second void means that the main function is not going to accept any value. This complete
line means that we have declared the main function here. For example a simple calculator takes two or more numbers
from you and returns the result like addition, subtraction, multiplication etc. It may be confusing at this time to understan d
the void functionality but in experiment 11 we will discuss it in detail.
{
Following the main function line is a curly bracket which marks the starting of mains body. Always remember that if any
bracket is opened in C language it needs to be closed hence the last line of the above program marks the ending of main
function.
clrscr();
This is the first function called inside the main body. All functions will always have a round bracket closing ‘ )’ and a
semicolon ‘;’ at their end. In that way we easily recognize the number of functions in a program. According to this rule we
can identify 3 functions in this program. However other properties in different functions may differ but this identity will be
common in all functions. clrscr is short form of clear screen. It clears the screen of any previous output. If not used wont
15
create any error but output will show all previous compilation result.
getch();
This is the last function of this program. Its name is short form of get character. Its purpose is to get a character. Its us ed
in last to stop the program until a character is entered. If not used wont show any error but the output will not stop after
compilation. In this case the output is checked manually by pressing Alt+F5 key.
The C program given above will give some compile time errors in Visual Studio. Write following code in the .c file.
#include<conio.h>
#include<stdio.h>
void main()
{
system("cls");
printf("My First Program");
_getch();
}
Save this file (Ctrl + s). Click on the green play icon present on top of the screen to compile and execute your first program.
A black window will appear which is called console. The console will display the output of your program.
Note: There are few functions of old C which is no more available in latest IDEs like clrscr(). Replace clrscr() with
system("cls") and getch() with _getch().
16
Example
Program
Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ My First Program
clrscr();
printf("My First Program");
getch();
}
Exercise
Carefully look at the following programs and write the output.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
printf("My First Program");
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
getch();
printf("My First Program");
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
getch();
printf("My First Program");
getch();
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
getch(); clrscr();
printf("My First Program");
}
17
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
getch();
printf("My First Program");
getch();
}
#include<conio.h> Write the output for the program on left
#include<stdio.h>
void main(void)
{
clrscr();
printf("My First Program");
getch();
}
#include”conio.h” Write the output for the program on left
#include”stdio.h”
void main(void)
{
clrscr();
printf("My First Program");
getch();
}
#include<conio.h> Write the output for the program on left
#include<stdio.h>
main()
{
clrscr();
printf("My First Program");
getch();
}
#include<CONIO.H> Write the output for the program on left
#include<STDIO.H>
void main(void)
{
clrscr();
printf("My First Program");
getch();
}
Assignment
Write a C program using commands described in this lab to make a resume showing your
complete details.
18
Experiment 2 .
Objective
Understanding and Using format specifier and escape sequences with printf.
Theory
The C library functionprintf() sends formatted output to stdout.Following is the declaration for printf() function.
format − This is the string that contains the text to be written to stdout. It can optionally contain embedded format tags that are
replaced by the values specified in subsequent additional arguments and formatted as requested.
Format specifiers are used to substitute and print values inside a printf or scanf statement which are further applicable on
variables. Below is a chart of format specifier examples using printf.
Escape Sequences are used to adjust spacing between lines or characters or the characters themselves.
Example
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{ A
clrscr(); Iqra University
printf("\n%c",'a'); 20
printf("\n%s","Iqra University"); 35.5
printf("\n%d",20); 1234567
printf("\n%f",35.5);
pri ntf("\n%ld", 1234567);
getch();
}
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr(); A Iqra University 2035.5 1234567
printf("\n%c %s %d %f %ld",'a',"Iqra
University",20,35.5,134567);
getch();
}
19
Write the output for following programs and give reasons.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
printf("\n%d",'a');
printf("\n%s","Iqra University");
printf("\n%c",20);
printf("\n%f",35.5);
pri ntf("\n%ld", 1234567);
getch();
}
Assignment
Write a C program to make your resume with format specifiers and escape sequences showing your complete
details.
Write a program using escape sequence to produce following output.
20
Experiment 3 .
Objective
Studying different data types, variables, variable names, variable declaration, variable definitionand variable initialization.
Theory
Variables are declared by first writing
data types followed by a variable name, e.g.
int a=10;
Here
Supported Example
No. Data Type Syntax format Specifier Value
1 Single Character char %c One character within single quotes char a=’a’;
2 Decimal Integer int %d Any whole number between -32,768 to 32,767 int a=10;
3 Long Integer long int %ld Any number between -2,147,483,648 to 2,147,483,647 long int a=12345;
4 Float float %f Any decimal point number between 10-38 to 1038 float a=1234.567;
5 Double double %lf Any decimal point number between 1 0-308 to 10308 double a=1 23456;
Variable Names
Variable names will always start with an alphabet.
Variable names can contain numbers (1,2,45,66) and underscores (_) but no other special characters (!@#$%^&*).
Variable names cannot resemble to any predefined word e.g. include, printf, getch, scanf etc..
A variable name cannot be used for multiple declarations.
Example
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
char a='a';
a 12 12.5 1234567
int b=12;
float c=12.5;
double d=1234567;
printf("%c %d %f %lf",a,b,c,d);
getch();
}
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
char a='a',a1=’b’;
int b=12,b1=13; b 13 13.5 1234568
float c=12.5,c1=13.5;
double d=1234567,d1=1234568;
printf("\n%c %d %f %lf",a,b,c,d);
printf("\n%c %d %f %lf",a1 ,b1 ,c1,d1);
getch();
}
21
Write the output for following programs.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
char a=97;
int b=’A’;
float c=12.5;
double d=1234567;
printf("%c %d %f %lf",a,b,c,d);
getch();
}
Assignment
Write a C program to declare multiple variable that shows an employee details such as Name, age, phone no,
salary address and designation. The program should print details of employee.
22
Experiment 4 .
Objective
Taking Input from the user at console screen using scanf and getche commands.
Theory
Scanf command can take input of different data types at a time.
Getche command can take only one character input.
Example
Write the output after supplying appropriate input on console screen.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
char a;
int b;
float c;
double d;
printf("\nEnter character ");
scanf("%c",&a);
printf("\nEnter integer ");
scanf("%d",&b);
printf("\nEnter float ");
scanf("%f",&c);
printf("\nEnter double ");
scanf("%lf",&d);
printf("\n%c %d %f %lf",a,b,c,d);
getch();
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
char a;
int b;
float c;
double d;
printf("Enter char integer float double\n");
scanf("%c %d %f %lf",&a,&b,&c,&d);
printf("\n%c %d %f %ld",a,b,c,d);
getch();
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
pri ntf("\nWhat is your section : ");
getche();
getch();
}
Assignment
Write a C program that takes input from the user and then displays the complete details such as his name, course,
university, program and location.
Write a C program that takes two numbers as input and swap their values .
23
Experiment 5 .
Objective
Arithmetic operators, conditional operators, assignment operators, Increment/decrement operators.Studying Math
functions.
Theory
Math.h header file is included for the definitions of math functions listed below. It is written as #include<math.h>.
Example
The program below shows the result for math and trigonometric functions. The functions pass the values to variables
which are further used for printing in printf.
Program Output
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
clrscr();
float a=45,b=1,sn,cs,tn,snh,csh,tnh;
sn=sin(a);
cs=cos(a); Trignometric Functions
tn=tan(a); sin 45 = 0.85
cos 45 = 0.53
snh=sinh(b); tan 45 = 1.62
csh=cosh(b);
tnh=tanh(b);
Hyperbolic Functions
printf("\n\n\n Trignometric Functions"); sinh 1 = 1.18
printf("\nsin 45 = %.2f",sn); cosh 1 = 1.54
printf("\ncos 45 = %.2f",cs); tanh 1 = 0.76
printf("\ntan 45 = %.2f",tn);
printf("\n\n\n Hyperbolic Functions");
printf("\nsinh 1 = %.2f",snh);
printf("\ncosh 1 = %.2f",csh);
printf("\ntanh 1 = %.2f",tnh);
getch();
}
24
The program below shows the result for math and trigonometric functions. It also demonstrates that some functions may
be called within the body of another function. For example here all the trigonometric functions are called inside printf
function.
Program Output
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void) Trignometric Functions
{ sin 45 = 0.85
clrscr(); cos 45 = 0.53
printf("\n\n\n Trignometric Functions"); tan 45 = 1.62
printf("\nsin 45 = %.2f",sin(45));
printf("\ncos 45 = %.2f",cos(45)); Hyperbolic Functions
printf("\ntan 45 = %.2f",tan(45)); sinh 1 =1.18
cosh 1 = 1.54
printf("\n\n\n Hyperbolic Functions"); tanh 1 = 0.76
printf("\nsinh 1 = %.2f",sinh(1));
printf("\ncosh 1 = %.2f",cosh(1));
printf("\ntanh 1 = %.2f",tanh(1)); Math Functions
pow 2,3 = 8.00
printf("\n\n\n Math Functions"); sqrt 49 = 7.00
printf("\npow 2,3 = %.2f",pow(2,3));
printf("\nsqrt 49 = %.2f",sqrt(49));
getch();
}
Operators
25
Example
Explain the following program after careful study.
Program Output
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a=2,b=4,c1,c2,c3,c4,d1,d2,d3,d4; 6 -28 0
c1=c2=c3=c4=5; 0 10 1 0 1
d1=d2=d3=d4=8; 8 215 1
printf("\n%d %d %d %d",a+b,a-b,a*b,a/b); 8 98 7
printf("\n%d %d %d %d %d %d",a>b,a<b,a>=b,a<=b,a==b,a!=b);
printf("\n%d %d %d %d",c1+=3,c2-=3,c3*=3,c4/3);
printf("\n%d %d %d %d",d1++,++d2,d3--,--d4);
getch();
}
Exercise
Write output for following programs and give reasons.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
main()
{
clrscr(); int a=5;
printf("\n%d %d",a++,a);
printf("\n%d ",a);
getch();
}
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
main()
{
clrscr(); int a=5;
printf("\n%d %d",- -a,a);
printf("\n%d ",a);
getch();
}
26
#include<stdio.h> Write the output for the program on left
#include<conio.h>
main()
{
clrscr(); int a=5; printf("\n%d %d
%dd",a+5,++a,a);
printf("\n%d ",a);
getch();
}
Assignment
27
Experiment 6 .
Objective
Studying loops. For loops, nested for loops, while loops, nested while loops, do while loops, nested do while loops. Studying
loops with cross combination.
Theory
for while do while
initialization; initialization;
do
for(initialization ; check range ; iteration) while(check range)
{
{ {
body
body body
iteration;
} iteration;
} while(check range)
}
Example: This table below shows nested loops. All the three programs have same output.
Loop Nested
Program Output Program Output
Loop
#include<stdio.h>
#include<conio.h>
void main(void)
#include<stdio.h> {
#i nclude<conio. clrscr();
h>void main(void) for(int a=0;a<=3;a++)
{ {
For for(int b=0;b<=3;b++)
For clrscr();
for(int a=0;a<=12;a++) {
printf("%d x 2 = %d\n",a,a*2); printf("%d%d\t",a,b);
getch(); }
} printf("\n");
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main(void)
#include<stdio.h> {
#incl ude<conio. h> clrscr();
void main(void) 0x2=0 int a=0,b;
{ 1x2=2 while(a<=3)
clrscr(); 2x2=4 {
int a=0; 3x2=6 b=0;
While while(a<=12) 4x2=8 While while(b<=3) 00 01 02 03
{ 5 x 2 = 10 { 10 11 12 13
printf("%d x 2 = %d\n",a,a*2); 6 x 2 = 12 printf("%d%d\t",a,b); 20 21 22 23
a++; 7 x 2 = 14 b++; 30 31 32 33
} 8 x 2 = 16 }
getch(); 9 x 2 = 18 printf("\n");
} 10 x 2 = 20 a++;
11 x 2 = 22 }
12 x 2 = 24 getch();
}
#include<stdio.h>
#include<conio.h>
void main(void)
#include<stdio.h>
#i nclude<conio. {
h>void main(void) clrscr();
int a=0,b;
{
do
clrscr();
{
int a=0;
do b=0;
Do while Do while do
{
printf("%d x 2 = %d\n",a,a*2); {
a++; printf("%d%d\t",a,b);
b++;
}
}while(b<=3);
while(a<=12);
printf("\n");
getch(); a++;
} }while(a<=3);
getch();
}
28
This program of while loops takes continuous input until enter key is pressed.
Program Output
#include<stdio.h>
#include<conio.h>void main(void)
{ clrscr();
Type any sentence
int a=0; Iqra University
printf("Type any sentence\n"); Total Characters typed = 15
while(getche()!='\r')
a++;
printf("\nTotal Characters typed = %d",a); getch();
Exercise
Carefully observer the following program and write output with reasons.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
for(int a=0;a<=12;a++);
printf("%d x 2 = %d\n",a,a*2);
getch(); }
29
Program:
Following program gives the sum of all numbers input by the user using while loop. The program will display the
sum when user enters 0 as input.
#include<conio.h>
#include<stdio.h>
void main()
{
system("cls"); // clear screen clrscr();
int num=-1;
int sum=0;
Understand the difference between break and continue by executing following programs.
break continue
int main() int main()
{ {
int i; int i;
double number, sum = 0.0; double number, sum = 0.0;
sum += number; // sum = sum + number; sum += number; // sum = sum + number;
} }
return 0; return 0;
} }
do-while
for while while for for do-while do-while for while do-while
while
for( ) while( ) for( ) do while( ) do
{ { { { { {
while( ) for( ) d for( ) do while( )
} } o }while( ) while( ) }while( )
while( ) }
}
30
Example
{
clrscr();
int a=0,b;
while(a<=3)
{
While For for(b=0;b<=3;b++)
{
printf("%d%d\t",a,b);
}
printf("\n");
a++;
}
getch();
}
Assignment
1. Input any number from user and generate its factorial e.g. factorial of 7 is 5040.
2. Write a program using loops to generate following pattern.
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654320
31
4. Write a program using loops to generate following output.
12 x 2 = 24
11 x 2 = 22
10 x 2 = 20
9 x 2 = 18
8 x 2 = 16
7 x 2 = 14
6 x 2 = 12
5 x 2 = 10
4 x 2 = 8
3 x 2 = 6
2 x 2 = 4
1 x 2 = 2
5. The Fibonacci sequence is a series where the next term is the sum of pervious two terms. Write a C program to
generate this sequence.
32
Experiment 7 .
Objective
Decision making and conditioning using If statements, If-else statements, switch-case.
Theory
If Nested If If-else Else-if Switch-case
if(cond) if(cond) if(cond) if(cond) switch(cond)
{ { { { {
Body If(cond) body body case’1‘:
} { } } body
body else else case’2‘:
} { If(cond) body
} Body { }
} Body
}
Example
This program illustrates simple if and nested if statements with else conditions.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
char ch;
int chr=0,wrd=1;
printf("Type any sentence\n");
while((ch=getche())!='\r') Type any sentence
{ Iqra Univ Khi Sindh Pak
chr++; Total Characters = 19
' '
if(ch==) Total Words = 5
{
wrd++;
chr--;
}
}
printf("\nTotal Characters = %d",chr);
printf("\nTotal Words = %d",wrd);
getch();
}
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
int cp=0;
printf("Enter CP marks between 1 & 100\n");
scanf("%d",&cp);
if(cp>=0 && cp<=100)
{
if(cp>=75)
printf("\nGrade A");
else
if(cp>=50)
printf("\nGrade C");
}
else
printf("\nIncorrect Input");
getch();
}
33
This program lets the user choose a number between 1 and 99 and guesses it in less than 10 hints.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
float gss,incr;
char ch;
printf("Think of a number Between 1 & 99\n");
printf("Press `g` for grateñn"); Think of a number between 1 and 99
printf("Press `l` for less\n"); Press `g` for greater
printf("Enter for exit\n"); Press `l` for less
Enter for exit
incr=gss=50;
Is your number greater, less or equal to 50
while(incr>1 .0)
{
printf("\nIs your number greater, less or equal to %.0f\n",gss); Is your number greater, less or equal to 75
incr/=2; Is your number greater, less or equal to 88
if((ch=getch())=='e')
break; You guessed 88
else if(ch=='g')
gss+=incr;
else
gss-=incr;
}
printf("You guessed %.0f",gss);
getch();
}
This program prompts the user to type his/her name. If any thing other than Upper/lower case alphabets or a space is
entered for example 1 ,2,@#$% then it is detected and nothing is printed until a correct character is input.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr(); char ch;
printf("Name : ");
while((ch=getche())!='\r')
{
if( (ch>=65 && ch<=90) || (ch>=97 && ch<=122) || ch==' ' );
else
printf("\b \b");
}
getch();
This is a simple calculator program that adds or subtracts two numbers entered by the user.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
float nm1 =1 .0,nm2=1 .0;
char op;
Assignment
Detect error for out ranged numbers e.g. below 0 or above 100.
35
2. Program the following.
Ask User to select one option from the following.
Calculate area of Circle [c]
Calculate area of Rectangle [r]
Calculate area of Triangle [t]
If user enters c then ask user to enter radius and calculate area using following formula.
If user enters r then ask user to enter length & width and calculate area using following formula.
If user enters t then ask user to enter base & height and area using following formula.
36
Experiment 8 .
Objective
User defined functions, passing values to function, and returning values from functions.
Theory
Functions give user a facility to make functions according to their own needs.
Example
This program has a simple function with no return type or arguments passing and prints a sentence.
Program Output
#include<stdio.h>
#include<conio.h>
void iqra(void);
void main(void)
{
clrscr();
Iqra University
iqra();
getch();
}
void iqra(void)
{
printf("\nIqra University");
}
This program has a function with no return type but two arguments passed as integers and printed with their sum.
Program Output
#include<stdio.h>
#include<conio.h>
void add1(int,int);
void main(void)
{
clrscr();
add1(2,4); 2 + 4 =6
getch();
}
This program has a function with integer return type and two arguments passed as integers.
Program Output
#include<stdio.h>
#include<conio.h>
int add1(int,int);
void main(void)
{
int a,b,c1;
a=2;
b=4;
clrscr(); 2 + 4 =6
c1=add1(2,4);
printf("\n%d + %d = %d",a,b,c1);
getch();
}
37
Assignment
38
Experiment 9 .
Objective
Arrays, array index, single and multi-dimensional arrays.Arrays and loops.Sorting data in arrays.
Theory
a
Arrays are variables that can hold multiple 0 9
values at one time. They have a specified
1 4
length and have addresses known Values
Stdlib.h is used for rand function which generates random numbers within a given range.
Example
Below are three tables showing one dimensional character, integer and float arrays. Each table shows three different
methods of declaring and initializing an array.
39
The picture below shows how a two dimensional array may look like.
0 1 2 3
0 0 5 10 15
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19
Table below shows three different methods of declaring and initializing a two dimensional integer array.
This program shows a three dimensional integer array namely aaa, of such length that has 4 two dimensional arrays and
each two dimensional array has 3 rows and 2 columns initialized in one of the several ways shown above for integer
arrays this function prints the element on address 2,1,0.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
int aaa[4][3][2]={
{{1,2},{3,4},{5,6}},
{{7,8},{9,10},{1 1,12}},
{{1 3,14},{1 5,16},{1 7,1 8}},
{{19,20},{21,22},{23,24}},
};
printf("%d",aaa[2][1][0]);
getch();
}
ALGORITHMS
Arrays have many properties applicable on them. Three such properties are.
- Searching an array,
- Entering data in an array,
- Sorting an array.
Hence we apply these on array using algorithms which may be categorized as follows.
40
- Searching
- By address or location
- By Value
- Input
- FIFO (First in First out)
- FILO or LIFO
- Sorting
- Ascending / Descending
Exercise
This program prompts the user for a number from the given data searches and returns its location.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
int a[5]={8,6,3,7,2},vl,a1,a2=0;
for(a1=0;a1<=4; a1 ++)
printf("%d ",a[a1]);
printf("\nFrom the above enter one value to search : ");
scanf("%d",&vl);
while(a[a2]!=vl)
{
a2++;
}
printf("Location of %d is %d",vl,a2+1);
getch();
}
This program accepts data from the user in a stack or First In Last Out (FILO) method such that every time the user
enters a number it is stored at zero location and all the other numbers are shifted to next positions.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
int aa,arr[5]={0,0,0,0,0};
for(int
a1=0;a1<5;a1++) {
for(int a2=5;a2>=0;a2--
){
arr[a2]=arr[a2-1];
}
printf("Enter Value for FILO\n");
scanf("%d",&arr[0]);
for(int a3=0;a3<5;a3++)
printf("\n%d",arr[a3]);
getch();
clrscr();
}
for(int d=0;d<5;d++)
printf("\n%d",arr[d]);
getch();
}
41
This program sorts the numbers in side the array in ascending order.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
void main(void)
{
clrscr();
int tmp,arr[5]={23,16,97,33,42};
for(int a=0;a<5;a++)
{
for(int b=0;b<4;b++)
{
if(arr[b]>arr[b+1])
{
tmp=arr[b];
arr[b]=arr[b+1];
arr[b+1]=tmp;
}
}
}
for(int c=0;c<5;c++)
printf("\n%d",arr[c]);
getch();
}
This program randomly generates 10 values between 1 and 100 to be placed in integer array.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
#include<stdlib.h>
void main(void)
{
clrscr();
int a[10],b;
for(b=0;b<1 0;b++)
{
printf("\n%d",a[b]=(rand()%1 00+1));
}
getch();
}
Assignment
33,4,55,42,66,22,77,21,33,34,66,88,73,2,71,23
42
Experiment 10 .
Objective
Studying Structures, different ways to declare define and initialize structures.
Theory
Structures are variables which can accept values of different data types (e.g. char, int, float, etc.) or as defined by the
user.
Example
The structure iqra of this program has been defined and declared at a time. While its initialized in another statement.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
struct iqra
{
char chr;
int nmb;
}iq1,iq2; iq1.chr = a iq1.nmb = 1
iq1.chr='a'; iq1.chr = b iq1.nmb = 2
iq1.nmb=1;
iq2.chr='b';
iq2.nmb=2;
The structure of this program has been defined, declared and initialized in three different steps.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
struct iqra
{
char chr;
int nmb;
};
struct iqra iq1; iq1 .chr = a iq1 .nmb = 1
struct iqra iq2; iq1 .chr = b iq1 .nmb = 2
iq1 .chr='a';
iq1.nmb=1;
iq2.chr='b';
iq2.nmb=2;
43
The structure in this program has first been defined. But declared and initialized in another statement together.
Program Output
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
struct iqra
{
char chr;
int nmb; iq1.chr = a iq1.nmb = 1
}; iq1.chr = b iq1.nmb = 2
getch();
}
Assignment
44
Experiment 11 .
Objective
Learn how Pointers access data using memory address.
Theory
Every variable is a memory location and every memory location has its address defined which can be accessed using
ampersand (&) operator, which denotes an address in memory.
A pointer is a variable whose value is the address of another variable, i.e., direct add ress of the memory location. Like
any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a
pointer variable declaration is
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointervariable.
The asterisk * used to declare a pointer. In this statement the asterisk is being used to designate a variable as a
pointer.
Exercise:
Program Output
#include <stdio.h>
Address of var variable: bffd8b3c
int main () { Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
int var = 20; /* actual variable declaration
*/
int *ip; /* pointer variable declaration
*/
return 0;
}
45
Assignment
Program Output
#include<stdio.h>
int main()
{
static char *s[] = {"black",
"white", "pink", "violet"};
char **ptr[] = {s+3, s+2, s+1, s},
***p;
p = ptr;
++p;
printf("%s", **p+1);
return 0;
}
include<stdio.h>
int main()
{
int i=3, *j, k;
j = &i;
printf("%d\n", i**j*i+*j);
return 0;
}
#include<stdio.h>
int main()
{
char str[20] = "Hello";
char *const p=str;
*p='M';
printf("%s\n", str);
return 0;
}
46
Experiment 12 .
Objective
Graphics, basic applications of graphics by making buttons and animations.
Theory
Graphics.h header file is used for graphics function, dos.h is is used for delay function and math.h is used for
trigonometric functions. Below are some of the graphics functions that may be used in this course.
For the table below xc, yc, x1, y1, n atc all represent constant values.
ellipse(xc,yc,start,end,xrad,yrad); setlinestyle(n);
rectangle(x1 ,y1 ,x2,y2); setfillstyle(n);
line(x1 ,y1 ,x2,y2); floodfill(n);
circle(xc,yc, rad); setfillpattern(n);
arc(xc,yc,start,end, rad); setfillstyle(n);
bar(x1,y1,x2,y2); settextstyle(n);
bar3d(x1 ,y1 ,x2,y2,z1 ,z2); settextjustify(n);
putpixel(x,y,color); textheight(n);
outtextxy(x,y,"Text"); textwidth(n);
setcolor(n); setusercharsize(n);
setbkcolor(n);
Example
This program has a graphical button which is animated to be pressed when ever any keyboard button is pressed.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void btn1 (void);
void main(void)
{
clrscr();
int driver,mode;
driver=EGA;
mode=EGAHI;
initgraph(&driver,&mode,"c:\\tc3\\bgi");
btn1();
getch();
}
void btn1 (void)
{
int x1=250,y1=1 25,x2=275,y2=1 50,dly=75;
rectangle(x1 ,y1 ,x2,y2);
line(x2+2,y1 ,x2+2,y2+2); ///Vertical
line(x1 ,y2+2,x2+2,y2+2); ///Horizontal
while(getche()!='\r')
{
setcolor(0); ///Black
line(x2+2,y1,x2+2,y2+2); ///Vertical
line(x1 ,y2+2,x2+2,y2+2); ///Horizontal
delay(dly);
setcolor(15); ///White
line(x1+2,y1+2,x1+2,y2); ///Vertical
line(x1+2,y1+2,x2-1,y1+2); ///Horizontal
delay(dly);
setcolor(0); ///Black
line(x1+2,y1+2,x1+2,y2-1); ///Vertical
line(x1+2,y1+2,x2-1,y1+2); ///Horizontal
setcolor(15); ///White
line(x2+2,y1,x2+2,y2+2); ///Vertical
line(x1 ,y2+2,x2+2,y2+2); ///Horizontal
}
}
47
This program shows an animated circle which rotates in a circular path.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<math.h>
void main(void)
{
clrscr();
int driver,mode;
driver=EGA;
mode=EGAHI;
initgraph(&driver,&mode,"c:\\tc3\\bgi");
setcolor(15);
int r=50;
float pi=22/7,d;
while(!kbhit())
{
setcolor(15);
cleardevice();
d=(pi/(90*3))*r;
circle(250+1 30*sin(d),150-100*cos(d),1 0);
delay(4);
r++;
}
getch();
closegraph();
}
Assignment
1. Graphically program the following.
Design simple calculator with buttons such that it resembles an actual calculator.
Make any presentation with animation to any selected topic (e.g. solar system, trigonometric waveform).
48
Experiment 13 .
Objective
Draw different charts using C graphics.
Theory
Different functions including line, setfillstyle and bar of graphics.h header file can be used to draw horizontal and vertical
axis and bars on screen.
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "X:\\TC\\BGI");
settextstyle(BOLD_FONT,HORIZ_DIR,2);
outtextxy(275,0,"BAR GRAPH");
setlinestyle(SOLID_LINE,0,2);
/* Draw X and Y Axis */
line(90,410,90,50);
line(90,410,590,410);
line(85,60,90,50);
line(95,60,90,50);
line(585,405,590,410);
line(585,415,590,410);
outtextxy(65,60,"Y");
outtextxy(570,420,"X");
outtextxy(70,415,"O");
/* Draw bars on screen */ Figure 3: Output - Bar Chart
setfillstyle(XHATCH_FILL, RED);
bar(150,80,200,410);
bar(225,100,275,410);
bar(300,120,350,410);
bar(375,170,425,410);
bar(450,135,500,410);
getch();
closegraph();
return 0;
}
49
Assignment:
1. Following C program will draw pie chart using graphics. Write the program given below and draw the pie chart
that displays on the screen on the Output column.
Program Output
#include<graphics.h>
#include<conio.h>
int main() {
int gd = DETECT, gm, x, y;
initgraph(&gd, &gm, "C:\\TC\\BGI");
settextstyle(BOLD_FONT,HORIZ_DIR,2);
outtextxy(220,10,"PIE CHART");
/* Setting cordinate of center of circle
*/
x = getmaxx()/2;
y = getmaxy()/2;
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,1);
setfillstyle(SOLID_FILL, RED);
pieslice(x, y, 0, 60, 120);
outtextxy(x + 140, y - 70, "FOOD");
setfillstyle(SOLID_FILL, YELLOW);
pieslice(x, y, 60, 160, 120);
outtextxy(x - 30, y - 170, "RENT");
setfillstyle(SOLID_FILL, GREEN);
pieslice(x, y, 160, 220, 120);
outtextxy(x - 250, y, "ELECTRICITY");
setfillstyle(SOLID_FILL, BROWN);
pieslice(x, y, 220, 360, 120);
outtextxy(x, y + 150, "SAVINGS");
getch();
closegraph();
return 0;
}
2. Write a program in C to make a digital clock using graphics.h header file. Use delay(1000) to add delay of 1
second. The program should display following output.
50
Experiment 14 .
Objective
Learn to create, open, write and close text files for data storage with C language.
Theory
Opening Files
fopen( ) function can be used to create a new file or to open an existing file.
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following
values –
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing. If it does not exist, then a new file is created. Here your
program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode. If it does not exist, then a new file is
created. Here your program will start appending content in the existing file content.
r+ Opens a text file for both reading and writing.
w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it
exists, otherwise creates a file if it does not exist.
a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The
reading will start from the beginning but writing can only be appended.
Closing a File
To close a file, use the fclose( ) function. The
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file
Writing a File
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success,
otherwise EOF is returned in case of any error.
int fputs( const char *s, FILE *fp );
fprintf(FILE *fp,const char *format, ...) function can also be used to write a string into a file.
Following code creates a new file test.txt in /tmp directory and writes two lines using two different functions.
.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
Reading a File
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the
buffer buf, appending a null character to terminate the string.
char *fgets( char *buf, int n, FILE *fp );
fscanf(FILE *fp, const char *format, ...) function can also be used to read strings from a file, but it stops reading after
encountering the first space character.
51
Exercise
Write output of the following program.
Program Output
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
Assignment:
1. Write to a text file using fprintf(). Take number input from user and stores in the file program.txt.
2. Read from a text file using fscanf(). Read the integer present in the program.txt file and prints it onto the
screen.
52
Experiment 15 .
Objective
Understanding registers and accesses the hardware using C language. Learn the basics of Inline Assembly.
Theory
Register
A processor register (CPU register) is one of a small set of data holding places that are part of the computer processor. A
register must be large enough to hold an instruction.
A register may hold an instruction, a storage address, or any kind of data (such as a bit sequence or individual
characters). Some instructions specify registers as part of the instruction. For example, an instruction may specify that the
contents of two defined registers be added together and then placed in a specified register.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main(void)
{
clrscr();
union REGS regs;
regs.h.ah = 1;
regs.h.dl = 0x80;
int86(0x13,�s,�s);
printf("
If successful operation then AH & AL register resets.");
printf("
AH register - %d",regs.h.ah);
printf("
AL register - %d",regs.h.al);
printf("
Successful Operation.");
getch();
}
Inline Assembly
Generally the inline term is used to instruct the compiler to insert the code of a function into the code of its caller at the point
where the actual call is made. Such functions are called "inline functions". The benefit of inlining is that it reduces function-
call overhead. Inline Assembly is just a set of assembly instructions written as inline functions. Inline assembly is used for
speed up.
We can use either of the following formats for basic inline assembly.
asm("assembly code");
or
__asm__ ("assembly code");
Please refer to the example below. Compile it using "-g" option of GNU C compiler "gcc" to keep debugging information
with the executable and then using GNU Debugger "gdb" to inspect the contents of CPU registers.
53
Program
#include <stdio.h>
int main() {
/* Add 10 and 20 and store result into register %eax */
__asm__ ( "movl $10, %eax;"
"movl $20, %ebx;"
"addl %ebx, %eax;"
);
return 0 ;
}
54