Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

C Lab Material

Uploaded by

080bct082.shruti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

C Lab Material

Uploaded by

080bct082.shruti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Learning C by Examples 369

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.

EXERCISE-ONE: BASIC INTRODUCTION

Background theory: What is a programming language? The types of programming


languages, introduction to C programming language, compilation process, structure of a C
program, difference between compiler and interpreter, difference between software and
firmware, difference between system software and application software.

1. Type the following program and see the output.


#include<stdio.h>
#include<conio.h>
void main(void)
{
printf(“This is my first C program.”);
getch();
}
Note: To compile: Alt+F9, To run: Ctrl+F9, to save F2, give file name and .C extension before
saving. Run this program without getch(). Run this program with clrscr() before printf(). Remove the
semicolons and run the program. Right click on printf() and read the help of printf() function.
Similarly right click on getch() to know more about it. In this everything can be studed using help.
To remove the line(s) of program, enclose in /* */. This enclosing process is called commenting.

2. Type the following program and run with different input.


#include<stdio.h>
#include<conio.h>
void main()
{
int s, a, b, c=20; /* variable declaration */
Er. Krishna Kandel
Learning C by Examples 370
printf(“Enter value of a:”); /* to display message on the screen */
scanf(“%d”,&a); /* to give value of a */
printf(“Enter value of b:”); /* to display message on the screen */
scanf(“%d”,&b); /* to give values of b */
s=a+b*c; /* processing */
printf(“sum=%d”, s); /* to display value stored at s */
getch(); /* to make program wait until user enters any character */
}
Activity: right click on int, printf, scanf, getch, void, main, include, stdio.h, conio.h and study more
about the terms.

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.

4. Write a program to calculate the area, circumference of a circle of radius r.


5. Write a program to calculate the volume of a sphere of radius r.
6. Write a program to calculate the simple interest. Read values of P, T, R from the user.
7. Read values of x and y from the user and evaluate the expression v=x3+y2-100/x;
8. Write a program to read 4 integers from the user and display the mean of the numbers.
9. Write a program to read a, l, b, and h of a parallelepiped and display its volume.
10. Write a program to read the price of two pens and five copies and calculate the price after
10% discount.
11. Write a program to read the a time value (hh:mm:ss) and convert it to the seconds and
display it.
12. Write a program to read the name and age of a person and display them.
13. Write a program to read a character and display it.

Er. Krishna Kandel


Learning C by Examples 371
EXERCISE-TWO: VARIABLES, OPERATORS AND EXPRESSIONS

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.

1.A program that inputs seconds as input and converts to minutes.


#include<stdio.h>
void main(void)
{ int seconds,min;
printf("Enter number of seconds:");
scanf("%d",&seconds);
min=seconds/60; /* integer division */
seconds=seconds%60; / integer division */
printf("\nMinutes=%d",min);
printf("\nSeconds=%d",seconds);
}
2.A program to illustrate post fix increment operator
#include<stdio.h>
void main()
{
int x=5,v;
v=++x * ++x + ++x;
printf("v=%d,x=%d\n",v,x);
}
3. A program to read three different integers from the user and display the largest numbers from
them.
#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,c,l;
clrscr();
printf(“Enter three different integers:”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b&&a>c)
l=a;
else if(b>a&&b>c)
l=b;
else
l=c;
printf(“Largest:%d”, l);
getch();
}

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 ]

Er. Krishna Kandel


Learning C by Examples 373

EXERCISE-THREE: CONSOLE INPUT/OUTPUT

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

1.Write a program to read a character using getche()/getchar() and display using


putch()/putchar().
2.Write a program to read a character and a string using scanf() and display printf().
3.Write a program to read strings using gets() and display using puts().
4.This example illustrates different format specifications for printing integer numbers.
void main()
{
int a=12345;
printf("\ncase 1 %d",a);
printf("\ncase 2 %i",a);
printf("\ncase 3 %15d",a);
printf("\ncase 4 %-15d",a);
printf("\ncase 5 %015d",a);
printf("\ncase 6 %-+15d",a);
printf("\ncase 7 %3d",a);
}
5.This example illustrates different format specifications for printing real numbers.
void main()
{
float n=123.9876;
printf("\ncase 1 %f",n);
printf("\ncase 2 %e",n);
printf("\ncase 3 %g",n);
printf("\ncase 4 %15.4f",n);
printf("\ncase 5 %-15.3f",-n);
printf("\ncase 6 %015.4e",n);
printf("\ncase 7 %.8f",n);
printf("\ncase 8 %2.2f",n);
}
6.This example illustrates different format specifications for printing characters.
void main()
{
char ch='a';
printf("\nCase 1 =%c",ch);
printf("\nCase 2 =%10c",ch);
printf("\nCase 3 =%-10c",ch);
}
7.This example illustrates different format specifications for printing strings.
void main()
{
char str[20]="I love Baglung.";
printf("\nCase 1 %s",str);
printf("\nCase 2 %18s",str);
printf("\nCase 3 %-18s",str);
Er. Krishna Kandel
Learning C by Examples 374
printf("\nCase 4 %18.8s",str);
printf("\nCase 5 %-18.9s",str);
printf("\nCase 6 %5s",str);
printf("\nCase 7 %.10s",str);
}
8.This example illustrates the concept of printing mixed data.
void main()
{
int n=12345;
float m=123.9876;
char ch='a';
char str[20]="I love Baglung.";
printf("n=%7dm=%12.5fch=%-2cstr=%16s",n,m,ch,str);
}
9.This example illustrates different format specifications for reading integer numbers.
void main(void)
{
int a,b;
printf(“Enter an integer number:”);
scanf(“%d”,&a);
printf(“The read and stored value of a is =%d”,a);
printf("Enter another integer number:");
scanf("%3d",&b);
printf("The read and stored value of b is =%d",b);
}
10.This example illustrates the concept of reading strings using %wc format specification .
void main(void)
{
char str[50];
printf("Enter a string:");
scanf("%10c",str);
printf("Read string is: %s", str);
}
11.This example shows the concept of defining a search set to read strings.
void main()
{
char str[70];
printf("How old are you:");
scanf("%[a-z0-9 ]",str);
printf("Read string is : %s",str);
}
12.This example also shows the concept of defining a search set to read strings.
void main()
{
char str[70];
printf("Enter a string:");
scanf("%[^M]",str);
printf("Read string is: %s",str);
}

