UG - B.Sc. - Computer Science - 130 14 - Lab Programming in C
UG - B.Sc. - Computer Science - 130 14 - Lab Programming in C
LAB: PROGRAMMING IN C
Author
Shweta Harsh Tiwari, Freelance Author
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
LAB: PROGRAMMING IN C
BLOCK 4: POINTERS
10. Initialization of pointer variables, address of variable, accessing a variable through its pointer
11. Pointer as Functions
12. Strings with Pointer: pointers and character strings, pointers and structures
BLOCK 5: FILES
13. Programs based on file handling
14. Error Handl
INTRODUCTION
Self-Instructional
Material
C Program Fundamentals
BLOCK 1 C PROGRAM
FUNDAMENTALS
NOTES
The first program while learning any programming language is ‘Hello world’
program. This program is used to check the programming environment. It will give
you idea of program editor, how to compile program and how to run program?
This program is very useful in learning the menus, shortcut and increase our
confidence. It is the easiest program but still we have to run this program for
understanding programming. For every program you have to first :
Write a program code compile (Ctrl+F9) Run(Alt +F9) observe
the output save your program (F2), you can also save your program before
compiling.
1. Write a program to print “Hello world!” on screen (Hello.c)
Step 1: Type the program in C or C++ editor
Self-Instructional
Material 1
C Program Fundamentals Step 3: Run the program and automatically *.exe is generated. Short cut for run is
Alt +F9.Output window will show you the output
Output:
NOTES
2. Write a program to input your name and age and display on screen.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr(); /*to clear screen*/
Self-Instructional
2 Material
3. Write a program to input principle, rate and time and display simple C Program Fundamentals
interest.
#include<stdio.h>
#include<conio.h>
NOTES
void main()
{
float p,r,t,SI; /*variable declaration */
clrscr(); /*to clear screen*/
SI=(p*r*t)/100;
Output:
temp=x; //swapping
x=y;
y=temp;
getch();
}
Output:
Self-Instructional
Material 5
C Program Fundamentals getdate(&d); //get current date in d variable
}
Output:
f=m/0.3048;
Self-Instructional
6 Material
getch(); C Program Fundamentals
}
Output:
NOTES
m=f*0.3048;
Self-Instructional
Material 7
C Program Fundamentals void main()
{
unsigned int A; /*variable declaration */
Self-Instructional
8 Material
12. Write a program to calculate area and circumference of circle. C Program Fundamentals
Declare PI as constant.
#include<stdio.h>
#include<conio.h>
NOTES
#include<dos.h>
void main()
{
const float PI=3.14; /* constant variable
declaration */
float r,A,C;
A=PI *r*r;
C=2*PI*r;
}
Output:
void main()
{
int a=3,b=5,c;
c=!a||(b=7);
printf(“\nb=%d\nc=%d”, b,c);
getch();
}
Self-Instructional
Material 9
C Program Fundamentals 14. Write the ouput of following program.
#include<stdio.h>
#include<conio.h>
NOTES void main()
{
int x,y,z;
x=48;
y=49;
z=50;
}
Output:
Self-Instructional
Material 11
C Program Fundamentals 18. Write a program to enter a character by using getchar (), convert it
into opposite (small to capital and capital to small) and use putchar
() function to display result.
#include<stdio.h>
NOTES
#include<conio.h>
#include<dos.h>
void main()
{
Char x; /* variable declaration */
Clrscr (); /*to clear screen*/
printf (“Enter any letter :- “);
x=getchar (); //input value of x
if (x>=65 && x<=90) //check letter is capital
x=x+32;
else if (x>=97 && x<=122)
//check letter is small
x=x-32;
else
printf (“Letter is not an Alplabet , Sorry can’t
convert”);
printf (“\nConverted letter is “);
putchar (x); //output
getch ();
}
Output:
In case of capital letter
Self-Instructional
12 Material
19. Write a program to check whether number is negative or positive C Program Fundamentals
using if….else.
Logic : if number >=0 then positive else negative
#include<stdio.h>
NOTES
#include<conio.h>
#include<dos.h>
void main()
{
int x; /* variable declaration */
clrscr (); /*to clear screen*/
printf (“Enter any number :- “);
scanf (“%d”,&x); //input value of x
if (x>=0) //check for positive number
printf (“%d is a positive number”,x);
else
printf (“%d is negative number”,x);
getch ();
}
Output:
In case of positive number
20. Write a program to enter a number and display whether the number
is positive or negative using ternary operator.
Ternary operator is a control statement similar to if…else
statement:
Syntax of ternary operator is:
(Condition)?true statement :false statement ;
Where condition is formed using variable and operator
(relational operator), true statement is the statement
to be executed when the condition is true and false
statement will be executed when the condition is false
(just like else statement). It is used when logic is
very simple in conditional statement.
Self-Instructional
Material 13
C Program Fundamentals Program:
#include<stdio.h>
#include<conio.h>
NOTES #include<dos.h>
void main()
{
int x; /* variable declaration */
clrscr (); /*to clear screen*/
getch ();
}
Output:
In case of positive number
Try yourself:
(i) Write a program to display greatest number out of two numbers
using ternary operator.
(ii) Write a program to enter your age, and display the message whether
“eligible to vote” or “not eligible to vote”.
void main()
{
int x; /* variable declaration */ NOTES
clrscr (); /*to clear screen*/
if (x % 2==0)
printf (“Number is even”);
else
printf (“Number is odd”);
getch ();
}
Output:
In case of even
In case of odd
Try yourself:
(i) Write a program to enter a number and display whether number is
divisible by 5 or not.
(ii) Write a program to enter a number and check number is divisible by
2 and 4 both.
(iii) Write a program to enter a number and check whether number is
divisible by 3 and 7.
}
Output:
In case of vowel
In case of consonant
Self-Instructional
16 Material
23. Write a program to enter two numbers and find the greatest number. C Program Fundamentals
#include<stdio.h>
#include<conio.h>
#include<dos.h> NOTES
void main()
{
int x,y; /* variable declaration */
clrscr (); /*to clear screen*/
if (x>y)
{
printf (“%d is greater “,x);
}
else if(y>x)
{
printf (“%d is greater”,y);
}
else
{
printf (“Both are equal”);
}
getch ();
}
Output:
In case of greater
In case of equal
Self-Instructional
Material 17
C Program Fundamentals 24. Write a program to enter three numbers and find the smallest number.
#include<stdio.h>
#include<conio.h>
NOTES #include<dos.h>
void main()
{
int x,y,z; /* variable declaration */
clrscr (); /*to clear screen*/
getch ();
}
Output:
In case of greater
Self-Instructional
18 Material
In case of all equal C Program Fundamentals
NOTES
25. Write a program to check leap year or not.
Logic :z Leap year is divisible by 4
Use of %(modulus operator) to check divisibility test
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int Y; /* variable declaration */
clrscr (); /*to clear screen*/
Self-Instructional
Material 19
C Program Fundamentals
Try yourself:
(i) Write a program to enter your year of birth and check whether the
year is leap year or not and also check how many leap years occurs
NOTES after your birth.
Hint: Refer program 7 for the use of struct date structure. Also refer
program 21 to check leap year . use calculation to find out number
of leap years after your birth.
26. Write a program to enter any character and find whether number is
character, digit, or other character.
Logic : If ASCII value is between (65 and 90) or(97 and
122) then character
Else If value is between (48 and 58) then digit
Else other character
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
char x; /* variable declaration */
clrscr (); /*to clear screen*/
printf (“Enter any character to check :- “);
scanf (“%c”,&x);
if ((x >=65 && x<=90)||(x>=97 &&x<=122))
//check for character
{
printf (“%c is an alphabet”,x);
}
else if(x>=48 &&x<=57) //check for digit
{
printf (“%c is a digit “,x);
}
else
{
printf (“%c is not an alphabet nor an digit , it is
other character”);
}
getch ();
Self-Instructional
}
20 Material
Output: C Program Fundamentals
In case of an alphabet
NOTES
In case of an digit
In case of both
switch (variable)
{
case value1: // executed if variable =value1;
break;
case value2: // executed if variable =value2;
break;
default: // executed if variable is not equal to any
value
}
Self-Instructional
22 Material
Program: C Program Fundamentals
#include<stdio.h>
#include<conio.h>
#include<dos.h> NOTES
void main()
{
int x; /* variable declaration */
char ch;
clrscr(); /*to clear screen*/
switch (x)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“Monday”);
break;
case 3: printf(“Tuesday”);
break;
case 4: printf(“Wednesday”);
break;
case 5: printf(“Thursday”);
break;
case 6: printf(“Friday”);
break;
case 7: printf(“Saturday”);
break;
default: printf(“ Not a valid number”);
break;
}
printf(“\nDo you want to continue: Press Y ot N”);
ch=getch();
if(ch==’y’ || ch ==’Y’)
Self-Instructional
Material 23
C Program Fundamentals goto startagain;
else
printf(“\nProgram is closing “);
NOTES getch();
}
Output:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int x,y,z; /* variable declaration */
char ch,op;
clrscr(); /*to clear screen*/
if(ch==’y’ || ch ==’Y’)
NOTES goto startlabel;
else
printf(“\nProgram is closing “);
getch();
}
Output:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int x=1; /* variable declaration */
clrscr(); /*to clear screen*/
Self-Instructional
26 Material
labelx: C Program Fundamentals
printf(“\n%d”,x);
x=x+1;
NOTES
if(x<=10)
goto labelx;
getch();
}
Output:
A:
printf(“\n%d”,x);
x=x+1;
B:
printf(“\n%d”,x+1);
x=x+2;
if(x<=10)
goto A;
else if(x<=20)
goto B;
else
goto C;
Self-Instructional
Material 27
C Program Fundamentals C:
getch();
}
Label1:
printf(“\n%d”,a);
a=a+10;
Label2:
printf(“\n%d”,a);
a=a+20;
if(a<=100)
goto Label1;
else if(a>=100 && a<=300)
goto Label2;
getch();
}
34. Write a program to display numbers from 20 to 1 in reverse order
using goto statement.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int a=20; /* variable declaration */
clrscr(); /*to clear screen*/
Label1:
Self-Instructional
28 Material
printf(“\n%d”,a); C Program Fundamentals
a=a-1;
if(a>=1)
goto Label1; NOTES
getch();
}
Output:
35. Write a program to print your name on Screen using goto statement
for infinite time.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
Label1:
printf(“Shweta Tiwari”);
goto Label1;
getch();
}
Self-Instructional
Material 29
C Program Fundamentals Output:
NOTES
Press Alt+Ctrl+Del and open task manager and close the program.
Looping
Looping means to repeat certain statements for finite or infinite number of time
.C language has three types of loops. You can use any of the loop to write a
program. It’s totally based on programmer choice to select type of loop. Once
you will be able to run your program manually on paper then you will be mastering
loop. When we run program on paper, then the process is known as dry run.
Nested Loop:
Loop within loop is called nested loop.
Three types of loops are
while loop
do while loop
for loop
Syntax of while loop…
initialization;
while (condition is true)
{
Statements to be executed;
}
Syntax of do while loop: do while will be executed at
least once as the condition is checked at the end.
Initialization;
Self-Instructional
30 Material
do{ C Program Fundamentals
statements;
}while(condition is true);
Syntax for for…loop NOTES
for(initialization; condition ; increment/ decrement )
{
Statement;
}
36. Write a program to print first 10 even numbers using while loop.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int E=2; /*variable initiliazation */
while(E<=20)
{
printf(“\n%d”,E);
E=E+2;
}
getch();
}
Output:
getch();
}
Output:
Try yourself:
(i) Write a program to display first 20 odd numbers using the while
loop.
(ii) Write a program to print table of 5 on screen using while loop.
38. Write a program to print the series on screen using while loop.
6 12 18 24 30 ……..n times
#include<stdio.h>
#include<conio.h>
void main()
{
int n,t=6,x=1; /*variable initiliazation */
clrscr(); /*to clear screen*/
printf(“Enter the value of n”);
scanf(“%d”,&n);
while(x<=n)
Self-Instructional
32 Material
{ C Program Fundamentals
printf(“\t%d”,x*t);
x=x+1;
} NOTES
getch();
}
Output
Try yourself:
(i) Write a program to display your name for 10 times on screen using
while loop.
(ii) Write a program to display the following series on screen.
4 10 16 22 28 34
#include<stdio.h>
#include<conio.h>
void main()
{
int a=0,b=1,c,n; /*variable initiliazation */
Self-Instructional
Material 33
C Program Fundamentals c=a+b;
printf(“\t%d”,c);
NOTES a=b;
b=c;
n=n-1;
}
getch();
}
Output:
Try yourself:
(i) Write a program to print the n th value of Fibonacci series.
Example n=10 then the result 10th Fibonacci
element = 34
#include<stdio.h>
#include<conio.h>
void main()
{
int n,count=0,x=1; /*variable initiliazation */
while (x<=n)
{
Self-Instructional
34 Material
if(n % x == 0) C Program Fundamentals
count++;
x++;
NOTES
}
if(count==2)
printf(“Number is prime “);
else
printf(“Number is not a prime number that means composite
number”);
getch();
}
Output:
In case of not a prime number
41. Write a program to find out the Armstrong numbers from 0 to 999
range.
This program computes all Armstrong numbers in the range of 0 and 999.
An Armstrong number is a number such that the sum of its digits raised to
the third power is equal to the number itself.
For example, 371 is an Armstrong number, since
33 + 73 + 13 = 371.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=0,count=0,x,y,z,temp,sum=0; /*variable
initiliazation */
Self-Instructional
Material 35
C Program Fundamentals while (a<=999)
{
temp=a;
NOTES
x=temp%10; //taking out last digit
temp=temp/10;
y=temp%10;
temp=temp/10;
z=temp%10;
temp=temp/10;
sum=(x*x*x)+(y*y*y)+(z*z*z);
if(sum==a)
{
count++;
printf(“\nArmstrong number%d=%d”,count,a);
}
a++;
}
getch();
}
Output:
42. Write a program to enter a number between 100 and 999 and reverse
its digits.
Example : 546 will be 645
Simple logic is to take all the digits in different
variable and multiply them with 100,10,1 and add them
to get reverse number
X=5
Y=4
Z=6
(X *100)+(Y*10)+(Z*1) to get reverse number
Self-Instructional
36 Material
Program: C Program Fundamentals
#include<stdio.h>
#include<conio.h>
void main() NOTES
{
int a=0,x,y,z,temp,rev=0; /*variable initiliazation */
temp=a;
rev=(x*100)+(y*10)+(z*1);
printf(“\nNumber =%d \t Reverse number=%d”,a,rev);
getch();
}
Output:
Self-Instructional
Material 37
C Program Fundamentals 43. Write a program to enter three digit number and check whether
number is palindrome or not. Palindrome is the number which will be
same on reversing it.
#include<stdio.h>
NOTES
#include<conio.h>
void main()
{
int a=0,x,y,z,temp,rev=0; /*variable initiliazation
*/
temp=a;
rev=(x*100)+(y*10)+(z*1);
if(a==rev)
printf(“\nNumber =%d is palindrome”,a);
else
printf(“\nNumber =%d is not a palindrome”,a);
getch();
Self-Instructional
}
38 Material
Output: C Program Fundamentals
NOTES
In case of palindrome
while(n<=20)
{
sum=sum+n;
n++;
}
printf(“Sum of first 10 natural number is =%d”,sum);
getch();
}
Output:
#include<stdio.h>
#include<conio.h>
void main() Self-Instructional
Material 39
C Program Fundamentals {
int n,fact=1,temp; /*variable initiliazation */
}
printf(“Factorial of a number %d is %d”,n,fact);
getch();
}
Output:
Try yourself:
(i) Write a program to find number of digits in a number.
(ii) Write a program to find frequency of each digit in a number.
(iii) Write a program to find the product of digits in a number.
(iv) Write a program to find sum of first and last digit.
(v) Write a program to print sum of first ten even numbers.
(vi) Write a program to print product of first and last digit.
(vii) Write a program to display first ten natural numbers from n to
1(descending order).
Self-Instructional
40 Material
46. Write a program to print table of any number entered by user upto n C Program Fundamentals
number of times.
Example: Table of : 7
Upto how many times : 15 NOTES
Then the table of 7 will be displayed upto 7 × 15 = 105
In this loop will be executed according to the number entered by user and
that’s why the condition is checked at last and the value is entered by user
#include<stdio.h>
#include<conio.h>
void main()
{
int n,t,x=1; /*variable initiliazation */
getch();
}
Output:
Self-Instructional
Material 41
C Program Fundamentals 47. Write a program to print natural numbers upto n times.
#include<stdio.h>
#include<conio.h>
NOTES void main()
{
int n,x=1; /*variable initiliazation */
do
{
printf(“\n%d”,x);
x++;
}while (x<=n);
getch();
}
Output:
48. Write a program to print a random number till user want to print. In
this program user is going to generate random numbers till user
press ‘Y’ to continue.
rand () function is used in C to generate random numbers. If we generate
a sequence of random number with rand () function, it will create the
same sequence again and again every time program runs. Say if we are
generating 5 random numbers in C with the help of rand () in a loop, then
every time we compile and run the program our output must be the same
sequence of numbers.
Self-Instructional
42 Material
rand () function is present in <stdlib.h> C Program Fundamentals
Program:
#include<stdio.h>
#include<conio.h> NOTES
void main()
{
char ch; /*variable declaration */
int x=1,n;
do
{
printf (“\nYour %d random number is %d”,x,rand());
x++;
printf (“\n\nDo you want to continue generating random
number,Press’Y’ or’N’:”) ;
fflush(stdin);
scanf(“%c”,&ch);
}while (ch==’Y’ || ch==’y’);
getch();
}
Output:
49. Write a program to find out the number of digits in a number entered
by user.
#include<stdio.h>
#include<conio.h>
void main()
Self-Instructional
Material 43
C Program Fundamentals {
int x,count=0,temp; /*variable declaration */
getch();
}
Output:
do
{
printf(“\ni=%d\tj=%d”,i++,j++);
i++;
j—;
}
while (i<=20);
Self-Instructional
44 Material
getch(); C Program Fundamentals
Try yourself:
(i) Write a program to generate the following output: NOTES
10 20 40 80 160 320
Try yourself:
Write a program to generate following output.
1 4 9 16 25 36 49 72 81 100
Self-Instructional
Material 45
C Program Fundamentals 53. Write the output for the following program :
#include<stdio.h>
#include<conio.h>
NOTES void main()
{
int i=1,j=2; /*variable declaration */
clrscr(); /*to clear screen*/
do
{
printf(“\ni=%d\tj=%d”,i++,j++);
j++;
}
while (i<=10,j<=10);
getch();
}
54. Write the output of the following program.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1; /*variable declaration */
clrscr(); /*to clear screen*/
do
{
printf(“\nOutput =%d”,i * ++i);
i++;
}
while (i<=10);
getch();
}
For loop
For loop is the loop which contain initialization , condition checking and increment
and decerment in one single statement .Steps of for loop is shown in the form of
flowchart:
Self-Instructional
46 Material
C Program Fundamentals
i. Initialization
ii. condition
NOTES
If condition is true
iv. Increment/
decrement
Note: If the increment is pre increment or pre decrement then , step iv. Will be executed
(increment/decrement) before step iii.(statements)
Syntax:
for (initialization; condition ; increment /decrement )
{
Statements;
}
Example:
for( int x=1; x<=10;x++)
{
printf(“\t%d”,x);
}
Output:
1 2 3 4 5 6 7 8 9 10
55. Write a program to print first 10 odd numbers on screen.
#include<stdio.h>
#include<conio.h>
void main()
{
int i; /*variable declaration */
clrscr(); /*to clear screen*/
for (i=1;i<=19;i=i+2)
{
printf(“\n%d”,i);
Self-Instructional
Material 47
C Program Fundamentals }
getch();
}
NOTES Output:
56. Write a program to enter a number (n) and find out sum of series
upto n times.
Sum= 1+2 +3+4+5 +6…….n
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i; /*variable declaration */
clrscr(); /*to clear screen*/
printf(“Enter the value of n:”);
scanf(“%d”,&n);
for (i=1;i<=n;i++)
{
printf(“%d+”,i);
sum=sum+i;
}
printf(“ =%d”,sum);
getch();
}
Output:
Self-Instructional
48 Material
57. Write a program to print Fibonacci series upto n using for loop. C Program Fundamentals
#include<stdio.h>
#include<conio.h>
void main() NOTES
{
int a=0,b=1,c,n; /*variable initiliazation */
getch();
}
Output:
NOTES getch();
}
Output:
#include<conio.h>
void main()
{
int n,temp,revnum,remainder; /*variable declaration
*/
clrscr(); /*to clear screen*/
printf(“Enter the number to reverse it “);
scanf(“%d”,&n);
for(temp=n,revnum=0;temp!=0;temp=temp/10)
{
remainder=temp%10;
revnum=revnum*10+remainder;
}
printf(“Original number=%d and reverse
number=%d”,n,revnum);
getch();
}
Output:
i=1;
j=1;
clrscr(); NOTES
for(k=1;k<=3;k++)
{
printf(“\n%d\t%d\t%d”,i,j,k);
}
getch();
}
Nested loop
Loop within a loop is called nested loop.
Generally we use nested loop using for loop , as it is short to write and easy
to understand
Nested loop has more than one loop . The first loop is known as outer loop
. the loop within the loop is known as inter loop.
Nested loop working is explained through flowchart
61. Write a program to print the pattern on screen using nested loop.
1
12
123
1234
12345
Self-Instructional
Material 51
C Program Fundamentals In the program outer loop is for number of rows(5)
Inner loop is used to print elements in one col
NOTES
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int row,col; /*variable declaration */
Self-Instructional
Material 53
C Program Fundamentals {
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
Self-Instructional
54 Material
int row,col; /*variable declaration */ C Program Fundamentals
Logic 1 program:
#include<stdio.h>
#include<conio.h>
void main()
{
Self-Instructional
Material 55
C Program Fundamentals int row,col,n; /*variable declaration */
for (col=1,n=10;col<=row;col++,n-=2)
//inner loop
{
printf(“\t%d”,n);
} //closing of inner loop
printf(“\n”); //to change row otherwise all
the elements will be printed
on same line
} //closing of outer loop
getch();
}
Output:
Logic 2 Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int row,col,n; /*variable declaration */
getch();
}
Output: NOTES
for(row=5;row>=1;row—);
{
for (col=1;col<=row;col++)
{
printf(“\t*”);
}
printf(“\n”);
}
getch();
}
Output:
66. Write a program to print the above output pattern on screen for two
times.
Self-Instructional
58 Material
Program: C Program Fundamentals
#include<stdio.h>
#include<conio.h>
void main() NOTES
{
int row,col,n; /*variable declaration */
for(n=1;n<=2;n++)
{
for(row=5;row>=1;row—)
{
for (col=1;col<=row;col++)
{
printf(“\t*”);
}
printf(“\n”);
}
}
getch();
}
Self-Instructional
Material 59
C Program Fundamentals
Try yourself:
(i) Write a program to print the following pattern on screen
5 4 3 2 1
NOTES 4 3 2 1
3 2 1
2 1
1
(ii) Write a program to print the following pattern on screen
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
for(i=1;i<=5;i++)
{
for(fact=1,j=i;j>=1;j—)
{
fact=fact*j;
}
sum=sum+(float)i/fact;
}
printf(“Sum of series =%f”,sum);
getch();
}
Output:
Self-Instructional
60 Material
Functions, Arrays and Strings
A 10 20 30 40 50
getch();
}
Output:
Self-Instructional
62 Material
sum=sum+a[i]; Functions, Arrays and Strings
}
printf(“\nSum of all elements= %d “,sum);
getch(); NOTES
}
Output:
for(i=4;i>=0;i—)
{
printf(“\nElement %d of array =%d”,i+1,a[i]);
}
getch();
}
Self-Instructional
Material 63
Functions, Arrays and Strings Output:
NOTES
for(i=0;i<=9;i++) //sorting
{
for(j=0;j<=9;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
Self-Instructional
64 Material
for(i=0;i<=9;i++) Functions, Arrays and Strings
{
printf(“%d\t”,a[i]);
} NOTES
getch();
}
Output:
Try yourself:
(i) Write a program to enter 5 elements in an array and swap first and
last item and then display array.
(ii) Write a program to display the size of array using sizeof().
Hint: n=sizeof(a)/sizeof(int);
sizeof() function is present in stdio.h. It will give you the total memory
size occupied by variable and then divide by sizeof each data type.
If array contain 5 elements then sizeof()function returns 10,then 10/
2=5 are the number of elements .
(iii) Write a program to create array of 10 elements and replace all the
prime numbers by 0.
Note: This program requires nested loop , one for array and other
for checking prime number.
(iv) Write a program to initialize an array of 20 elements and replace all
the even number by 0 and all the odd number by 1.
(v) Write a program to search a number in an array of size 10 and also
display the position of array element if found otherwise display the
message” not found”.
Self-Instructional
Material 65
Functions, Arrays and Strings Two dimensional Array:
Two dimensional array is used to represent matrices.
It is divided into rows and columns
NOTES It is declared as datatype variable[n][m];
Example: int A[2][3];
This creates array of 2 rows and 3 columns.
A[0][0] A[0][1] A[0][2]
Self-Instructional
66 Material
for(i=0;i<=2;i++) //array initilazation Functions, Arrays and Strings
{
for(j=0;j<=2;j++)
{ NOTES
printf(“\nEnter the element[%d][%d] of
array”,i,j);
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(“\t%d”,a[i][j]);
}
printf(“\n”);
}
getch();
}
Output:
Self-Instructional
Material 67
Functions, Arrays and Strings Program
#include<stdio.h>
#include<conio.h>
printf(“\t%d”,a[i][j]);
}
printf(“\n”); NOTES
}
printf(“\nB=\n”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“\t%d”,b[i][j]);
}
printf(“\n”);
}
printf(“\nC=\n”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“\t%d”,c[i][j]);
}
printf(“\n”);
}
getch();
}
Output:
Self-Instructional
Material 69
Functions, Arrays and Strings 7. Write a program for matrix multiplication for 2 × 2 matrix
#include<stdio.h>
#include<conio.h>
NOTES void main()
{
int a[2][2],b[2][2],c[2][2],i,j,k,sum=0;
//array declaration
clrscr(); /*to clear screen*/
Self-Instructional
70 Material
c[i][j]=sum; Functions, Arrays and Strings
}
}
NOTES
printf(“\nA=\n”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“\t%d”,a[i][j]);
}
printf(“\n”);
}
printf(“\nB=\n”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“\t%d”,b[i][j]);
}
printf(“\n”);
}
printf(“\nC=\n”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“\t%d”,c[i][j]);
}
printf(“\n”);
}
getch();
}
Self-Instructional
Material 71
Functions, Arrays and Strings Output:
NOTES
Try yourself:
(i) Write a program to enter 3 × 3 matrix and replace all the even number
by 0 and odd number by 1. The matrix you get is sparse matrix.
(ii) Write a program to arrange the elements of 2 × 2 matrix in descending
order.
(iii) Write a program to find maximum and minimum of array from 4 × 4
matrix.
(iv) Write a program in c to find the transpose of matrix (transpose is
row will be converted as columns and columns will be considered
as rows)
String Handling in c
String is an array of characters.
At last string contain NULL character(‘\0’) for ending the string
In c language <string.h> header file is used for string handling.
It contains some of the common functions like
strcpy() – to copy string
strcat() – to concatenate string
strlen()- to display string length
strcmp()- to compare strings
Different ways of declaring string are:
char str1[20]; // Character array
char str2[20] = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ };
// Array initialization
char str3[20] = “hello”; // Shortcut array
Self-Instructional initialization
72 Material
char str4[20] = “”; // Empty or null C string Functions, Arrays and Strings
of length 0,equal to “”
We can also declare a C string as a pointer to a
char:
char* str5 = “hello”;
NOTES
To read string use : gets(str); function
To display string use : puts(str); function
8. Write a program in C language to read a string and display it.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char str[30];
printf(“Enter String “);
gets(str);
printf(“\nString is “);
puts(str);
getch();
}
Output:
void main()
{
char str1[30],str2[30];
clrscr();
printf(“Enter String “);
gets(str1);
strcpy(str2,str1);
printf(“\nCopied String is “);
Self-Instructional
Material 73
Functions, Arrays and Strings puts(str2);
getch();
}
NOTES Output:
10. Write a program to enter two strings, compare them and display the
message whether the strings are equal or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
clrscr();
printf(“Enter String1 “);
gets(str1);
printf(“Enter String2”);
gets(str2);
if (strcmp(str1,str2)==1)
{
printf(“Both the strings are same”);
}
else
{
printf(“String are not same”);
}
getch();
}
Output:
Self-Instructional
74 Material
11. Write a program to enter a string and find out whether the string is Functions, Arrays and Strings
palindrome or not.
In this we use strrev(str); function to reverse the
string.
NOTES
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
clrscr();
printf(“Enter String1 “);
gets(str1);
}
Output:
Try yourself:
(i) Write a program to find the length of string using strlen() function.
(ii) Write a program to concatenate the two strings entered by user.
(iii) Write a program in c to change the case of letters into opposite .i.e
capital will change into small and small will change into capital.
Self-Instructional
Material 75
Functions, Arrays and Strings User defined functions
User defined function are used in structural programming. C is structural
programming and it supports user defined functions. When we create functions, it
NOTES require three things:
declaration (before definition ),
definition ,
function call
Function declaration is used before definition .To declare any function we
have to write:
Return type fun_name (arguments);
o Return type can be any data type which is returned by function.
o Function name should be unique, without spaces and it should not be
keyword.
o Arguments are the list of values provided to function for calculation
Function definition:
Return type fun_name (arguments)
{
_______________;
_______________;
}
Function call:
Function call is used to call function and after execution of function it come back to
the position from where we called the function. Function cannot be executed without
call.
Fun_name (argument value);
User defined functions are of four types:
(a) Return no value , passes no arguments
(b) Return no value , passes arguments
(c) Return value , passes no argument
(d) Return value , passes arguments
Now consider the same program with four different types:
12. Write a program to create a function sum with all four types and call
it in program.
#include<stdio.h>
#include<conio.h>
void sum1(); //function declaration with no return
Self-Instructional
76 Material
value, no arguments Functions, Arrays and Strings
void main()
{
char ch=’y’;
int a,b,c,n;
clrscr();
Self-Instructional
Material 77
Functions, Arrays and Strings printf(“Sum=%d”,c);
}
else if(n==4)
NOTES {
printf(“Enter two number for addtion”);
scanf(“%d%d”,&a,&b);
c=sum4(a,b); //function call
printf(“sum=%d”,c);
}
else
{
printf(“Invalid choice, Try again”);
}
printf(“\nDo you want to continue, press ‘y’ or
‘n’”);
fflush(stdin);
scanf(“%c”,&ch);
}
getch();
}
Self-Instructional
78 Material
Functions, Arrays and Strings
int sum3() //function definition
{
int a,b,c;
printf(“Enter two number for addtion”);
NOTES
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Try yourself:
(i) Write a function which return the value and passes argument for
calculating factorial of a number.
(ii) Write a function in c which return value but passes no argument for
calculating Simple Interest.
(iii) Write a function in c which return no value, but passes argument for
displaying Fibonacci series upto n times.
(iv) Write a function in c which return no value , but passes argument for
finding out number of digit in a number.
Self-Instructional
Material 79
Functions, Arrays and Strings Recursive function:- Recursive function is a function which call itself.
Function which calls itself is called recursive function. The working of
recursive function is shown in flowchart.
NOTES
void main()
{
count_uptoten ( 0 );
}
void main()
Self-Instructional
80 Material
{ Functions, Arrays and Strings
int n;
printf(“Enter the number to take out factorial:
“);
NOTES
scanf(“%d”, &n);
printf(“Factorial of number%d is %d”, n,
fact(n));
}
int fact(int n)
{
if (n >= 1)
return n*fact(n-1);
else
return 1;
}
Output:
Try yourself:
(i) Write recursive function to print your name for 10 times.
(ii) Write recursive function to display the sum of array.
(iii) Write recursive function to display sum of n numbers.
Self-Instructional
Material 81
Structures and Union
float ta;
float hra;
float deduction; NOTES
float gross;
float netsal;
};
void main()
{
struct emp E; // de cla ri ng st ru ct
variable
clrscr();
E=getinfo(E); //fucntion call
putinfo(E); //fucntion call
getch();
}
Next program will show you the example of creating array of structure.
2. Write a program to create array of structure for emp. Program should
enter the info of 5 employees and display it.
The same above program is modified to illustrate example.
Program:
#include<stdio.h>
#include<conio.h>
Self-Instructional
84 Material
float deduction; Structures and Union
float gross;
float netsal;
}; NOTES
struct emp *getinfo(struct emp E[]);
//declaring function
void putinfo(struct emp E[]); //declaring function
void main()
{
struct emp E[5],*Eptr; //declaring struct
variable
clrscr();
Eptr=getinfo(E); //fucntion call
putinfo(Eptr); //fucntion call
getch();
}
void main()
{
struct student stu = {“Ram”, 1, 80};
clrscr();
Self-Instructional
86 Material
putdata(stu.name, stu.roll_no, stu.marks); Structures and Union
getch();
}
struct student
{
char name[30];
struct dob d; //structure within structure
};
void main()
{
struct student s;
clrscr();
printf(“Enter name”);
Self-Instructional
Material 87
Structures and Union fflush(stdin);
gets(s.name);
printf(“\Enter dob”);
NOTES scanf(“%d%d%d”,&s.d.dd,&s.d.mm,&s.d.yyyy);
printf(“Name is %s”,s.name);
printf(“\nDOB is %d/%d/%d”,s.d.dd,s.d.mm,s.d.yyyy);
getch();
}
Output:
Try yourself:
(i) Write a program to store and print the roll no., name, age and marks
of a student using structures.
(ii) Write a program to add two distances in inch-feet using structure.
The values of the distances is to be taken from the user.
(iii) Write a program to add, subtract and multiply two complex numbers
using structures to function.
(iv) Write a program to compare two dates entered by user. Make a
structure named Date to store the elements day, month and year to
store the dates. If the dates are equal, display “Dates are equal”
otherwise display “Dates are not equal”.
Union in c language
A union is a special data type available in C that allows to store different data
types in the same memory location.
Unions can be useful in many situations where we want to use the same
memory for two or more members.
Union is like a structure. In union, all members share the same memory
location.
The main difference between union and structure is union occupies less
memory space as compared to structure.
Example of union
#include <stdio.h>
#include <string.h>
#include<conio.h>
Self-Instructional
88 Material
union userdata { Structures and Union
int i;
float f;
char str[20]; NOTES
};
void main( ) {
union userdata d;
clrscr();
printf( “Memory size occupied by data : %d Bytes\n”,
sizeof(d));
getch();
}
Output:
struct mystruct
{
char fname[30];
float sal;
int emocode;
} S;
void main()
{
printf(“The size of union = %d”, sizeof(U));
printf(“\nThe size of structure = %d”, sizeof(S));
getch();
}
Self-Instructional
Material 89
Pointers
BLOCK 4 POINTERS
NOTES Pointers
Pointer are address variable .
They are used to store address of variable .
By using pointers we can change the values stored in variable.
Pointer are declared by using the following syntax
Datatype *pointername;
Pointer uses two operators :
* read as value stored at
Example: *ptr is read as value stores at ptr(address)
& address of
Example: &a is read as address of a
Example of pointer declaration and initialization and
pointer handling
a ptr ptr2
10 1001 1009
Self-Instructional
90 Material
Note: The very important things are *(value stored at) and & Pointers
(address of ) operator . When you read the operator properly,
there is no chance of errors or mistakes in pointer programs.
void main()
{
int x[] = { 10, 20, 30, 40, 50} ;
int *ptr;
ptr = X;
printf(“ %d “, *( ptr + 1) );
getch( );
}
2. Predict the output of the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5, *p;
p = &i;
printf(“%d\n”, i * *p * i + *p);
getch();
}
Self-Instructional
Material 91
Pointers 3. Predict the output of the following program.
#include<stdio.h>
#include<conio.h>
#include <stdio.h>
#include<conio.h>
0 B h o p a l ‘\0’
1 N a g p u r ‘\0’
2 C h e n n a i ‘\0’
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
char *ptr[3] = //array of pointer
{
“Bhopal”,
“Nagpur”,
“Chennai”,
};
int i, j;
for (i = 0; i <=2; i++)
{
j = 0;
Self-Instructional
Material 93
Pointers while(*(ptr[i] + j) != ‘\0’)
{
printf(“%c”, *(ptr[i] + j));
NOTES j++;
}
printf(“\n”);
}
getch();
}
8. Write a program to arrange the stirng in lexographical order
(dictionary order).
#include <string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
char str[10][20], temp[20];
printf(“Enter 5 words:\n”);
}
Output:
NOTES
Syntax of calloc()
pointer = (cast-type*)calloc(n, element-size);
Example
ptr = (int*) calloc(5, sizeof(int));
The above statement allocates continous space in memory for
an array of 5 elements each of size of int, i.e, 2 or 4 bytes.
Syntax of free( )
free(pointer);
Example
free(ptr);
Self-Instructional
Material 95
Pointers It is always a better practice to free the space occupied in
our program before ending it.
9. Write a program to create array of n elements using pointer and
malloc ( ) function and display its sum.
NOTES
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n, i, *ptr, sum = 0;
clrscr();
Self-Instructional
96 Material
10. Write a program to create array using calloc () function for n number Pointers
void main () {
int i, n;
int *p;
clrscr();
printf(“Enter Number of elements to be entered:”);
scanf(“%d”,&n);
p = (int*)calloc(n, sizeof(int));
printf(“%d numbersof elements “,n);
Self-Instructional
Material 97
Files
BLOCK 5 FILES
File is a physical place in secondary memory. Variables are created in RAM and
NOTES
files are created in hard disk. The data stored in files are permanent. When the
program stop executing all the data is lost and if we want to save it permanently
than we have to use files.
C uses some special statements to perform operations on files.In c language
we can create two types of files
Text file
Binary file
Text file are having extension as .txt file.Text file is less secure and takes
huge amount of storage.
Binary files
Binary files are having .bin files in your computer. Binary files store the data in the
form of binary format. They are more secure and store large amount of data.
File operation
The basic file operations are
Create file
Open file
Read and write in file
Close file
For any type of file operation first we need to create file pointer. This pointer
is used to create, open, read and write and close file. All the functions related with
files are present in <stdio.h>
FILE *fptr;
Function to open file
fptr = fopen(“fileopen.ext”,”mode”)
where mode can any one of the following
“r” Opens file in read only mode
“rb” Opens file in read only in binary format
“w” Opens file in write mode
“wb” Opens file in binary write mode
“a” Opens files in append mode, add at last
“ab” Opens files in append mode , binary format
“r+” Opens file in read and write mode
“rb+” Opens files in read and write mode in binary
“w+” Open in both read and write mode
“wb+” Open in both read and write mode in binary mode
Self-Instructional
98 Material
Function to close file Files
fclose(fptr);
Function to put string in file
fputs(“string …”,fptr); NOTES
Function to get string from file
char *fgets(char *str, int n, FILE *stream)
Where fgets returns file pointer, str is the string to get values from file, n is
the maximum number of character and file * stream is file pointer.
Example fgets(str,50,fptr);
Will get the maximum 50 characters from file in str string.
Function for file pointer positioning
fseek (fptr, n,position);
where fptr is file pointer, n is the number of character
from position , and position can be any one out of three
SEEK_SET/ SEEK_CUR / SEEK_END
SEEK_Set is used for beginning
SEEK_CUR is used for current position
SEEK_END is sued for ending position
Example
fseek(fptr,10,SET_CUR)
file pointer is set after 10 characters form current position
How to write in file using function from keyboard to file?
scanf( ) fprintf ( )
Keyboard Variable File
Read from keyboard(Input)scanf( )to variable variable to file (output)fprintf( )
Read from keyboard(Input)scanf( )àto variable àvariable
to file (output)fprintf( )
How to read from file and display on monitor?
void main()
{
Self-Instructional
Material 99
Files int n; //file pointer
FILE *fptr;
char ch=’y’;
while (ch==’y’||ch==’Y’)
{
printf(“Enter num to be written on file : “);
scanf(“%d”,&n);
fclose(fptr);
printf(“file succefully created”);
getch();
}
Output:
If you will observe the file myfile.txt is created in your current drive.
2. Write a program to open file, read from file and display it on monitor.
#include <stdio.h>
#include <stdlib.h>
void main()
Self-Instructional
100 Material
{ Files
3. Write a program to append data in myfile.txt and again open the file
and display the data.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n; //file pointer
FILE *fptr;
char ch=’y’;
clrscr();
fptr = fopen(“myfile.txt”,”a”); / / o p e n f i l e in
append mode
if(fptr == NULL) //check if unable to
open file
{
printf(“Error!Not able to open file”);
Self-Instructional
Material 101
Files exit(1);
}
while (ch==’y’||ch==’Y’)
NOTES {
printf(“Enter number to be append in file “);
scanf(“%d”,&n);
fprintf(fptr,”%d”,n); //write in file
printf(“\nDo you want to add more numbers”);
fflush(stdin);
scanf(“%c”,&ch);
}
fclose(fptr);
printf(“\nfile succefully append and closed “);
fptr=fopen(“myfile.txt”,”r”);
fscanf(fptr,”%d”,&n);
printf(“%d”,n);
getch();
}
Output:
void main () {
FILE *fptr;
fptr = fopen(“myfile.txt”,”w+”);
fputs(“I learned c langauge”, fptr);
Self-Instructional
102 Material
5. Write a program to read file in reverse order and display it. Files
int count = 0;
int i = 0;
char c;
fp = fopen(“myfile.txt”,”r”);
if( fp == NULL )
{
printf(“\n File can not be opened : \n”);
exit(1);
}
getch();
}
Output:
Self-Instructional
Material 103
Files
Try yourself:
(i) Write a program to open a file”mydata.txt” in write mode and write
your name, age and address in file .
NOTES (ii) Write a program to open the file “mydata.txt” in read mode and
display the data present in it.
(iii) Write a program to create file “myinfo.txt” to open file in read and
write mode and write information about your hobbies using string
and display the information from file.
Self-Instructional
104 Material
Files
NOTES
Self-Instructional
Material 105
Files 7. Write a program in c to copy the one file to another using command
line arguments.
#include <stdio.h>
#include <conio.h>
NOTES
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fptr1,*fptr2;
char ch;
clrscr();
if(argc!=3)
{
printf(“\n Enter Two File Names for copyfile \n”);
exit(1);
}
if(argc==3)
{
fptr1 = fopen (argv[1],”r”);
fptr2 = fopen (argv[2],”w”);
if(fptr1==NULL )
{
puts(“\nFile can not be Open...\n”);
exit(1);
}
while((ch=getc(fptr1))!=EOF)
{
putc(ch,fptr2);
putchar(ch);
}
printf(“\n1 File copied \n”);
}
else
{
printf(“\n Now goes to File Menu - DOS Shell option
in TurboC++\n “);
Self-Instructional
106 Material
printf(“\n and then Enter Two File Names for copy Files
\n”);
printf(“\n Press Enter to continue... \n”);
}
NOTES
fclose(fptr1);
fclose(fptr2);
return(1);
}
This program will act as copy command of dos and copy the file1 to file2
Self-Instructional
Material 107
Files Instant Programming card for c language
NOTES
Self-Instructional
108 Material