C Lab Material
C Lab Material
Appendix A
Laboratory Exercises/Lab Manual/Lab Sheets
The laboratory post report of all exercises must contain the following topics.
Section SNo Content Remark
A Background Theory Write once for one laboratory exercise.
B a. 1Question
b. 2Algorithm
c. 3Flowchart
d. 4Pseudo code Write For each question of each laboratory
e. 5Source code exercise. (or follow instructions of your
f. 6Output honorable lecturer)
g. 7Discussion of the result with
respect to source code in
detail.
C Conclusion Write once for one laboratory exercise.
Note: Section A and B (1, 2, 3, 4) are the mandatory part of pre-report.
3. Type the following program and run and see the output.
#include<conio.h>
#include<stdio.h>
void main()
{
int s, a, b; /* variable declaration */
float p;
printf(“Address of a is %x”, &s); /* to know the memory address of variable s */
printf(“\n Address of b is %x”, &a);
printf(“\n\n Memory space s %d”, sizeof(s)); /* sizeof is an operator. It returns the size
occupied by any variable or data */
printf(“\n\n\n Size of a %d”, sizeof(p));
printf(“\n\n\n\n Size of 1.5 is %d”, sizeof(1.5));
printf(“\n\n\n\n\n Size of float data type is %d”, sizeof(float));
getch(); /* to make program wait until user enters any character */
}
Activity: right click on int, float, sizeof, getch, void, main, include, stdio.h, conio.h and study more
about the term. What does \n do? Replace \n with \t and see the output. Similarly use \a and run.
Background theory: Algorithm, flowchart, pseudo code, data types in C (with size and
range) operators , types of operator with precedence and associativity, expressions, integer,
real and mixed mode arithmetic, difference between type casting and type promotion,
overflow and underflow error, division by zero errors.
4.Type, compile, run and observe the output of the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
Er. Krishna Kandel
Learning C by Examples 372
int x,y,z;
clrscr();
x=30000,y=20000;
z=x+y;
printf(“Sum=%d”, z);
getch();
}
Note: Run this program with values of x= -30000 and y=-20000.
5.Type, run and observe the output.
#include<stdio.h>
#include<conio.h>
void main()
{
float a; char b; long int c; unsigned int e;
clrscr();
printf("Enter value of a");
scanf("%f",&a);
printf("Enter value of b:");
scanf(" %c",&b);
printf("Enter value of c and e");
scanf("%ld%u",&c,&e);
printf("value of a:%f\nvalue of b:%c\nvalue of c:%ld\nvalue of e:%u",a,b,c,e);
getch();
}
Write a program:
6.to convert the given Centigrade measure to Fahrenheit using relation F=1.8C+32.
7.to compute equivalent resistance of two resistors R1 and R2 when they are connected in
series and parallel connection.
8.to read two end points of a line, compute their mid point and display it.
9.to read the number of girls and boys in your class and display the ratio of girls to boys.
10.Write programs to evaluate the following expression:
a. S=x5+0.2xy+y7
b. f=(a+b)(2x+y)/(p-q)+ c-100
c. r=A/B [where A and B are integers]
d. r=(u/x+v/y)5/(p2/3u2.5-q/2v)3.5
11.Write a program to swap values of two variables, say a and b. [Hint: t=a;a=b;b=t ]
Background theory: character I/O, string I/O, format specification (flag, width specifier,
precision specifier, conversion characters), Formatted I/O, Limitation of scanf(), search set
Background theory: simple if, nested if, if…else, nested if…else, if…else if…else,
switch structures.
1. If a person’s age is greater than 65, he gets the seniority allowance. Write a program to read
the age of a person and display the appropriate message.
2. Write a program to read an integer form the user and check whether it is positive, zero or
negative.
3. Write a program to read three sides of a triangle from the user and calculate the area of the
triangle. Be sure to check the condition of the triangle if sides are given.
4. Write a program to read a character and check whether the character is uppercase and
lowercase.
5. Write a program to read an unsigned integer and check whether the number is odd or even.
If it is even, check whether it is greater than 100 or not and display appropriate message. If
the number is odd, check whether it is divisible by 11 but not by 7 and display a
meaningful message.
6. Write a program to determine all roots of a quadratic equation ax2+bx+c=0.
7. Write a program to evaluate the following function f(x) given by
a. =0 if x≤0
b. = x(x-10)(x-15) if 0<x≤10
c. = (x-10)(x-15)(x-20) if 10<x≤15
d. f(x)= (x-15)(x-20)(x-30) if 15<x≤20
e. =(x-20)(x-30)(x-40) if 20<x≤30
f. = 0 for all other cases
8. Write a program that prompts the user to enter any integer from 1 to 7 and displays the
corresponding day of the week.
9. Write a program that asks an arithmetic operator and two operands and performs the
corresponding operation on the operands.
10. Make a list of operators available in C with their precedence and associativity. Identify the
difference between the switch and the else if ladder structures.
11. “You are given a task to develop a system to read at least 100 integer numbers and
continue until the user enters No. Your system must have capacity to calculate the sum and
average of those numbers which are exactly divisible by 9 but not by 6 and lie between 1 to
100 and display a suitable message if no such number is read”. Write algorithm , flowchart
and code to develop such a system.
Background theory: for, while, do…while, nested for, nested while, nested
do…while, break, continue and goto structures and exit() function.
Note: Try to solve all the questions using for, while and do…while loop structures.
1. Run the following programs and observe/comment the output
2. a. int main()
b. int main()
{
{
int i; int a=10;
clrscr(); clrscr();
for(i=0;i<=255;i++) printf(“%d”, a);
printf(“%d=%c\t”,i,i); a=a+50;
getch(); printf(“%d”,a);
return 0; return 0;
} }
3. Write a program to read an unsigned integer and display from 1 to n and n to 1.
4. Write a program to display the sum of even numbers for 1 to n. [ n is an unsigned integer]
5. Write a program to read an integer(n) and find product from 1 to n else find sum from 0 to n.
6. Write a program to read an integer and calculate and display its factorial values. Display
appropriate message if its factorial cannot be calculated.
7. Write a program to calculate xn/n!. Where x is a floating point number and n is an integer (>=0).
8. Write a program to display the terms of a Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13 ……..
9. Write separate programs to check whether an unsigned integer entered by a user is a prime,
twin prime, triangular or Armstrong number.
10. Write a program to read a number (n) and display its multiplication table up to 10.
[1*5=5,…,10*5=50]
Background theory: Nested for, while, do…while structures, break, continue and
goto structures
1. Write a program to print a multiplication table of MXN. Read values of M and N from the
user.
2. Write a program to display the chessboard pattern. [Hint: print “\xdb” for white color and
print “ ” for black color.]
3. Write a program to read to integers (n1 and n2, both positive and n1<n2) from the user and
display the prime and palindrome numbers between n1 and n2. Display their count also.
4. Write a program to find the sum of all positive numbers entered by the user. Read numbers
and keep calculating the sum until the user enters 0.
5. Write separate programs to display the terms of the following sequences up to nth term:
a. 1, 2, 3, 4, 5+…………………..n
b. s=2, 4, 6, 8, 10, 12, 14………….2n
c. 1, 2, 4, 10, 17, 26……………
d. (12+22)/2, (22+32)/3, (32+42)/4,………….
e. 1, 1/3, 1/5, 1/7, 1/9, 1/11, 1/13…..1/2n-1
A. B. C. G. * * * * * * * H. 0
1 5 4 3 2 1 1 N * * * * * 1 1
1 2 5 4 3 2 2 E E * * * 2 2
1 2 3 5 4 3 3 P P P * 3 3
1 2 3 4 5 4 4 A A A A 2 4 4 2
1 2 3 4 5 5 5 L L L L L 1 5 5 1
F. 4 0 6 0
D. E. 3 4 1 5 5 1
A # # # # * 2 3 4 2 4 4 2
a B # # # * * 1 2 3 4 I. 1 3 3
A b C # # * * * 2 3 4 1 2 1 2 2
a B c D # * * * * 3 4 1 2 3 2 1 1 1
A b C d E * * * * * 4 1 2 3 4 3 2 1 0
1. Write a program to create a function float add(int, float);. The task of this function is to
calculate the sum of passed values and return to the calling function. Call this function
from main() and display the result.
2. Write a program to create a function void sumOfDigits(int);.This function must calculate
the sum of digits in the given number and display the sum.
3. Write a program to read a non-negative integer in main(). Pass this integer to a function
fact() having return type unsigned integer. This function calculates the factorial of the
received number and returns to main().
4. Write a program to create a function void check_prime(); The task of this function is to
read a number and check whether the number is prime or not and display the appropriate
message. Be sure that a real number cannot be either prime or composite. What about
negative numbers?
5. Combine question 1, 2, 3, 4 using the switch statement. For this, display a menu on the
screen to offer the user whether he wants to sum two numbers or sum of digits of an integer
or calculate the factorial of an integer or to know whether a number is prime or not.
6. Write a program to read an unsigned integer in main() pass it to a function
Er. Krishna Kandel
Learning C by Examples 378
(void countsDigits(int*, int*);). This function counts the number of odd digits and even
digits in it. Display the counts from main. Use concept passing by reference.
7. Write a program to create functions: int findLowest(int, int, int); and int findHighest(int,
int, int); . The task of findLowest() is to find the lowest of three integers and return an
integer to the calling function and, similarly, the task of findHighest() is to find the highest
of three integers and return an integer to the calling function. Call these functions in main()
giving appropriate arguments. Note: Use conditional operator (test expression?
expression1: expression2) to find the highest and lowest number.
8. Write programs using a recursive function to compute n!, xn, HCF of two numbers, sum
from 1 to n. Declare variables of appropriate types and read from the user.
9. Write a program using recursive function to compute the series: 12-22+32-42……(-1)n+1 n2.
Here, you cannot use pow() function and you should read the value of n from the user.
10. Write a program to computer the series: Sin(x)=x-x3/3!+x5/5!-x7/7!+x9/9!…….(-1) n-1
x (2n-1)
/(2n-1)! , n=1, 2, 3, 4, …….Here, write recursive function to calculate xn and n!
R
R
R
R
R
R
R
R
R
Background theory: What is a pointer? Why is it useful? Pointer variable declaration, pointer
initialization, pointer expression, pointer return type, dynamic memory allocation calloc(),
malloc(), realloc() functions for dynamic memory allocation and free() functions for releasing
allocated memory.
1. Run the following programs, observe the output and comment on that.
void main()
{
int a,b;
printf(“address of a:%u”,&a);
printf(“address of b:%u”,&b);
getch();
}
void main()
{
int *p,*q; /* Declaration of pointer variables */
int a,b; /* Declaration of ordinary variables */
p=&a; /* Using a referencing operator to initialize a pointer variable p.*/
q=&b;
printf("Address of a=%u\n",&a);
printf("Address of b=%u\n",&b);
printf("value of p=%u\n",p);
printf("value of q=%u\n",q);
printf("Enter value of a and b:");
scanf("%d%d",&a,&b);
printf("The value pointed by p is %d\n",*p); /*Using dereferencing operator (*).*/
printf("The value pointed by q is %d\n",*q);
printf("a+b=%d\n",a+b);
printf("*p+*q=%d",*p+*q); /* *p+*q → pointer expression */
}
2. Write a program to find the larger of two numbers using the concept of function and
pointer. Here pass two numbers from main() to a function that finds the larger. Display the
larger one from the main() without using a return statement.
3. Run the following program, observe the output and comment on that.
void main()
{
float marks[5];
int i;
printf(“%d”,marks);
printf(“address of different array elements:”);
for(i=0;i<5;i++)
printf(“address of element %d is %u\n”,i,&marks[i]);
/* printf(“address of element %d is %u\n”,i,(marks+i)); */
getch();
}
Note: Is there any difference between using expressions &array[i] and (array+i)?
4. This program asks the required size of array to the user and displays the addresses of
allocated blocks.
Er. Krishna Kandel
Learning C by Examples 381
#include<stdio.h>
#include<alloc.h> /* header file for memory management functions */
void main(void)
{
int n,i;
float *address; /* pointer variable declaration */
printf("Enter number of elements:");
scanf("%d",&n);
address=(float*)calloc(n,sizeof(float));
/* using calloc function to allocate memory for n number of float member */
if(address==NULL) /* to check whether the requested memory is allocated or not */
{ printf("Memory can not allocated.");
exit(); /* to exit from the program, if the contents of address is NULL */
}
for(i=0;i<n;i++)
{
printf("\nAddress of %d block %d ",i,(address+i));
}
free(address); /* to deallocate memory */
}
5. Solve all problems one dimensional array of exercise eight using the concept of
dynamic memory allocation. If you are interested try to solve the problems of two
dimensional arrays. Use equivalent notation of pointer and array as in the following
table.
Equivalent expressions of arrays and pointers
Type of array To be accessed Technique (→) Array Pointer
(↓) notation notation
One- Address of ith element &marks[i] (marks+i)
dimensional th
Value of i element marks[i] *(marks+i)
Two- Address of element at ith row and &marks[i][j] (*(marks+i)+j)
dimensional jth column
Value of element at ith row and jth marks[i][j] *(*(marks+i)+j)
column
Note: marks is an array name
D
D
D
D
D
D
D
D
D
Er. Krishna Kandel
Learning C by Examples 382
EXERCISE-TEN: STRING
Background theory : Introduction to string, role of null character at the end of strings, some
string handling functions: strlen(), strcat(), strcpy(), strcmp(), two dimensional arrays of
strings, dangling arrays, pointer to strings.
1. Run the following program, observe the output and comment on it.
void main()
{
int i;
char name1[]="pokhara city";
char name2[]={'k','a','t','h','m','a','n','d','u',' ','c','i',’t','y','\0'};
for(i=0;i<strlen(name1);i++)
printf(“%c\n”,name1[i]);
for(i=0;i<strlen(name2);i++)
printf(“%c\t”,name2[i]);
getch();
}
2. Write a program to check whether a string given by the user is Armstrong or not.
3. Write a program to read a string in main(), pass it to a function that returns the count of
numbers of words to main(). Display the count.
4. Write a program to read a string in main() using gets(). Pass it to a function that finds the
longest word of the string, counts the number of vowels and consonants in the word and
displays the counts and the world form main().
5. Write a program to reverse a word using a recursive function.
6. Write separate programs that exactly simulate the task strlen(), strcat(), strcpy() and
strcmp().
7. Write a program that will read a string and rewrite it in the alphabetical order. For example,
the word NEPAL should be written as AELNP
8. A program to count the frequency of characters in the string entered by a user.
9. A program to find the frequency of a character in the string entered by a user.
10. Write a program to read a string in main() pass it to a function. The function converts all
the upper case characters to lower case and vice versa.
11. Write a program to read names of 10 students in main() and pass the name list to a
function that sorts the array in ascending order. Display the sorted array from main().
12. Write a program to do the following:
• To print the question “Who is the prime minister of Nepal”?
• To accept the answer.
• To print “Good” and stop if the answer is correct.
• To print the message “try again”, if the answer is wrong.
• To display the correct answer when the answer is wrong even at the third attempt and
stop.
g
G
S
S
S
Er. Krishna Kandel
Learning C by Examples 383
EXERCISE-ELEVEN: STRUCTURE
Background theory: How structure template are declared, how structure variables are
declared, when memory is occupied, member operator(.), structure pointer operator(→),
structure initialization, arrays of structures, structures within structures, passing structures to
functions(by value and by reference), comparing structures with unions.
1. Write a program to read and display the Name, Address, Telephone number and Salary of
an employee using structure.
2. Create a structure employee containing names as character string, telephone as character
string and salary as integer. Input records of 10 employees. After that, display the mane,
telephone and salary of the employees with the highest salary and lowest salary and
display the average salary of all 10 employees.
3. Create a structure Date containing three members: int dd, int mm, int yy. Create another
structure Person containing four members: name, address, telephone and date of birth. For
member date of birth, create an object of structures date with in person. Using these
structures, write a program to input the records until the user enters ‘n’ or ‘N’. Then,
display the contents in tabular form.
4. Create a structure TIME containing hour, minutes and seconds as its member. Write a
program that uses this structure to input start time and stop time in main(). Pass the
structures to a function that calculates the sum and difference of start time and stop time.
Display sum and difference from main()
5. Write a program to compute any two instant memory spaces in a format (Kilobytes: Bytes:
Bits) using structure. Build functions to add and subtract given memory spaces where
1KB=1024B and 1B=8 bits and display the results in the main function.
Background theory: What is a file? Importance of file I/O, types of files, file operations, file
opening modes, buffer, difference between text and binary files, errors handling in file
processing, sequential and random access
1. Write a program to read years from the user and write to a file only if it is the leap year.
2. Write a program to read words from the user until the user enters ‘NO’ and write them to a
file if the word is vowel free. Display the content of the file.
3. Write a program to open a new file, read roll number, name, address and phone number of
students until the user says" no” after reading the data, write it to the file then display the
content of the file.
4. Write a program to input the name, roll, address, telephone number and score of a student.
Store the contents of the person in file first.txt. After that, copy the content of first.txt to
second .txt and display the content of second.txt. In this program, you should use the text
file. [You can use structure for data handling]
5. Modify question no 1, using a binary file. You should use fwrite() function to write data
into a the file and fread() functions to read data from the file [Here, you must use structure
for data handling]
Dww
Er. Krishna Kandel
Learning C by Examples 384
EXERCISE-THIRTEEN: GRAPHICS
Background theory: What is Graphics, importance of graphics, difference between text and
graphics modes of display unit, resolution, graphics adapters, drivers, graphics initialization,
different types of drawing functions, colors, text and font related functions
1. Write a program to lit a pixel at (x,y). Where values of x and y are entered by the user. You
must check whether the point is between (0, 0) and (maximum x, maximum y). The
maximum values of x and y coordinates can be found using getmaxx() and getmaxy()
functions.
2. Write a program to draw a line through points (20, 30) and (100,100).
3. Write a program to draw a rectangle having top-left coordinate (50,55) and right bottom
coordinate (100,150).
4. Write a program to draw 10 concentric circles having center at (150,150) and radius of
inner circle 40 and radius of immediate outer circle is 40+10 and so on.
5. Write a program to draw a circle at center (100,100) and radius 50.
6. Write a program to draw an arc of radius 70, center at (80, 80) and from angle 45 degrees to
150 degrees.
7. Write a program to draw a ellipse of major axis 50, minor axis 40, center at (100,100)
8. Write a program to draw an ellipse of major axis 50, minor axis 40, center at (100,100)
having start angle 2000 and end angle 3300.
9. Write a program to draw a pentagon, hexagon and heptagon taking vertices and side length
of your choice.
10. Write a program to demonstrate different types of font styles.
11. Write a program to present the data table in Bar graph and Line graph of graduated
students from different colleges in 2011 AD.
Note: All the coordinates given in the above questions are pixels. Solve all these questions using
the data entered by the user and checking condition as in question.
D
De
E
W
Ww
W
W
ddW
d