Er. Krishna Kandel


Learning C by Examples 375

EXERCISE-FOUR: BRANCHING STRUCTURES

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.

Er. Krishna Kandel


Learning C by Examples 376
EXERCISE-FIVE: REPETITIVE STRUCTURE (LOOPING, ITERATION)

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]

EXERCISE-SIX: NESTED LOOP STRUCTURE

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

Er. Krishna Kandel


Learning C by Examples 377
6. Write separate programs to evaluate the series up to nth term:
a. s=2+4+6+8+10+12+14………….2n
b. S=e-1 =1-1/1!+1/2!-1/3!+1/4! -1/5!……. (-1)n+1 /(n-1)!, n=1,2,3….
c. f(x)=1- x2/2!+x4/4!-x6/6!+x8/8!……………… (-1)i x2i/2i! where i=0,1,2,3………..
7. Write a program to evaluate the series until the term becomes less than 10-6.
sn=1+x/1!+x2/2!+x3/3!………………..
8. Write separate programs to print the following patterns using nested loop structures.

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

EXERCISE-SEVEN: USER DEFINED FUNCTIONS

Background theory: Advantages of functions, function declaration, return type,


formal and actual arguments, function call, function header, function body, definition,
return statement, types of user defined functions, call by values and call by reference,
scope of variables, storage classes, recursion, recursive function, base case and
recursive case of recursive problems.

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!

EXERCISE-EIGHT: ARRAYS [ONE DIMENSIONAL AND TWO DIMENSIONAL]


Background theory: What is an array? What are advantages and disadvantages of arrays, one
dimensional and two dimensional arrays, searching, sorting and passing arrays to functions.

Q ONE DIMENSIONAL ARRAYS TWO DIMENSIONAL ARRAYS


1. void main() void main()
{ {
int i, num[6]={4,5,3,2,15}; int i,j, num[2][2]={{4,5},{6,7}};
for(i=0;i<6;i++) for(i=0;i<2;i++)
printf(“%d”,num[i]); for(j=0;j<2;j++)
getch(); printf(“%d”,num[i][j]);
getch();
} }
2. void main() void main()
{ {
int i, num[6]; int i,j, num[3][3];
printf(“Enter members of array:”); printf(“Enter members of array:”);
for(i=0;i<6;i++) for(i=0;i<3;i++)
scanf(“%d”,&num[i]); for(j=0;j<3;j++)
for(i=0;i<6;i++) scanf(“%d”,&num[i][j]);
printf(“%d”, num[i]); for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”,num[i][j]);
getch(); getch();
} }
3. Write a program to find the sum of Write a program to find the sum of
elements of an integer array of size 10 elements of an integer array of size 4X5
that are divisible by 10 but not by 15. that are divisible by 10 but not by 15.
4. Write a program to add the elements at Write a program to add the elements at
corresponding positions of two arrays of corresponding positions of two arrays of
size n . Read values of n from the user size MXN. Read values of M and N from
the user.
Er. Krishna Kandel
Learning C by Examples 379
5. Write a program to find the highest and Write a program to find the highest and
the lowest elements of an array of size the lowest elements of an array of size
10. 3x3.
6. Write a program to read elements of an Write a program to find the sum of
array in main() pass it to a function to diagonal elements. Pass the array to a
sort it in descending order. Display the function that returns the sum of diagonal
sorted array from main(). elements.
7. Write a program to take a position and a Write a program to raise the power of
number and insert this number on this each member by 5.
position inside an array containing n
elements and of type float
8. Write a program to read an unsigned Write a program to generate a matrix of
integer array in main(). Pass it to a size 4x4 whose elements are given by the
function that counts the Armstrong expression aij=3-(i+j).
members and return to main().
9. Write separate programs to compute the Write a program to find the sum of
median, range, variance and standard individual rows of a two-dimensional
deviation. Note: array and assign them to a one-
Variance= (∑x2)/n – ( (∑x2)/n)2 and dimensional array and display the content
standard deviation is √(variance). of one dimensional array.
10. Write a program to read an array of size Write a program that reads two matrices
in main() of size 10 and of type float. of order mxn and pxq using function
Pass the array to a function that finds readMatrix(). The program should contain
the highest and the lowest member. a function processMartrix() that takes
Display the sum of the highest and the the matrices and multiplies them. The
lowest and difference between highest result of multiplication must be displayed
and lowest from main() using passing using a function showMatrix().
by reference. Display the highest and
the lowest member from the function
with their index.
Note: Display two-Dimensional arrays in matrix form and choose relevant data type for arrays.

R
R
R
R
R
R
R
R
R

Er. Krishna Kandel


Learning C by Examples 380
EXERCISE-NINE: POINTER AND DYNAMIC MEMORY ALLOCATION

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 */
}

Note that the other process is similar to the array.

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.

EXERCISE-TWELVE: FILE I/O

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.

College No of students College No of students


A 198 D 159
B 267 E 213
C 243

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

Er. Krishna Kandel

You might also like