SlideShare a Scribd company logo
In progress Version
Manual (CS-105)
Programming Fundamentals
Labs Using
C
Language
Compiled by:
Muhammad Sahfiq
DEPARTMENT OF INFORMATION TECHNOLOGYUNIVERSITY OF GUJRAT
2
Contents
Chapter# 1 Basic Concept related to C..................................................................................................7
0.1 A simple program that prints “Hello World” ......................................................................................7
0.2 To use of Escape Squences .................................................................................................................8
0.3 Use of Comments................................................................................................................................9
1.1 Use of Variables.....................................................................................................................................9
1.1.1 To print the values of Two variables..............................................................................................10
1.1.2 To calculate area and circumference of circle using define directive. ..........................................14
1.1.3 To find range of variable underflow and overflow........................................................................14
1.1.4 To swaps two values. ....................................................................................................................15
1.2Use of operators ...................................................................................................................................17
1.2.1 Use of Arithmetic operator............................................................................................................18
1.2.2 Use of compound assignment operators.......................................................................................18
1.2.3 Use of Increment operator with prefix/postfix form.....................................................................19
1.2.4 Use of Decrement operator with prefix/postfix form. ..................................................................19
1.2.5 To find salary on the behalf of working hour and hour week ......................................................20
1.3 Use of Scanf() ......................................................................................................................................17
1.3.1 To print the values of two variables using scanf............................................................................18
1.3.2 To print any character value using scanf. ......................................................................................18
1.3.3 To find salary by getting input such as working hour and hour week...........................................19
1.3.4 To find reverse of any input number. ...........................................................................................19
1.3.5 To find the number is even or odd by using arithmetic operator "%". .........................................20
1.3.6 To find size of different data types................................................................................................18
Chapter# 2 Selection or Conditional structure..................................................................................................17
2.1 Selection structure (IF)................................................................................................................................................17
2.1.1 To find that you have entered exact digit or not...........................................................................17
2.1.2 To find that you have entered exact character or not...................................................................18
2.1.3 To find that entered number is even or odd. ................................................................................18
2.1.4 To find minimum number among from the 3 entered numbers...................................................19
2.1.5 To find minimum number among from the 3 entered numbers...................................................19
2.1.6 To find that user is applicable for scholarship or not ....................................................................20
3
2.1.7 To determine that entered number is Positive or Negative..........................................................23
2.2 Use of logical operators in if statement ................................................................................................................21
2.2.1 To determine that entered character is vowel using OR operator ...............................................23
2.2.2 To find maximum number using AND operator. ...........................................................................24
2.2.3 To determine that number is positive or negative using NOT operator .......................................25
2.2.4 To find eligibility for scholarship using Multiple IF condition........................................................27
2.2.5 To find the square-root of an entered number using if condition. ...............................................25
2.3 Use of If-else.....................................................................................................................................................................24
2.3.1 To find about the entered word correction using if-else...............................................................25
2.3.2 To find that entered number is even or odd using if-else .............................................................26
2.3.3 To determine about leap year using if else condition................................................................27
2.4 Use of If-else-If.................................................................................................................................................................24
2.4.1 To print grade against marks using if-else-if statement ................................................................30
2.5 Swicth statement............................................................................................................................................................39
2.5.1 To determine about day using switch statement..........................................................................30
2.5.2 To find the area or circumference of the circle using switch condition ........................................31
2.5.3 To find the result of arithmetic operators using switch statement...............................................31
2.5.4 To determine about vowels and consonants using switch statement. .........................................34
2.6 Use of Conditional operator.......................................................................................................................................39
2.6.1 To print maximum number using conditional operator. ..............................................................35
2.6.2 To determine that number is even or odd using conditional operator.........................................35
2.6.3 To calculate salary and tells the bonus using conditional operator. .............................................36
chapter# 3 Loop iterations or repetations................................................................................................ 39
3.1 For loop............................................................................................................................................................................. 39
3.1.1 To print the message "Red" 10 times using for loop.....................................................................37
3.1.2 To print all Capital Alphabetic keys using for loop.........................................................................38
3.1.3 To print first five odd numbers using for loop...............................................................................39
3.1.4 To print the sum of given numbers using for loop ........................................................................41
3.1.5 To calculate the square-root given numbers using for loop..........................................................40
3.1.6 To print the table of the given number using for loop ..................................................................40
3.1.7 To find the factorial given number using for loop. .......................................................................41
4
3.1.8 To print a horizontal line of box using for loop..............................................................................41
3.1.9 To print the text within the boxes using multiple for loop............................................................42
3.2 Nested loop.......................................................................................................................................................................39
3.2.1 To print right side diagonal............................................................................................................39
3.2.2 To print left side diagonal..............................................................................................................40
3.2.3 To print the cross sign or symbol...................................................................................................40
3.2.4 To print right side triangle. ............................................................................................................41
3.2.5 To print down-side triangle............................................................................................................41
3.2.6 To print the symbol (#). .................................................................................................................42
3.2.7 To print the sum in a matrix shape using for loop.........................................................................43
3.3 While loop.........................................................................................................................................................................56
3.3.1 To display ASCII value until user will not strike the enter key.......................................................43
3.3.2 To count the character until user does not strike the enter key...................................................44
3.3.3 To prints the number is even or odd until user not strike the “-1”...............................................45
3.3.4 To find the total of 5 numbers.......................................................................................................45
3.3.5 To count characters, words, and digits using while loop...............................................................46
3.4 Do-While Loop.................................................................................................................................................................56
3.4.1 To check marks validation using do while loop .............................................................................51
Chapter# 4 Functions........................................................................................................................................ 56
4.1 To demonstrate about the functions................................................................................................52
4.2 To prints right and left angle triangles using functions. ...................................................................53
4.3 To draws rectangle according to the size of the class room, faculty room, and exam hall..............54
4.4 To convert the upper to lower case and lower to upper letters ......................................................55
4.5 To calculate the difference between time........................................................................................55
4.6 To calculates difference between two dates and result in days ......................................................52
4.7 Using parameterized functions ................................................................................................................................56
To calculate difference between two dates and result in days................. Error! Bookmark not defined.
Chapter # 5 Array……..……………………………………………………………………………………………………………... ……..68
5.1 Basics of Arrays ..…………………………………………………………..………………………………………………………………..68
5.1.1 Declaring and printing Array……………………………..…..…………………………………………………………………….68
5.1.2 Input data in Array from User………………..………..……………………………………………………………………………69
5
5.1.3 Finding sum and Average of an Array………………………………………………….………………………………………..70
5.1.4 Print the values of an array by passing it in function……………………………………………………………………..71
5.1.5 Sorting of an Array………………………………………………………………………………………………………………………..73
5.2 String………………………….……………………………………………………………………………………………………………….73
5.2.1 storing and printing a sentence in string……………………………………………………………………………………….73
5.3 Structure Basic.……………………………………………………………………………………………………………………………74
5.3.1 Declaring structure……………………………………………………………………………………………………………………….74
5.3.2 Storing more than on values in structure………………………………………………………………………………………75
5.4 Array type variables of structure…………………………………………………………………………………………………76
5.4.1 A program which store data of 8 students……………………………………………………………………………………76
Chapter#6 Pointers …………………………………………………………………………………………………………………………..77
6.1 Pointer Basics………………………………………………………………………………………………………………………………77
6.1.1 Direct and indirect value of an variable…………………………………………………………………………………………77
6.1.2Calculating the area and perimeter of a circle………………………………………………………………………………..79
6.2 Pointer of Array…………………………………………………………………………………………………………………………..80
6.2.1 Passing array to function using pointer…………………………………………………………………………………………80
Chapter#7 File Handling…………………………………………………………………………………………………………………….82
7.1 Basics of File handling………………………………………………………………………………………………………………….82
7.1.1 Reading from a file……..…………………………………………………………………………………………………………………82
7.1.2 Writing to a file …………………………………………………………………………………………………………………………….83
7.1.3 Writing data to a file in opened mode…………………………………………………………………………………………..84
7.1.4 File Copying with file Handling………………………………………………………………………………………………………85
7.1.5 Using structure and binary modes in file handling ……………………………………………………………………….86
Chapter#8 Graphics ………………………………………………………………………………………………………………………….88
8.1.1 Initialization and changing background color ……………………………………………………………………………….88
6
8.1.2 Printing text in graphics mode with different colors …………………………………………………………………….89
8.1.3 Printing text at different points…………………………………………………………………………………………………….90
8.1.4 Changing font and direction of text in graphics mode ………………………………………………………………….91
8.1.5 Blinking text in graphics ………………………………………...........................................................................92
8.2 Objects in graphics………………………………………………………………………………………………………………………93
7
Chapter# 1
Basic concept related C language
Program 0.1
A simple program that prints "Hello”.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(" Hello World");
getch();
}
Output:
Program 0.2
To use of Escape sequences.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Hello n World");
printf("Hello t World");
printf("Hello ' World");
printf("Hello " World");
printf("Hello a World");
printf("Hello r World");
getch();
}
Output:
8
Program 0.3
Use f comments.
#include<stdio.h>//Header file
#include<conio.h>//Header file
void main()//main function
{ //body of main
clrscr();//for clear screen
printf("ntUniversty of Gujrat...!n");//for output
printf("ntComputer Science & Information Technology ...!");//n for
new line t for spaces
getch();//for asdf
}//end of body
Output:
1.1 Use of variables
Program 1.1.1
To print values of two variables.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=5;
int b=7;
printf("nt The values of a=%d and b=%d ",a,b);
getch();
}
Output:
Program 1.1.2
To calculate area and circumference of circle using define directive.
#include<stdio.h>
#include<conio.h>
#define pi 3.141593
void main()
{
9
clrscr();
flaot a;
float r;
float c;
r=4.50;
a=2*pi*r*r;
c=2*pi*r;
printf("ntArea: %fntCircumference: %f",a,c);
getch();
}
Output:
Program 1.1.3
To find range of variable underflow and overflow.
#include<stdio.h>
#include<conio.h>
void main()
{
int var=32767;
clrscr();
var=var+1;
printf("t%d",var);
getch();
}
Output:
Program 1.1.4
To swaps two values.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=200;
int b=100;
int swap;
printf("ntBefore swappiing a=%d b=%d",a,b);
swap=a;
10
a=b;
b=swap;
printf("nntAfter swapping a=%d b=%dnn",a,b);
getch();
}
Output:
1.2Use of operators
Program 1.2.1
Use of Arithmetic operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b;
a=10;
b=5;
printf("nta+b = %d",a+b);
printf("nta-b = %d",a-b);
printf("nta*b = %d",a*b);
printf("nta/b = %d",a/b);
getch();
}
Output:
Program 1.2.2
Use of compound assignment operators.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
11
int a,b;
a=10;
printf("ntValue of a= %d",a);
a+=5;
printf("ntValue after a+=5: %d",a);
a-=5;
printf("ntValue after a-=5: %d",a);
a*=2;
printf("ntValue after a*=2: %d",a);
a/=2;
printf("ntValue after a/=2: %d",a);
getch();
}
Output:
Program 1.2.3
Use of Increment operator with prefix/postfix form.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,x;
a=b=0;
printf("nta=%d, b=%d, ",a,b);
x=++a;
printf("ntPrefix Increment: a=%d, x=%d",a,x);
x=b++;
printf("ntPostfix Increment: b=%d, x=%d",b,x);
getch();
}
Output:
12
Program 1.2.4
Use of Decrement operator with prefix/postfix form.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,x;
a=b=2;
printf("nta=%d, b=%d, ",a,b);
x=--a;
printf("ntPrefix Decrement: a=%d, x=%d",a,x);
x=b--;
printf("ntPostfix Decrement: b=%d, x=%d",b,x);
getch();
}
Output
Program 1.2.5
To find salary on the behalf of working hour and hour week
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float hr;
float hw;
float pay;
hr=150.00;
hw=15.30;
pay=hr*hw;
printf("t%f",pay);
getch();
}
Output:
1.3 Use of Scanf()
13
Program 1.3.1
T o print the values of two variables using scanf .
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a;
int b;
printf("ntEnter first value=");
scanf("%d",&a);
printf("ntEnter Second value=");
scanf("%d",&b);
printf("ntThe values of a= %d and b= %d ",a,b);
getch();
}
Output:
Program 1.3.2
To print any character value using scanf.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("ntEnter a char:t");
scanf("%c",&ch);
printf("ntThe char is:t%c",ch);
getch();
}
14
Output:
Program 1.3.3
To find salary by getting input such as working hour and hour week.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float hr;
float hw;
float pay;
printf("ntEnter hour rate:");
scanf("%f",&hr);
printf("ntEnter working hour:");
scanf("%f",&hw);
pay=hr*hw;
printf(" n tYour Pay is:%f",pay);
getch();}
Output:
Program 1.3.4
To find reverse of any input number.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,a,s,d;
printf("tEnter 4-digit number: ");
scanf("%d",&n);
a=n/1000;
n=n%1000;
s=n/100;
n=n%100;
15
d=n/10;
n=n%10;
printf("ntNumber in Revrse order: %d%d%d%d",n,d,s,a);
getch();
}
Output:
Program 1.3.5
To find the number is even or odd by using arithmetic operator "%".
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b;
printf("ntEnter a Number:");
scanf("%d",&a);
b=a%2;
printf("ntNote:nt If the value is 0 then given number is EVEN");
printf("nt If the value is 1 then given number is ODD");
printf("nntThe Value is=%d",b);
getch();
}
Output:
Program 1.3.6
To find size of different data types.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("ntThe size of char: %d",sizeof(char));
printf("ntThe size of int: %d",sizeof(int));
16
printf("ntThe size of float: %d",sizeof(float));
printf("ntThe size of long: %d",sizeof(long));
printf("ntThe size of double: %d",sizeof(double));
printf("ntThe size of long double: %d",sizeof(long double));
getch();
}
Output :
Exercise:
1. Write a program to check the sizes of the main C data types on your machine.
2. Write a program to illustrate whether the printf() standard library function truncates or rounds
when printing out a floating point number.
3. Write a program to check what the following code segment outputs and explain the results.
char c ;
printf("sizeof( c ) = %dn", sizeof( c ) ) ;
printf("sizeof( 'a' ) = %dn", sizeof( 'a' ) ) ;
printf("sizeof( c = 'a' ) = %dn", sizeof( c='a' ));
4. Run the "hello world" program on your system. Experiment with leaving out parts of the
program, to see what error messages you get.
5. Experiment to find out what happens when printf 's argument string contains c, where c is
some character not listed above.
6. Write a program which reads a character from the keyboard and writes out its ASCII
representation.
7. Now write a program which reads in an integer from the keyboard and print out its character
representation. Make certain you carry out appropriate bounds / error checking.
8. Write a program to read Fahrenheit temperatures and print them in Celsius. The formula is
C = (5/9)(F - 32). Use variables of type double in your program.
9. Write a program that reads in the radius of a circle and prints the circle‟s diameter,
circumference and area. Use the value 3.14159 for “pi”.
10. Write a program to print all input lines that are longer than 80 characters.
17
Chapter# 2
Selection structure:
2.1 Selection structure (IF)
Program 2.1.1
To find that you have entered exact digit or not .
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num;
printf(“ntEnter digit (5): “);
scanf(“%d”,&num);
if(num==5)
printf("ntYou have entered 5");
getch();
}
Output:
Program 2.1.2
To find that you have entered exact character or not .
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char ch,chh;
printf("ntEnter characters „n‟:");
ch=getche();
if(ch=='n')
printf("ntYou have entered 'n' ");
getch();
}
18
Output:
Program 2.1.3
To find that entered number is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num;
printf("ntEnter a number:");
scanf("%d",&num);
if(num%2==0)
printf("tThe number you have entered is Even.!!!");
if(num%2==1)
printf("tThe number you have entered is Odd.!!!");
getch();
}
Output:
Program 2.1.4
To find minimum number among from the 3 entered numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c,d,e,min;
printf("ntEnter a:");
scanf("%d",&a);
printf("ntEnter b:");
scanf("%d",&b);
printf("ntEnter c:");
scanf("%d",&c);
min=a;
if(b<min)
min=b;
19
if(c<min)
min=c;
printf("ntt Minimum Value is: %d",min);
getch();
}
Output:
Program 2.1.5
To find minimum number among from the 3 entered numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c,max;
printf("ntEnter a:");
scanf("%d",&a);
printf("ntEnter b:");
scanf("%d",&b);
printf("ntEnter c:");
scanf("%d",&c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf("nttMaximum Value is: %d",max);
getch();
}
Output:
20
Program 2.1.6
To find that user is applicable for scholarship or not.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float gpa,cgpa;
printf("ntEnter GPA:");
scanf("%f",&gpa);
printf("ntEnter CGPA:");
scanf("%f",&cgpa);
if(gpa>=3.0)
if(cgpa>=3.0)
printf("ntCongartualtions...!!!n t You will get full scholorship");
getch();
}
Output:
Program 2.1.7
To determine that entered number is Positive or Negative.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n;
printf("ntEnter a Number: ");
scanf("%d",&n);
if(n>0)
printf("ntNumber is Positive..!");
if(n<0)
printf("ntNumber is Negative..!");
getch();
}
Output:
21
2.2 Use of logical operators in if statement
Program 2.2.1
To determine that entered character is vowel using OR operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
printf("ntEnter any character: ");
scanf("%ch",&ch);
if(ch=='A'||ch=='a'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U')
printf("ntYour entered a vowel: %c",ch);
getch();
}
Output:
Program 2.2.2
To find maximum number using AND operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c;
printf("ntEnter a: ");
scanf("%d",&a);
printf("ntEnter b: ");
scanf("%d",&b);
printf("ntEnter c: ");
scanf("%d",&c);
if((a>b)&&(a>c))
printf("ntMaximum number is: %d",a);
if((b>c)&&(b>a))
printf("ntMaximum number is: %d",b);
22
if((c>a)&&(c>b))
printf("ntMaximum number is: %d",c);
getch();
}
Output:
Program 2.2.3
To determine that number is positive or negative using NOT operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n;
printf("ntEnter a Number: ");
scanf("%d",&n);
if(!(n>0))
printf("ntNumber is Negative..!");
if(!(n<0))
printf("ntNumber is Positive..!");
getch();
}
Output:
Program 2.2.4
To find eligibility for scholarship using Multiple IF condition.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float cgpa;
23
int age;
char status, gender,grade;
printf("ntEnter the CGPA 3.0 almost:");
scanf("%f",&cgpa);
printf("ntEnter the age 25 almost:");
scanf("%d",&age);
printf("ntEnter the status as Reglar press 'R':");
status=getche();
printf("nntEnter the Gender 'M' for male and 'F' for female.:");
gender=getche();
printf("nntEnter the Grade.:");
grade=getche();
if(cgpa>=3.0&&age<=25)
if(status=='r'||status=='R')
if(gender=='M'||gender=='F'||gender=='m'||gender=='f')
if(grade=='A'||grade=='a')
printf("nn Congratulations...!!!! You will get scholorship..");
getch();
}
Output:
Program 2.2.5
To find the square-root of an entered number using if condition.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int n;
float sqroot;
printf("ntEnter a number:");
scanf("%d",&n);
if(n>0)
sqroot=sqrt(n);
printf("tThe sqroot of %d is %f",n,sqroot);
getch();
}
24
Output:
2.3 Use of If-else
Program 2.3.1
To find about the entered word correction using if-else.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
printf("ntEnter a character (y): ");
ch=getche();
if(ch=='Y'||ch=='y')
printf("ntYou have enter Y");
else
printf("ntYou have entered another word");
getch();
}
Output:
Program 2.3.2
To find that entered number is even or odd using if-else
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num;
printf("nn Enter a number:");
scanf("%d",&num);
if(num%2==0)
printf("The number you have entered is Even.!!!");
else
printf("The number you have entered is Odd.!!!");
getch();
}
25
Output:
Program 2.3.3
To determine about leap year using if else condition.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int num;
printf("ntEnter year in the format of 0000:");
scanf("%d",&num);
if(num%4==0)
printf("ntThe Year which you have entered Leap Year.!!!");
else
printf(“ntIts no Leap year..!!!”);
getch();
}
Output:
2.4 Use of If-else-If
Program 2.4.1
To print grade against marks using if-else-if statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int marks;
printf("ntEnter Marks:");
scanf("%d",&marks);
if(marks>=80&&marks<=100)
printf("ntYou have obtained Grade 'A' ");
else if(marks>=70&&marks<=79)
26
printf("ntYou have obtained Grade 'B' ");
else if(marks>=60&&marks<=69)
printf("ntYou have obtained Grade 'C' ");
else if(marks>=50&&marks<=59)
printf("ntYou have obtained Grade 'D' ");
else
printf("nt Grade 'F' ");
getch();
}
Output:
2.5 Switch Statement
Program 2.5.1
To determine about day using switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("ntEnter a Day number:");
scanf("%d",&n);
switch(n)
{
case 1:
printf("ntFriday");
break;
case 2:
printf("ntSaturday");
break;
case 3:
printf("ntSunday");
break;
case 4:
printf("ntMonday");
break;
case 5:
printf("ntTuesday");
break;
case 6:
printf("ntWednesday");
break;
27
case 7:
printf("ntThursday");
break;
default:
printf("ntInvalid Day number.");
}
getch();
}
Output:
Program 2.5.2
To find the area or circumference of the circle using switch condition.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float a,c,r;
int num;
printf("ntEnter a number=t 1 for area and 2 for circumference:");
scanf("%d",&num);
printf("ntEnter the Radius:");
scanf("%f",&r);
switch(num)
{
case 1:
printf("ntFor Area.:");
a=3.1416*r*r;
printf("ntThe Area is:%f",a);
break;
case 2:
printf("ntFor Circumference.:");
c=2*3.1416*r;
printf("ntThe Circumference is:%f",c);
break;
default:
printf("ntWrong Number you have entered");
}
getch();
}
28
Output:
// OR
Program 2.5.3
To find the result of arithmetic operators using switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float a,b,c;
char optr;
printf("ntEnter choice + - * / %: ");
scanf("%c",&optr);
printf("ntEnter first value: ");
scanf("%f",&a);
printf("ntEnter second value: ");
scanf("%f",&b);
switch(optr)
{
case '+':
c=a+b;
printf("ntThe Addition is:%f",c);
break;
case '-':
c=a-b;
printf("ntThe Subtration is:%f",c);
break;
case '*':
c=a*b;
29
printf("ntThe Multiplication is:%f",c);
break;
case '/':
c=a/b;
printf("ntThe Division is:%f",c);
break;
case '%':
c=int(a)%int(b);
printf("ntThe Modulus is:%d",c);
break;
default:
printf("ntWrong Operator..!!!!");
}
getch();
}
Output:
Program 2.5.4
To determine about vowels and consonants using switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char letter;
printf("ntEnter a letter:);
scanf("%c",&letter);
switch(letter)
{
case „a‟:
case „A‟:
case „e‟:
case „E‟:
case „i‟:
case „I‟:
case „o‟:
case „O‟:
case „u‟:
case „U‟:
printf("ntYou have entered a Vowel");
break;
30
default:
printf("ntYou have entered Consonant");
getch();
}
Output:
2.6 Use of conditional operator
Program 2.6.1
To print maximum number using conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num1,num2,result;
printf("ntEnter first number: ");
scanf("%d",&num1);
printf("ntEnter second number: ");
scanf("%d",&num2);
//result=(num1>num2)?1:0;
result=(num2<num1)?printf("ntFirst number is
greater"):printf("ntSecond number is greater");
getch();
}
Output:
Program 2.6.2
To determine that number is even or odd using conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,reslt;
clrscr();
printf("ntEnter a number: ");
31
scanf("%d",&num);
//reslt=(num%2==0)? 0:1;
reslt=(num%2==0)? printf("ntEven"):printf("ntOdd");
getch();
}
Output:
Program 2.6.3
To calculate salary and tells the bonus using conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float sal,bonus,rsal,result;
printf("ntEnter Your current Salary Please:");
scanf("%f",&sal);
result=(sal>10000)?printf("ntYour Bonus is 10%"):printf("ntYour Bonus is 5%");
bonus=sal*10/100;
printf("nntYou will get %f bonus.",bonus);
rsal=sal+bonus;
printf("nntYour revised salary is:%f",rsal);
getch();
}
Output:
32
Exercise of chapter 2:
1. Write a program which prints out the ASCII and hex values of all characters input at the
keyboard terminating only when the character `q' or `Q' is entered.
2. Write a program to keep count of the occurrence of a user specified character in a
stream of characters of known length (e.g. 50 characters) input from the keyboard.
Compare this to the total number of characters input when ignoring all but alphabetic
characters.
Note: The ASCII values of 'A'...'Z' are 65...90 and 'a'...'z' are 97...122.
3. Write a program to find the roots of a user specified quadratic equation. Recall the roots
of ax bx c 02
   are
-b b 4ac
2a
2
 
The user should be informed if the specified quadratic is valid or not and should be
informed how many roots it has, if it has equal or approximately equal roots (b2
==
4ac), if the roots are real (b2
- 4ac > 0) or if the roots are imaginary (b2
- 4ac < 0). In the
case of imaginary roots the value should be presented in the form (x + i y).
Note that C has a standard library function sqrt( ), which returns the square root of its
operand, and whose prototype can be found both in the help system.
4. Write a program that allows the user to read a user specified number of double precision
floating point numbers from the keyboard. Your program should calculate the sum and
the average of the numbers input. Try and ensure that any erroneous input is refused by
your program, e.g. inadvertently entering a non-numeric character etc.
5. Write and simulate a program using the C language:
- Input 1 lowercase ASCII letter (between „a‟ and „z‟)
- Change lowercase ASCII letter to uppercase ASCII letter.
- Output them on screen.
6. Write a program that prompts the user for a string, and prints its reverse.
7. Write a C program which converts the number in seconds to hour, minute and seconds.
If the number is less than 1000, the program should print the message “You should enter
an integer number greater than or equal to 1000”
Sample runs:
Enter the number of seconds> 7322
7322 seconds is equivalent to 2 hours 2 minutes 2 seconds.
Enter the number of seconds> 500
You should enter an integer number greater than or equal to 1000
8. Write a program that reads in five integers and then determines and prints the largest
and the smallest integers in the group. Use only the programming techniques you have
learned in the lecture.
Sample run:
Input 5 integers: 9 4 5 8 7
The largest value is 9
33
The smallest value is 4
9. Write a C program that reads three nonzero integers and determines and prints if they
could be the sides of a right triangle. [Hint: Use Pythagorean Theorem]
Sample runs:
Enter three integers: 3 4 5
The three integers are the sides of a right triangle
Enter three integers: 5 3 4
The three integers are the sides of a right triangle
Enter three integers: 9 4 1
The three integers are not the sides of a right triangle
10. Write a program that reads an integer from keyboard. Assuming it is the number of
month of the year, print out the name of that month. Your program should also check
that the number is a valid month number. If it is not a valid number, you should print a
warning message.
Sample runs:
Enter the month number> 11
NOVEMBER
Enter the month number> 13
Not a valid month number!
34
Chapter# 3
Loop iterations or repetitions
3.1 For loop
Program 3.1.1
To print the message "Red" 10 times using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for (int t=0; t<10; t++)
printf("tRed n");
getch();
}
Output:
Program 3.1.2
To print all Capital Alphabetic keys using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
for(ch='A';ch<='Z';ch++)
printf("%c ",ch);
getch();
}
35
Output:
Program 3.1.3
To print first five odd numbers using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int num=1;num<=10;num+=2)
printf("%d",num);
getch();
}
Output:
Program 3.1.4
To print the sum of given numbers using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int j,k,sum,n;
printf("ntEnter serial numbers:");
scanf("%d",&n);
sum=0;
printf("ntIntegertt sum");
for(j=1;j<=n;j++)
{
sum=sum+j;
printf("nt %dtt %d",j,sum);
}
getch();
}
36
Output:
Program 3.1.5
To calculate the square-root given numbers using for loop.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
float j,sq,n;
printf("ntEnter serial numbers:");
scanf("%f",&n);
printf("tIntegertt Square root");
for(j=1;j<=n;j++)
{
sq=sqrt(j);
printf("nt %f",j);
printf("t %f",sq);
}
getch();
}
Output:
Program 3.1.6
To print the table of the given number using for loop.
#include<stdio.h>
#include<conio.h>
void main()
37
{
clrscr();
int c,r;
printf("ntEnter a number:");
scanf("%d",&c);
for(int n=1;n<=10;n++)
{
printf(“t”);
r=n*c;
printf("%d*%d=%dn",c,n,r);
}
getch();
}
Output:
Program 3.1.7
To find the factorial given number using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,f;
printf("ntEnter number: ");
scanf("%d",&n);
f=1;
for(int c=n;c>=1;c--)
{
f=f*c;
}
printf("ntThe Factorial is: %d",f)
getch();
}
38
Output:
Program 3.1.8
To print a horizontal line of box using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“t”);
for (int t=0; t<10; t++)
{
printf("=");
}
getch();
}
Output:
Program 3.1.9
To print the text within the boxes using multiple for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1;i<=24;i++)
{
printf("#");
}
printf("n");
printf("# University Of Gujrat #n");
for(int j=1;j<=24;j++)
{
printf("#");
}
printf("n");
getch();
}
39
Output:
3.2 Nested loop
Program 3.2.1
To print right side diagonal.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int outer=7;outer>=1;outer--)
{
for(int inner=1;inner<=outer;inner++)
{
printf(" ");
}
printf("#");
printf("n");
}
getch();
}
Output:
Program 3.2.2
To print left side diagonal.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int outer=1;outer<=7;outer++)
{
for(int inner=1;inner<=outer;inner++)
{
printf(" ");
40
}
printf("#");
printf("n");
}
getch();
}
Output:
Program 3.2.3
To print the cross sign or symbol.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
if(i==j||(i+j)==11)
printf("#");
else printf(" ");
printf("n");
}
getch();
}
Output:
41
Program 3.2.4
To print right side triangle.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int outer=1;outer<=7;outer++)
{
for(int inner=1;inner<=outer;inner++)
{
printf("#");
}
printf("n");
}
getch();
}
Output:
Program 3.2.5
To print down-side triangle.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int outer=7;outer>=1;outer--)
{
for(int inner=1;inner<=outer;inner++)
{
printf("#");
}
printf("n");
}
getch();
}
Output:
42
Program 3.2.6
To print the symbol (#).
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(i*j%2==0)
printf("=");
else
printf(" ");
}
printf("n");
}
getch();
}
Output:
Program 3.2.7
To print the sum in a matrix shape using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1;i<=5;i++)
{
printf(“t”);
for(int j=1;j<=5;j++)
{
43
printf("%d",i+j);
}
printf("n");
}
getch();
}
Output:
3.3 While loop
Program 3.3.1
To display ASCII value until user will not strike the enter key.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char ch='a';
while(ch!='r')
{
printf("n Enter Character:");
ch=getche();
printf("nn The ASCII value of %c=%d",ch,ch);
}
getch();
}
Output:
Program 3.3.2
To count the character until user does not strike the enter key.
#include<stdio.h>
#include<conio.h>
44
void main()
{
clrscr();
int count=0;
printf("ntEnter Phrase:");
while(getche()!='r')
{
count++;
}
printf("ntNumber of Characters= %d",count);
getch();
}
Output:
Program 3.3.3
To prints the number is even or odd until user not strike the “-1”.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int i;
while(i!=-1)
{
printf("ntEnter a Number:");
scanf("%d",&i);
if((i%2)==0)
{
printf("ntNumber is even");
}
else
printf("ntNumber is Odd");
}
getch();
}
45
Output:
Program 3.3.4
To find the total of 5 numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int total=0;
int count=0;
while(count<=4)
{
total=total+count;
count++;
printf("nt %d",total);
}
getch();
}
Output:
Program 3.3.5
To count characters, words, and digits using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int wc=0;
46
int cc=-1;
int dc=0;
char ch;
printf("ntEnter Phrase: ");
while(ch!='r')
{
ch=getche();
if(ch==' ')
wc++;
else if(ch>=48&&ch<=57)
dc++;
else
cc++;
}
printf("nntTotal Characters %d,Total Words %d,Total Digits %d",cc,++wc,dc);
getch();
}
Output:
3.4 Do-While loop
Program 3.4.1
To check marks validation using do while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int score;
do
{
printf("ntEnter Marks: ");
scanf("%d",&score);
if(score<0||score>100)
printf("ntInvalid score, you have entered.!!! nntPlease Enter Valid Marks b/w (1-
100)..");
}
while(score<0||score>100);
if(score>=90&&score<=100)
printf("ntA grade");
else if(score>=80&&score<=90)
printf("ntB grade");
47
else if(score>=70&&score<=80)
printf("ntC grade");
else if(score>=60&&score<=70)
printf("ntD grade");
else if(score>=50&&score<=60)
printf("ntE grade");
else
printf("ntFail");
getch();
}
Output:
Exercise of Chapter 3:
1. Write a program to print out all the Fibonacci numbers using short integer variables until the
numbers become too large to be stored in a short integer variable i.e. until overflow occurs.
a. Use a for loop construction.
b. Use a while loop construction.
Note: Fibonacci numbers are (1,1,2,3,5,8,13,...
2. Write a program which simulates the action of a simple calculator. The program should take
as input two integer numbers then a character which is one of +,-,*,/,%. The numbers should
be then processed according to the operator input and the result printed out. Your program
should correctly intercept any possible erroneous situations such as invalid operations, integer
overflow, and division by zero.
3. Write a program that prompts the user for a sentence, and prints each word on its own line.
4. Write a function that outputs a right isosceles triangle of height and width n, so n = 6 would
look like
*
**
***
****
*****
******
48
5. Write a function that outputs a sideways triangle of height 2n-1 and width n, so the output for
n = 4 would be:
*
**
***
****
***
**
*
6. Write a function that outputs a right-side-up triangle of height n and width 2n-1; the output for
n = 6 would be
*
***
*****
*******
*********
***********
7. Write a function to calculate if a number is prime. Return 1 if it is prime and 0 if it is not a
prime.
8. Execute the following code and look at the result and then try to change the code in some
way.
(1)
void main(){
char i;
clrscr();
for(i=120;i<=128;i++){
printf("%d ",i);
}
getch();
}
Output: Infinite loop
(2)
void main(){
int i;
clrscr();
for(i=0,i++,i<=5;i++,i<=2;i=0,i<=5,i+=3){
printf("%d ",i);
}
getch();
}
Output: 2
(3)
49
void main(){
int i=1;
clrscr();
for(;;){
printf("%d ",i);
}
getch();
}
Output: Infinite loop
(4)
void main(){
int i=2;
clrscr();
for(i=0;i<=3;i++){
static int i;
i=i+8;
}
printf("%d",i);
getch();
}
Output: 4
(5)
extern int j;
void main(){
int i=0;
clrscr();
for(i=0;i<=2;i+=1){
int j=5;
printf("%d ",j);
j++;
}
getch();
}
int j=25;
Output: 5 5 5
(6)
extern int j;
void main(){
int i=0;
clrscr();
for(i=0;i<=2;i+=1){
int j=5;
printf("%d ",j);
j++;
50
}
getch();
}
int j=25;
Output: 5 5 5
51
Chapter# 4
Functions:
Program 4.1
To demonstrate about the functions.
#include<stdio.h>
#include<conio.h>
void drawline(void);
void main()
{
clrscr();
drawline();
printf("nt#University Of Gujrat#n");
drawline();
printf("n");
drawline();
printf("n");
printf("t# Faculty of Cs & It #n");
drawline();
getch();
}
void drawline(void)
{
printf("t");
for(int i=1;i<=22;i++)
printf("#");
}
Output:
Program 4.2
52
To prints right and left angle triangles using functions.
#include<stdio.h>
#include<conio.h>
void leftangle(void);
void rightangle(void);
void main()
{
clrscr();
leftangle();
rightangle();
getch();
}
void leftangle(void)
{
for(int i=1;i<=7;i++)
{
printf(“t”);
for(int j=1;j<=i;j++)
printf("#");
printf("n");
}
}
void rightangle(void)
{
for(int k=7;k>=1;k--)
{
printf(“t”);
for(int l=1;l<=k;l++)
printf("#");
printf("n");
}
}
Output:
Program 4.3
53
To draws rectangle according to the size of the class room, faculty room, and exam
hall using functions.
#include<stdio.h>
#include<conio.h>
void drawline(int width,int length);
void main()
{
clrscr();
printf("tClass room:n");
drawline(4,9);
printf("tFaculty room:n");
drawline(5,7);
printf("tExam Hall:n");
drawline(5,16);
getch();
}
void drawline(int width,int length)
{
for(int a=1;a<=width;a++)
{
printf("tt");
for(int b=1;b<=length;b++)
printf("#");
printf("n");
}
}
Output:
Program 4.4
To convert the upper to lower case and lower to upper letters.
#include<stdio.h>
#include<conio.h>
char getlc(void);
54
void main()
{
clrscr();
char ch;
printf("ntEnter UpperCase Letter: ");
ch=getlc();
printf("ntResult in lower case letter is:%c",ch);
printf("ntEnter lower Case Letter: ");
ch=getlc();
printf("ntResult in lowe case letter is: %c",ch);
getlc();
getch();
}
char getlc(void)
{
char ch;
ch=getche();
if(ch>=65&&ch<=90)
ch=ch+32;
else
ch=ch-32;
return(ch);
}
Output:
Program 4.5
To calculate the difference between time.
#include<stdio.h>
#include<conio.h>
int getmint(void);
void main()
{
clrscr();
int mint1,mint2;
printf("ntEnter first time(hour:minutes):");
mint1=getmint();
printf("ntEnter second time(hour:minutes):");
mint2=getmint();
printf("ntDifference in Minutes %d",mint2-mint1);
getch();
55
}
int getmint(void)
{
int hour,minut;
scanf("%d:%d",&hour,&minut);
return(hour*60+minut);
}
Output:
Program 4.6
To calculates difference between two dates and result in days.
#include<stdio.h>
#include<conio.h>
int ageday(void);
void main()
{
clrscr();
int d1,d2;
printf("ntEnter first date format year-month-day (5-3-10):");
d1=ageday();
printf("ntEnter Second date format year-month-day (3-3-10):");
d2=ageday();
printf("ntDifference in Days: %d",d2-d1);
getch();
}
int ageday(void)
{
int year,month,days;
scanf("%d-%d-%d",&year,&month,&days);
return((year*365)+(month*30)+days);
}
Output:
56
4.1 Using parameterized functions
Program 4.1.1
To calculate difference between two dates and result in days.
#include<stdio.h>
#include<conio.h>
int ageday(int year,int month,int days);
void main()
{
int d1,d2;
printf("ntThe first date is: 2003-03-10");
d1=ageday(03,03,10);
printf("ntThe Second date is: 2005-03-10):");
d2=ageday(05,03,10);
printf("nntDifference in Days: %d",d2-d1);
getch();
}
int ageday(int year,int month,int days)
{
return((year*365)+(month*30)+days);
}
Output:
Exercise:
1. Write a program that can convert temperatures from the Fahrenheit scale to Celsius and
back. The relationship is C = (5/9)(F - 32). Your program should read a temperature and
which scale is used and convert it to the other, printing out the results. Write one or more
functions to carry out the actual conversion.
2. Write a program that reads in the radius of a circle and prints the circle‟s diameter,
circumference and area. Write functions for appropriate logical tasks in your program. You
should #define all appropriate constants in your program.
3. Write and test a function to convert an unsigned integer to binary notation. Use the sizeof
operator to make the program machine independent i.e. portable.
4. Write and test two functions, one that packs two character variables into one integer variable
and another which unpacks them again to check the result.
57
5. Write and test a circular shift left function for one byte unsigned variables i.e. unsigned
characters.
e.g. 10011100 circular shift left by 2 yields 01110010.
6. An integer is said to be prime if it is divisible only by one and itself. Write a function which
determines whether an integer is prime or not. To test your function write a program that prints
out all prime numbers between 1 and 10,000.
7. Write and test a function to read in a signed integer from the standard input device. Your
function should not be allowed to use the scanf function. The function should have the prototype
int getint( void ) ;
and should be able to accommodate the presence of a minus sign, a plus sign or no sign ( i.e.
positive by default ). Note that the ASCII values of the digits 0 - 9 are consecutive, 48 - 57 and
that if we wish to convert the digit „3‟ for example to an integer we simply subtract the ASCII
value of digit „0‟ from its ASCII value i.e. „3‟ - „0‟ = 51 - 48 = 3.
8. Write and test a function to get a floating point number from the standard input device. The
function should have the prototype
float getfloat( void ) ;
and should be able to accommodate normal floating point notation and exponential notation.
You should make use of the getint() function in exercise 5. to read in the various components of
the floating point number.
9. Write and test a function
double power ( double x, int n );
to calculate the value of x raised to the power of n.
(a) Use your own calculations.
(b) Use the standard library function pow() ( for more information use help system )
paying particular attention to type compatibilities.
10. Write a recursive function to calculate and print out all the Fibonacci values up to and
including the nth
. Recall that the Fibonacci series is 1, 1, 2, 3, 5, 8, 13, ... .To test your program
allow the user to enter the value of n and then print out the series. The program should run
continuously until it is explicitly terminated by the user.
58
Chapter# 5
Arrays:
5.1 Basics of Array
Program 5.1.1
Declaring and printing an array.
#include<conio.h>
#include<stdio.h>
void main()
{
/*declaration and printing an Array*/
clrscr();
/*initializing array without passing the number of subscripts*/
int arr[]={25,30,20,10,35,45};
/*initialization of array with declaring the size*/
int arr1[4]={40,10,5,50};
for(int i=0;i<=5;i++) //printing the array 1
{
printf("The Element no %d is %dn",i+1,arr[i]);
}
for( i=0;i<4;i++)
{
printf("Member %d is %dn",i+1,arr1[i]);
}
getch();
}
Output:
Program 5.1.2
Input data in an array from user.
59
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
/*asking user to input data in array.*/
int arr[5]; //declaring the number of indexes is compulsory here.
for(int i=0;i<5;i++)
{
printf("Enter the number %d: ",i+1);
scanf("%d",&arr[i]);
printf("n");
}
for(i=0;i<=4;i++)
{
printf("Number %d is %d n",i+1,arr[i]);
}
getch();
}
Output:
Program 5.1.3
Finding sum and average of an array members.
#include<stdio.h>
#include<conio.h>
void main()
{
/*Finding sum and average of Array members.*/
clrscr();
int sum=0;
float avg;
int marks[5];
for(int i=0;i<5;i++)
{
60
printf("Enter the marks in subject %d ",i+1);
scanf("%d",&marks[i]);
printf("n");
}
for(i=0;i<=4;i++)
{
sum=sum+marks[i];
}
printf("Sum is %d. n",sum);
avg=sum/5.0;
printf("Average is %f ",avg);
getch();
}
Output:
Program 5.1.4
Print the values of an array bay passing it in function.
#include<conio.h>
#include<stdio.h>
void display(int a);
void main()
{
/*printing the values of array by passing into the function*/
clrscr();
int arr[5];
for(int j=0;j<5;j++)
{
printf("Enter the number %d ",j+1);
scanf("%d",&arr[j]);
printf("n");
}
for(int i=0;i<=4;i++)
{
display(arr[i]); //Passing array members by value
}
61
getch();
}
void display(int a)
{
printf("%dn",a);
}
Output:
Progr5.1.5
Sorting of an array .
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int arr[5];
for(int a=0;a<=4;a++)
{
printf("Enter the number %d: ",a+1);
scanf("%d",&arr[a]); //scanning the value of array.
}
clrscr();
printf("nn Array before sorting is ");
for(a=0;a<=4;a++)
{
printf("%d ",arr[a]); //printing the value of array before sorting.
}
int temp;
printf("nn After sorting, it is t ");
for(int i=0;i<=4;i++)
{
for(int j=i;j<=4;j++)
{
if(arr[i]>arr[j]) //Decision making
{
temp=arr[i];
62
arr[i]=arr[j]; //values interchanging
arr[j]=temp;
}
}
}
for(int c=0;c<=4;c++) //Final loop
{
printf("%d ",arr[c]); //printing the list after sorting...
}
getch();
}
Output:
5.2 String
5.2.1
Storing and printing a sentence using string.
#include<conio.h>
#include<stdio.h>
void main()
{clrscr();
char name[100];
printf("nEnter any sentence nn");
gets(name);
printf("nYou Enter nn");
puts(name);
getch();
}
Output:
63
5.3 Structure Basics
Program 5.3.1
Declaring structure
#include<conio.h>
#include<stdio.h>
struct xyz
{
char name[10];
};
void main()
{
Clrscr();
xyz name;
printf(“n Enter any sentence without space…….n”);
scanf(“%s”,&name.name);
getch();
}
Output:
Program 5.3.2
Storing more then one values in a structure.
#include<conio.h>
#include<stdio.h>
struct xyz
{
char name[100],address[1000];
int number;
};
void main()
{
64
Clrscr();
xyz name;
printf("nEnter Name of person = ");
gets(name.name);
printf("nEnter Adress of person = ");
gets(name.adress);
printf("nEnter Mobile number of person = ");
scanf("%d",&name.number);
printf("nEntered Name = ");
puts(name.name);
printf("nEntered Adress = ");
puts(name.adress);
printf("nEntered Mobile number = %d",name.number);
getch();
}
Output:
5.4 Array type variable and members of Structure
Program 5.4.1
A program which stores data of 8 students.
#include<conio.h>
#include<stdio.h>
struct rec
{
int sub[6],sum;
float av_stu;
};
void main()
{clrscr();
int i,j;
float av_class=0.0; :
rec student[8];
for(i=0;i<=7;i++)
{student[i].sum=0;
printf("nStudent # %d",i+1);
for(j=0;j<=5;j++)
65
{
printf("nEnter marks of subject %d = ",j+1);
scanf("%d",&student[i].sub[j]);
student[i].sum=student[i].sum+student[i].sub[j];
}
student[i].av_stu=student[i].sum/6.0;
printf("nAverage of student # %d = %.2f ",i+1,student[i].av_stu);
av_class=av_class+student[i].av_stu;
}
av_class=av_class/8.0;
printf("nnAverage Class = %.2f",av_class);
getch();
}
Output:
66
Exercise:
1. Write a program in C to read a set of numbers and store in one-dimensional array and
then to find the largest and the smallest number. Find also the difference between the
two numbers.
2. Write a program in C that uses array to store the telephone no. of 20 students against
their roll no. Input a Roll no, and then search the arrays for the student‟s telephone
number.
3. Find the sum of the numbers of an array
4. Find the highest value in an array
5. Linear Search Technique in an array
6. Write a C program to bubble sort.
7. Write a C program to Selection Sort.
8. Write a C program to Insertion sort.
9. Write a C program to accept a sting as input and convert the lower case letters to
uppercase & vice-versa of that string.
10. Write a program in C to find the number of vowels in each word of a given text using
pointer.
11. String Operation using array:String Copy, catenation, compare, find length
12. Write a C program to accept a sting as input and convert the lower case letters to
uppercase & vice-versa of that string.
13. Write a program in C to read a set of names, roll number, gender, height and weight of
the student from the keyboard and to sort them in an ascending order of name using a
structure.
67
Chapter# 6
Pointers:
6.1 pointer Basics
Program 6.1.1
Direct and indirect value of an variable.
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
/* Basics Of Pointer */
int a=10;
int *ap=&a;
printf("Value in A is %dn",a);
printf("Address of A is %dn",&a);
printf("Indirect value of A is %dn",*ap);
printf("Indirect adderss of A is %dn",ap);
printf("Address of pointer is %dn",&ap);
getch();
}
Output:
Program 6.1.2
Printing the values call by reference and call by value .
#include<conio.h>
#include<stdio.h>
void disp1(int a, int b);
void disp2(int *a, int *b);
void main()
{
clrscr();
/*Pointer Introduction*/
int a=10,b=21;
68
disp1(a,b);
disp2(&a,&b);//also can initialize int ap=&a and int bp=&b and pass ap and bp
getch();
}
void disp1(int a, int b)
{
printf("Calling by value.n%dn%dn",a,b);
}
void disp2(int *a, int *b)
{
printf("Calling by Referance.n%dn%d",*a,*b);
}
Output:
Program 6.1.2
Calculating the area and perimeter of a circle.
#include<conio.h>
#include<stdio.h>
void arp(float , float *, float *);
void main()
{
/*Calculating Area and Perimeter by help of Pointer*/
clrscr();
float rad,a,p;
printf("nEnter the Radius of circle: ");
scanf("%f",&rad);
arp(rad,&a,&p);
printf("Area is %f.n",a);
printf("Perimeter is %f",p);
getch();
}
void arp(float r,float *a, float *p)
{
69
*a=3.14*r*r;
*p=2*3.14*r;
}
Output:
6.2 pointer of Array
Program 6.2.1
Passing array to a function using pointer.
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int arr[5];
for(int a=0;a<=4;a++)
{
printf("Enter the number %d: ",a+1);
scanf("%d",&arr[a]); //scanning the value of array.
}
clrscr();
printf("nn Array before sorting is ");
for(a=0;a<=4;a++)
{
printf("%d ",arr[a]); //printing the value of array before sorting.
}
int temp;
printf("nn After sorting, it is t ");
for(int i=0;i<=4;i++)
{
for(int j=i;j<=4;j++)
{
if(arr[i]>arr[j]) //Decision making
{
70
temp=arr[i];
arr[i]=arr[j]; //values interchanging
arr[j]=temp;
}
}
}
for(int c=0;c<=4;c++) //Final loop
{
printf("%d ",arr[c]); //printing the list after sorting...
}
getch();
Output:
Exercise:
1. Write a program to display the contents of two dimensional array using pointer.
2. Write a program to demonstrate how a pointer to a function is declared to perform simple
arithmetic operation such as addition, subtraction, multiplication and division of two
numbers.
3. Write a program in C to compare two given strings using pointers.
71
Chapter# 7
File Handling:
7.1 Basics of File Handling
Program 7.1.1
Reading from a file.
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
/* File Handling basics */
FILE *fp=fopen("C:1.txt","r");
if(fp==NULL) Output:
printf("Error");
else
{
char ch;
while(1)
{
ch=fgetc(fp);
printf("%c",ch);
if(ch==EOF)
break;
}
}
fclose(fp);
getch();
}
Output:
Program 7.1.2
Writing to a file.
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
/* File Handling basics */
72
FILE *fp=fopen("C:1.txt","w");
if(fp==NULL)
printf("Error");
else
{
char ch;
while(1)
{
ch=getche();
if(ch=='.')
break;
else
fputc(ch,fp);
}
}
fclose(fp);
getch();
}
Output:
Program 7.1.3
writing data to a file in append mode.
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
/* File Handling basics */
FILE *fp=fopen("C:1.txt","a");
if(fp==NULL)
printf("Error");
else
{
char ch;
while(1)
{
ch=getche();
if(ch=='.') //finishing when user enters a dot
break;
else
fputc(ch,fp);
}
73
}
fclose(fp);
getch();
}
Output:
Program 7.1.4
File Copying with File Handling.
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
/* File Copying */
char ch;
FILE *fp=fopen("C:1.txt","r");
if(fp==NULL)
{
printf("Error");
exit(1); //terminating when file opening Error
}
FILE *ft=fopen("C:2.txt","w");
if(ft==NULL)
{
printf("Error");
exit(2);
}
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
else
fputc(ch,ft);
}
printf("Copying completed successfully.");
fclose(ft);
fclose(fp);
getch();
}
Output:
74
Program 7.1.5
Using Structure and Binary modes in File Handling.
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
/* Using Structure and Binary modes in File Handling */
FILE *fp;
char ch='y';
struct std //structure declaration
{
char name[20];
int age;
float marks;
};
struct std n; //object decleration
fp=fopen("C:Std.dat","wb"); //file opening in write binary mode
if(fp==NULL)
{
puts("Cannot open the source file");
exit(1);
}
while(ch=='y')
{
75
printf("Enter the Name: ");
gets(n.name);
printf("nEnter the age: ");
scanf("%d",&n.age);
printf("nEnter the marks: ");
scanf("%d",&n.marks);
/*writing to file using binary functions and fwrite */
fwrite(&n,sizeof(n),1,fp);
printf("Enter Y if want to add another record.n");
fflush(stdin);
ch=getche();
}
fclose(fp);
getch();
}
Output:
Exercise:
1. Write a program in C to create a product inventory file containing product name, cost
and quantity and then read the product inventory file.
2. Write a program in C using random access file function to create a database of the
students information such roll number, name, sex, address and the program should have
the following facilities.
a. to list the entire database
b. to display a particular record
c. to delete a record.
76
Chapter# 8
Graphics:
Program 8.1.1
Initialization and changing background color.
#include<graphics.h>
#include<conio.h>
void main()
{
clrscr();
int d,m;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
setbkcolor(4);
getch();
closegraph();
}
Output:
Program 8.1.2
Printing text in graphics mode with different colors.
#include<graphics.h>
77
#include<conio.h>
void main()
{clrscr();
int d,m;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
cleardevice();
setbkcolor(4);
outtext("University of Gujrat.");
setcolor(1);
outtext("University of Gujrat.");
setcolor(2);
outtext("University of Gujrat.");
getch();
closegraph();
}
Output:
Program 8.1.3
Printing text in graphics mode with different colors at different position .
#include<graphics.h>
#include<conio.h>
void main()
{clrscr();
int d,m;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
cleardevice();
setbkcolor(4);
outtextxy(10,20,"University of Gujrat.");
setcolor(1);
outtextxy(50,50,"University of Gujrat.");
setcolor(2);
outtextxy(80,80,"University of Gujrat.");
getch();
closegraph();
}
78
Output:
Program 8.1.4
Changing fonts and direction of text in graphics mode.
#include<conio.h>
#include<graphics.h>
void main()
{
int d,m;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
cleardevice();
Setbkcolor(5);
Setcolor(1);
settextstyle(1,0,5);
outtextxy(75,8,“Pakistan.");
Setcolor(15);
settextstyle(1,1,5);
outtextxy(75,40,“Pakistan.");
getch();
closegraph();
}
Output:
79
Program 8.1.5
Blinking text in graphics.
#include<graphics.h>
#include<conio.h>
#include<dos.h>
void main()
{clrscr();
int d,m,i=1;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
cleardevice();
setbkcolor(4);
settextstyle(7,0,4);
while(!kbhit())
{
setcolor(i);
outtextxy(50,100,"University of Gujrat.");
delay(150);
i++;}
getch();
closegraph();
}
Output:
80
8.2 Objects Graphic
Program 8.2.1
Object functions in graphics.
#include<conio.h>
#include<graphics.h>
void main()
{int d,m;
d=DETECT;
initgraph(&d,&m,"c:turboc3bgi");
cleardevice();
outtextxy(35,65,"circle");
circle(50,40,15);
outtextxy(150,60,"Arc");
arc(155,40,0,180,15);
outtextxy(42,160,"Rectangle");
rectangle(35,100,120,150);
outtextxy(185,120,"Line");
line(140,100,230,100);
getch();
closegraph();
}
81
Output:
References:
1. Let us C.
2. Turbo C.
3. Past Students Assignments.
4. Past Students Exams.

More Related Content

What's hot

Dive into greasemonkey (español)
Dive into greasemonkey (español)Dive into greasemonkey (español)
Dive into greasemonkey (español)
guest89b13c
 
8 2-sp1 administering-broker
8 2-sp1 administering-broker8 2-sp1 administering-broker
8 2-sp1 administering-broker
Nugroho Hermanto
 
SANS Holiday hack 2020
SANS Holiday hack 2020SANS Holiday hack 2020
SANS Holiday hack 2020
RobertKuakini
 
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
HION IT
 
ZTE Axon M Manual/User Guide
ZTE Axon M Manual/User GuideZTE Axon M Manual/User Guide
ZTE Axon M Manual/User Guide
manualsheet
 
Nortel Call Pilot telephone administration guide
Nortel Call Pilot telephone administration guideNortel Call Pilot telephone administration guide
Nortel Call Pilot telephone administration guide
Clearlines Telephone Co.
 
What's New in ZW3D 2012 v1.0
What's New in ZW3D 2012 v1.0What's New in ZW3D 2012 v1.0
What's New in ZW3D 2012 v1.0
VX
 
Igo Primo Navigation Software User Manual
Igo Primo Navigation Software User ManualIgo Primo Navigation Software User Manual
Igo Primo Navigation Software User Manual
WilliamS78
 
Marketing Proposal
Marketing ProposalMarketing Proposal
Marketing Proposal
Louis Shepherd
 
First7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programmingFirst7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programming
xmeszeus
 
1746nm002
1746nm0021746nm002
Openbravo for Retail Solution Description (RMP19)
Openbravo for Retail Solution Description (RMP19)Openbravo for Retail Solution Description (RMP19)
Openbravo for Retail Solution Description (RMP19)
Xavier Places Cano
 
R Ints
R IntsR Ints
R Ints
Ajay Ohri
 
Tap watch 22 user manual-03253d
Tap watch 22 user manual-03253dTap watch 22 user manual-03253d
Tap watch 22 user manual-03253d
czimet
 
Dot Mobi Mobile Web Developers Guide
Dot Mobi Mobile Web Developers GuideDot Mobi Mobile Web Developers Guide
Dot Mobi Mobile Web Developers Guide
eraz
 
CPanel User Guide
CPanel User GuideCPanel User Guide
CPanel User Guide
webhostingguy
 
Um8000 user guide_2-0
Um8000 user guide_2-0Um8000 user guide_2-0
Um8000 user guide_2-0
daviscontrols
 

What's hot (17)

Dive into greasemonkey (español)
Dive into greasemonkey (español)Dive into greasemonkey (español)
Dive into greasemonkey (español)
 
8 2-sp1 administering-broker
8 2-sp1 administering-broker8 2-sp1 administering-broker
8 2-sp1 administering-broker
 
SANS Holiday hack 2020
SANS Holiday hack 2020SANS Holiday hack 2020
SANS Holiday hack 2020
 
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
지브라프린터 Zebra iMZ320 감열 3인치 모바일프린터 매뉴얼
 
ZTE Axon M Manual/User Guide
ZTE Axon M Manual/User GuideZTE Axon M Manual/User Guide
ZTE Axon M Manual/User Guide
 
Nortel Call Pilot telephone administration guide
Nortel Call Pilot telephone administration guideNortel Call Pilot telephone administration guide
Nortel Call Pilot telephone administration guide
 
What's New in ZW3D 2012 v1.0
What's New in ZW3D 2012 v1.0What's New in ZW3D 2012 v1.0
What's New in ZW3D 2012 v1.0
 
Igo Primo Navigation Software User Manual
Igo Primo Navigation Software User ManualIgo Primo Navigation Software User Manual
Igo Primo Navigation Software User Manual
 
Marketing Proposal
Marketing ProposalMarketing Proposal
Marketing Proposal
 
First7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programmingFirst7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programming
 
1746nm002
1746nm0021746nm002
1746nm002
 
Openbravo for Retail Solution Description (RMP19)
Openbravo for Retail Solution Description (RMP19)Openbravo for Retail Solution Description (RMP19)
Openbravo for Retail Solution Description (RMP19)
 
R Ints
R IntsR Ints
R Ints
 
Tap watch 22 user manual-03253d
Tap watch 22 user manual-03253dTap watch 22 user manual-03253d
Tap watch 22 user manual-03253d
 
Dot Mobi Mobile Web Developers Guide
Dot Mobi Mobile Web Developers GuideDot Mobi Mobile Web Developers Guide
Dot Mobi Mobile Web Developers Guide
 
CPanel User Guide
CPanel User GuideCPanel User Guide
CPanel User Guide
 
Um8000 user guide_2-0
Um8000 user guide_2-0Um8000 user guide_2-0
Um8000 user guide_2-0
 

Similar to Manual cs it

Novell login documentation and troubleshooting
Novell login documentation and troubleshootingNovell login documentation and troubleshooting
Novell login documentation and troubleshooting
Children's Hospitals and Clinics
 
Math for programmers
Math for programmersMath for programmers
Math for programmers
mustafa sarac
 
Gcrypt
GcryptGcrypt
AltiGen Max Communicator Manual
AltiGen Max Communicator ManualAltiGen Max Communicator Manual
AltiGen Max Communicator Manual
CTI Communications
 
AltiGen Max Agent Manual
AltiGen Max Agent  ManualAltiGen Max Agent  Manual
AltiGen Max Agent Manual
CTI Communications
 
Electrónica digital: Logicsim
Electrónica digital: LogicsimElectrónica digital: Logicsim
Electrónica digital: Logicsim
SANTIAGO PABLO ALBERTO
 
Strike_English_UM_UEIK2_KR_121509_F5-web
Strike_English_UM_UEIK2_KR_121509_F5-webStrike_English_UM_UEIK2_KR_121509_F5-web
Strike_English_UM_UEIK2_KR_121509_F5-web
guestf0ca56
 
Swf File Format Spec V10
Swf File Format Spec V10Swf File Format Spec V10
Swf File Format Spec V10
losalamos
 
Expert_Programming_manual.pdf
Expert_Programming_manual.pdfExpert_Programming_manual.pdf
Expert_Programming_manual.pdf
EMERSON EDUARDO RODRIGUES
 
Manual instructiuni-pirelli-dpl-10-black
Manual instructiuni-pirelli-dpl-10-blackManual instructiuni-pirelli-dpl-10-black
Manual instructiuni-pirelli-dpl-10-black
Quickmobile
 
Hp33s calculator user_guide
Hp33s calculator user_guideHp33s calculator user_guide
Hp33s calculator user_guide
Land Surveyors United Community
 
Mongo db crud-guide
Mongo db crud-guideMongo db crud-guide
Mongo db crud-guide
Dan Llimpe
 
Mongo db crud guide
Mongo db crud guideMongo db crud guide
Mongo db crud guide
Deysi Gmarra
 
C++ annotations version
C++ annotations versionC++ annotations version
C++ annotations version
PL Sharma
 
Advanced macro guide
Advanced macro guideAdvanced macro guide
Advanced macro guide
Erick Souza Martinho
 
Hats guia de_macro
Hats guia de_macroHats guia de_macro
Hats guia de_macro
Erick Souza Martinho
 
Debugger.pdf
Debugger.pdfDebugger.pdf
Debugger.pdf
BuTriLn
 
Nokia 3520 User's Manual.pdf
Nokia 3520 User's Manual.pdfNokia 3520 User's Manual.pdf
Nokia 3520 User's Manual.pdf
atswalla
 
Programming
ProgrammingProgramming
Programming
Aravindharamanan S
 
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
HION IT
 

Similar to Manual cs it (20)

Novell login documentation and troubleshooting
Novell login documentation and troubleshootingNovell login documentation and troubleshooting
Novell login documentation and troubleshooting
 
Math for programmers
Math for programmersMath for programmers
Math for programmers
 
Gcrypt
GcryptGcrypt
Gcrypt
 
AltiGen Max Communicator Manual
AltiGen Max Communicator ManualAltiGen Max Communicator Manual
AltiGen Max Communicator Manual
 
AltiGen Max Agent Manual
AltiGen Max Agent  ManualAltiGen Max Agent  Manual
AltiGen Max Agent Manual
 
Electrónica digital: Logicsim
Electrónica digital: LogicsimElectrónica digital: Logicsim
Electrónica digital: Logicsim
 
Strike_English_UM_UEIK2_KR_121509_F5-web
Strike_English_UM_UEIK2_KR_121509_F5-webStrike_English_UM_UEIK2_KR_121509_F5-web
Strike_English_UM_UEIK2_KR_121509_F5-web
 
Swf File Format Spec V10
Swf File Format Spec V10Swf File Format Spec V10
Swf File Format Spec V10
 
Expert_Programming_manual.pdf
Expert_Programming_manual.pdfExpert_Programming_manual.pdf
Expert_Programming_manual.pdf
 
Manual instructiuni-pirelli-dpl-10-black
Manual instructiuni-pirelli-dpl-10-blackManual instructiuni-pirelli-dpl-10-black
Manual instructiuni-pirelli-dpl-10-black
 
Hp33s calculator user_guide
Hp33s calculator user_guideHp33s calculator user_guide
Hp33s calculator user_guide
 
Mongo db crud-guide
Mongo db crud-guideMongo db crud-guide
Mongo db crud-guide
 
Mongo db crud guide
Mongo db crud guideMongo db crud guide
Mongo db crud guide
 
C++ annotations version
C++ annotations versionC++ annotations version
C++ annotations version
 
Advanced macro guide
Advanced macro guideAdvanced macro guide
Advanced macro guide
 
Hats guia de_macro
Hats guia de_macroHats guia de_macro
Hats guia de_macro
 
Debugger.pdf
Debugger.pdfDebugger.pdf
Debugger.pdf
 
Nokia 3520 User's Manual.pdf
Nokia 3520 User's Manual.pdfNokia 3520 User's Manual.pdf
Nokia 3520 User's Manual.pdf
 
Programming
ProgrammingProgramming
Programming
 
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
인터맥프린터 Intermec PB21 PB31 감열 모바일프린터 매뉴얼
 

Recently uploaded

Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
riddhimaagrawal986
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
TaghreedAltamimi
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 

Recently uploaded (20)

Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 

Manual cs it

  • 1. In progress Version Manual (CS-105) Programming Fundamentals Labs Using C Language Compiled by: Muhammad Sahfiq DEPARTMENT OF INFORMATION TECHNOLOGYUNIVERSITY OF GUJRAT
  • 2. 2 Contents Chapter# 1 Basic Concept related to C..................................................................................................7 0.1 A simple program that prints “Hello World” ......................................................................................7 0.2 To use of Escape Squences .................................................................................................................8 0.3 Use of Comments................................................................................................................................9 1.1 Use of Variables.....................................................................................................................................9 1.1.1 To print the values of Two variables..............................................................................................10 1.1.2 To calculate area and circumference of circle using define directive. ..........................................14 1.1.3 To find range of variable underflow and overflow........................................................................14 1.1.4 To swaps two values. ....................................................................................................................15 1.2Use of operators ...................................................................................................................................17 1.2.1 Use of Arithmetic operator............................................................................................................18 1.2.2 Use of compound assignment operators.......................................................................................18 1.2.3 Use of Increment operator with prefix/postfix form.....................................................................19 1.2.4 Use of Decrement operator with prefix/postfix form. ..................................................................19 1.2.5 To find salary on the behalf of working hour and hour week ......................................................20 1.3 Use of Scanf() ......................................................................................................................................17 1.3.1 To print the values of two variables using scanf............................................................................18 1.3.2 To print any character value using scanf. ......................................................................................18 1.3.3 To find salary by getting input such as working hour and hour week...........................................19 1.3.4 To find reverse of any input number. ...........................................................................................19 1.3.5 To find the number is even or odd by using arithmetic operator "%". .........................................20 1.3.6 To find size of different data types................................................................................................18 Chapter# 2 Selection or Conditional structure..................................................................................................17 2.1 Selection structure (IF)................................................................................................................................................17 2.1.1 To find that you have entered exact digit or not...........................................................................17 2.1.2 To find that you have entered exact character or not...................................................................18 2.1.3 To find that entered number is even or odd. ................................................................................18 2.1.4 To find minimum number among from the 3 entered numbers...................................................19 2.1.5 To find minimum number among from the 3 entered numbers...................................................19 2.1.6 To find that user is applicable for scholarship or not ....................................................................20
  • 3. 3 2.1.7 To determine that entered number is Positive or Negative..........................................................23 2.2 Use of logical operators in if statement ................................................................................................................21 2.2.1 To determine that entered character is vowel using OR operator ...............................................23 2.2.2 To find maximum number using AND operator. ...........................................................................24 2.2.3 To determine that number is positive or negative using NOT operator .......................................25 2.2.4 To find eligibility for scholarship using Multiple IF condition........................................................27 2.2.5 To find the square-root of an entered number using if condition. ...............................................25 2.3 Use of If-else.....................................................................................................................................................................24 2.3.1 To find about the entered word correction using if-else...............................................................25 2.3.2 To find that entered number is even or odd using if-else .............................................................26 2.3.3 To determine about leap year using if else condition................................................................27 2.4 Use of If-else-If.................................................................................................................................................................24 2.4.1 To print grade against marks using if-else-if statement ................................................................30 2.5 Swicth statement............................................................................................................................................................39 2.5.1 To determine about day using switch statement..........................................................................30 2.5.2 To find the area or circumference of the circle using switch condition ........................................31 2.5.3 To find the result of arithmetic operators using switch statement...............................................31 2.5.4 To determine about vowels and consonants using switch statement. .........................................34 2.6 Use of Conditional operator.......................................................................................................................................39 2.6.1 To print maximum number using conditional operator. ..............................................................35 2.6.2 To determine that number is even or odd using conditional operator.........................................35 2.6.3 To calculate salary and tells the bonus using conditional operator. .............................................36 chapter# 3 Loop iterations or repetations................................................................................................ 39 3.1 For loop............................................................................................................................................................................. 39 3.1.1 To print the message "Red" 10 times using for loop.....................................................................37 3.1.2 To print all Capital Alphabetic keys using for loop.........................................................................38 3.1.3 To print first five odd numbers using for loop...............................................................................39 3.1.4 To print the sum of given numbers using for loop ........................................................................41 3.1.5 To calculate the square-root given numbers using for loop..........................................................40 3.1.6 To print the table of the given number using for loop ..................................................................40 3.1.7 To find the factorial given number using for loop. .......................................................................41
  • 4. 4 3.1.8 To print a horizontal line of box using for loop..............................................................................41 3.1.9 To print the text within the boxes using multiple for loop............................................................42 3.2 Nested loop.......................................................................................................................................................................39 3.2.1 To print right side diagonal............................................................................................................39 3.2.2 To print left side diagonal..............................................................................................................40 3.2.3 To print the cross sign or symbol...................................................................................................40 3.2.4 To print right side triangle. ............................................................................................................41 3.2.5 To print down-side triangle............................................................................................................41 3.2.6 To print the symbol (#). .................................................................................................................42 3.2.7 To print the sum in a matrix shape using for loop.........................................................................43 3.3 While loop.........................................................................................................................................................................56 3.3.1 To display ASCII value until user will not strike the enter key.......................................................43 3.3.2 To count the character until user does not strike the enter key...................................................44 3.3.3 To prints the number is even or odd until user not strike the “-1”...............................................45 3.3.4 To find the total of 5 numbers.......................................................................................................45 3.3.5 To count characters, words, and digits using while loop...............................................................46 3.4 Do-While Loop.................................................................................................................................................................56 3.4.1 To check marks validation using do while loop .............................................................................51 Chapter# 4 Functions........................................................................................................................................ 56 4.1 To demonstrate about the functions................................................................................................52 4.2 To prints right and left angle triangles using functions. ...................................................................53 4.3 To draws rectangle according to the size of the class room, faculty room, and exam hall..............54 4.4 To convert the upper to lower case and lower to upper letters ......................................................55 4.5 To calculate the difference between time........................................................................................55 4.6 To calculates difference between two dates and result in days ......................................................52 4.7 Using parameterized functions ................................................................................................................................56 To calculate difference between two dates and result in days................. Error! Bookmark not defined. Chapter # 5 Array……..……………………………………………………………………………………………………………... ……..68 5.1 Basics of Arrays ..…………………………………………………………..………………………………………………………………..68 5.1.1 Declaring and printing Array……………………………..…..…………………………………………………………………….68 5.1.2 Input data in Array from User………………..………..……………………………………………………………………………69
  • 5. 5 5.1.3 Finding sum and Average of an Array………………………………………………….………………………………………..70 5.1.4 Print the values of an array by passing it in function……………………………………………………………………..71 5.1.5 Sorting of an Array………………………………………………………………………………………………………………………..73 5.2 String………………………….……………………………………………………………………………………………………………….73 5.2.1 storing and printing a sentence in string……………………………………………………………………………………….73 5.3 Structure Basic.……………………………………………………………………………………………………………………………74 5.3.1 Declaring structure……………………………………………………………………………………………………………………….74 5.3.2 Storing more than on values in structure………………………………………………………………………………………75 5.4 Array type variables of structure…………………………………………………………………………………………………76 5.4.1 A program which store data of 8 students……………………………………………………………………………………76 Chapter#6 Pointers …………………………………………………………………………………………………………………………..77 6.1 Pointer Basics………………………………………………………………………………………………………………………………77 6.1.1 Direct and indirect value of an variable…………………………………………………………………………………………77 6.1.2Calculating the area and perimeter of a circle………………………………………………………………………………..79 6.2 Pointer of Array…………………………………………………………………………………………………………………………..80 6.2.1 Passing array to function using pointer…………………………………………………………………………………………80 Chapter#7 File Handling…………………………………………………………………………………………………………………….82 7.1 Basics of File handling………………………………………………………………………………………………………………….82 7.1.1 Reading from a file……..…………………………………………………………………………………………………………………82 7.1.2 Writing to a file …………………………………………………………………………………………………………………………….83 7.1.3 Writing data to a file in opened mode…………………………………………………………………………………………..84 7.1.4 File Copying with file Handling………………………………………………………………………………………………………85 7.1.5 Using structure and binary modes in file handling ……………………………………………………………………….86 Chapter#8 Graphics ………………………………………………………………………………………………………………………….88 8.1.1 Initialization and changing background color ……………………………………………………………………………….88
  • 6. 6 8.1.2 Printing text in graphics mode with different colors …………………………………………………………………….89 8.1.3 Printing text at different points…………………………………………………………………………………………………….90 8.1.4 Changing font and direction of text in graphics mode ………………………………………………………………….91 8.1.5 Blinking text in graphics ………………………………………...........................................................................92 8.2 Objects in graphics………………………………………………………………………………………………………………………93
  • 7. 7 Chapter# 1 Basic concept related C language Program 0.1 A simple program that prints "Hello”. #include<stdio.h> #include<conio.h> void main() { clrscr(); printf(" Hello World"); getch(); } Output: Program 0.2 To use of Escape sequences. #include<stdio.h> #include<conio.h> void main() { clrscr(); printf("Hello n World"); printf("Hello t World"); printf("Hello ' World"); printf("Hello " World"); printf("Hello a World"); printf("Hello r World"); getch(); } Output:
  • 8. 8 Program 0.3 Use f comments. #include<stdio.h>//Header file #include<conio.h>//Header file void main()//main function { //body of main clrscr();//for clear screen printf("ntUniversty of Gujrat...!n");//for output printf("ntComputer Science & Information Technology ...!");//n for new line t for spaces getch();//for asdf }//end of body Output: 1.1 Use of variables Program 1.1.1 To print values of two variables. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a=5; int b=7; printf("nt The values of a=%d and b=%d ",a,b); getch(); } Output: Program 1.1.2 To calculate area and circumference of circle using define directive. #include<stdio.h> #include<conio.h> #define pi 3.141593 void main() {
  • 9. 9 clrscr(); flaot a; float r; float c; r=4.50; a=2*pi*r*r; c=2*pi*r; printf("ntArea: %fntCircumference: %f",a,c); getch(); } Output: Program 1.1.3 To find range of variable underflow and overflow. #include<stdio.h> #include<conio.h> void main() { int var=32767; clrscr(); var=var+1; printf("t%d",var); getch(); } Output: Program 1.1.4 To swaps two values. #include<stdio.h> #include<conio.h> void main() { int a=200; int b=100; int swap; printf("ntBefore swappiing a=%d b=%d",a,b); swap=a;
  • 10. 10 a=b; b=swap; printf("nntAfter swapping a=%d b=%dnn",a,b); getch(); } Output: 1.2Use of operators Program 1.2.1 Use of Arithmetic operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b; a=10; b=5; printf("nta+b = %d",a+b); printf("nta-b = %d",a-b); printf("nta*b = %d",a*b); printf("nta/b = %d",a/b); getch(); } Output: Program 1.2.2 Use of compound assignment operators. #include<stdio.h> #include<conio.h> void main() { clrscr();
  • 11. 11 int a,b; a=10; printf("ntValue of a= %d",a); a+=5; printf("ntValue after a+=5: %d",a); a-=5; printf("ntValue after a-=5: %d",a); a*=2; printf("ntValue after a*=2: %d",a); a/=2; printf("ntValue after a/=2: %d",a); getch(); } Output: Program 1.2.3 Use of Increment operator with prefix/postfix form. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b,x; a=b=0; printf("nta=%d, b=%d, ",a,b); x=++a; printf("ntPrefix Increment: a=%d, x=%d",a,x); x=b++; printf("ntPostfix Increment: b=%d, x=%d",b,x); getch(); } Output:
  • 12. 12 Program 1.2.4 Use of Decrement operator with prefix/postfix form. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b,x; a=b=2; printf("nta=%d, b=%d, ",a,b); x=--a; printf("ntPrefix Decrement: a=%d, x=%d",a,x); x=b--; printf("ntPostfix Decrement: b=%d, x=%d",b,x); getch(); } Output Program 1.2.5 To find salary on the behalf of working hour and hour week #include<stdio.h> #include<conio.h> void main() { clrscr(); float hr; float hw; float pay; hr=150.00; hw=15.30; pay=hr*hw; printf("t%f",pay); getch(); } Output: 1.3 Use of Scanf()
  • 13. 13 Program 1.3.1 T o print the values of two variables using scanf . #include<stdio.h> #include<conio.h> void main() { clrscr(); int a; int b; printf("ntEnter first value="); scanf("%d",&a); printf("ntEnter Second value="); scanf("%d",&b); printf("ntThe values of a= %d and b= %d ",a,b); getch(); } Output: Program 1.3.2 To print any character value using scanf. #include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); printf("ntEnter a char:t"); scanf("%c",&ch); printf("ntThe char is:t%c",ch); getch(); }
  • 14. 14 Output: Program 1.3.3 To find salary by getting input such as working hour and hour week. #include<stdio.h> #include<conio.h> void main() { clrscr(); float hr; float hw; float pay; printf("ntEnter hour rate:"); scanf("%f",&hr); printf("ntEnter working hour:"); scanf("%f",&hw); pay=hr*hw; printf(" n tYour Pay is:%f",pay); getch();} Output: Program 1.3.4 To find reverse of any input number. #include<stdio.h> #include<conio.h> void main() { clrscr(); int n,a,s,d; printf("tEnter 4-digit number: "); scanf("%d",&n); a=n/1000; n=n%1000; s=n/100; n=n%100;
  • 15. 15 d=n/10; n=n%10; printf("ntNumber in Revrse order: %d%d%d%d",n,d,s,a); getch(); } Output: Program 1.3.5 To find the number is even or odd by using arithmetic operator "%". #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b; printf("ntEnter a Number:"); scanf("%d",&a); b=a%2; printf("ntNote:nt If the value is 0 then given number is EVEN"); printf("nt If the value is 1 then given number is ODD"); printf("nntThe Value is=%d",b); getch(); } Output: Program 1.3.6 To find size of different data types. #include<stdio.h> #include<conio.h> void main() { clrscr(); printf("ntThe size of char: %d",sizeof(char)); printf("ntThe size of int: %d",sizeof(int));
  • 16. 16 printf("ntThe size of float: %d",sizeof(float)); printf("ntThe size of long: %d",sizeof(long)); printf("ntThe size of double: %d",sizeof(double)); printf("ntThe size of long double: %d",sizeof(long double)); getch(); } Output : Exercise: 1. Write a program to check the sizes of the main C data types on your machine. 2. Write a program to illustrate whether the printf() standard library function truncates or rounds when printing out a floating point number. 3. Write a program to check what the following code segment outputs and explain the results. char c ; printf("sizeof( c ) = %dn", sizeof( c ) ) ; printf("sizeof( 'a' ) = %dn", sizeof( 'a' ) ) ; printf("sizeof( c = 'a' ) = %dn", sizeof( c='a' )); 4. Run the "hello world" program on your system. Experiment with leaving out parts of the program, to see what error messages you get. 5. Experiment to find out what happens when printf 's argument string contains c, where c is some character not listed above. 6. Write a program which reads a character from the keyboard and writes out its ASCII representation. 7. Now write a program which reads in an integer from the keyboard and print out its character representation. Make certain you carry out appropriate bounds / error checking. 8. Write a program to read Fahrenheit temperatures and print them in Celsius. The formula is C = (5/9)(F - 32). Use variables of type double in your program. 9. Write a program that reads in the radius of a circle and prints the circle‟s diameter, circumference and area. Use the value 3.14159 for “pi”. 10. Write a program to print all input lines that are longer than 80 characters.
  • 17. 17 Chapter# 2 Selection structure: 2.1 Selection structure (IF) Program 2.1.1 To find that you have entered exact digit or not . #include<stdio.h> #include<conio.h> void main() { clrscr(); int num; printf(“ntEnter digit (5): “); scanf(“%d”,&num); if(num==5) printf("ntYou have entered 5"); getch(); } Output: Program 2.1.2 To find that you have entered exact character or not . #include<stdio.h> #include<conio.h> void main() { clrscr(); char ch,chh; printf("ntEnter characters „n‟:"); ch=getche(); if(ch=='n') printf("ntYou have entered 'n' "); getch(); }
  • 18. 18 Output: Program 2.1.3 To find that entered number is even or odd. #include<stdio.h> #include<conio.h> void main() { clrscr(); int num; printf("ntEnter a number:"); scanf("%d",&num); if(num%2==0) printf("tThe number you have entered is Even.!!!"); if(num%2==1) printf("tThe number you have entered is Odd.!!!"); getch(); } Output: Program 2.1.4 To find minimum number among from the 3 entered numbers. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b,c,d,e,min; printf("ntEnter a:"); scanf("%d",&a); printf("ntEnter b:"); scanf("%d",&b); printf("ntEnter c:"); scanf("%d",&c); min=a; if(b<min) min=b;
  • 19. 19 if(c<min) min=c; printf("ntt Minimum Value is: %d",min); getch(); } Output: Program 2.1.5 To find minimum number among from the 3 entered numbers. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b,c,max; printf("ntEnter a:"); scanf("%d",&a); printf("ntEnter b:"); scanf("%d",&b); printf("ntEnter c:"); scanf("%d",&c); max=a; if(b>max) max=b; if(c>max) max=c; printf("nttMaximum Value is: %d",max); getch(); } Output:
  • 20. 20 Program 2.1.6 To find that user is applicable for scholarship or not. #include<stdio.h> #include<conio.h> void main() { clrscr(); float gpa,cgpa; printf("ntEnter GPA:"); scanf("%f",&gpa); printf("ntEnter CGPA:"); scanf("%f",&cgpa); if(gpa>=3.0) if(cgpa>=3.0) printf("ntCongartualtions...!!!n t You will get full scholorship"); getch(); } Output: Program 2.1.7 To determine that entered number is Positive or Negative. #include<stdio.h> #include<conio.h> void main() { clrscr(); int n; printf("ntEnter a Number: "); scanf("%d",&n); if(n>0) printf("ntNumber is Positive..!"); if(n<0) printf("ntNumber is Negative..!"); getch(); } Output:
  • 21. 21 2.2 Use of logical operators in if statement Program 2.2.1 To determine that entered character is vowel using OR operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); char ch; printf("ntEnter any character: "); scanf("%ch",&ch); if(ch=='A'||ch=='a'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U') printf("ntYour entered a vowel: %c",ch); getch(); } Output: Program 2.2.2 To find maximum number using AND operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); int a,b,c; printf("ntEnter a: "); scanf("%d",&a); printf("ntEnter b: "); scanf("%d",&b); printf("ntEnter c: "); scanf("%d",&c); if((a>b)&&(a>c)) printf("ntMaximum number is: %d",a); if((b>c)&&(b>a)) printf("ntMaximum number is: %d",b);
  • 22. 22 if((c>a)&&(c>b)) printf("ntMaximum number is: %d",c); getch(); } Output: Program 2.2.3 To determine that number is positive or negative using NOT operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); int n; printf("ntEnter a Number: "); scanf("%d",&n); if(!(n>0)) printf("ntNumber is Negative..!"); if(!(n<0)) printf("ntNumber is Positive..!"); getch(); } Output: Program 2.2.4 To find eligibility for scholarship using Multiple IF condition. #include<stdio.h> #include<conio.h> void main() { clrscr(); float cgpa;
  • 23. 23 int age; char status, gender,grade; printf("ntEnter the CGPA 3.0 almost:"); scanf("%f",&cgpa); printf("ntEnter the age 25 almost:"); scanf("%d",&age); printf("ntEnter the status as Reglar press 'R':"); status=getche(); printf("nntEnter the Gender 'M' for male and 'F' for female.:"); gender=getche(); printf("nntEnter the Grade.:"); grade=getche(); if(cgpa>=3.0&&age<=25) if(status=='r'||status=='R') if(gender=='M'||gender=='F'||gender=='m'||gender=='f') if(grade=='A'||grade=='a') printf("nn Congratulations...!!!! You will get scholorship.."); getch(); } Output: Program 2.2.5 To find the square-root of an entered number using if condition. #include<stdio.h> #include<conio.h> #include<math.h> void main() { clrscr(); int n; float sqroot; printf("ntEnter a number:"); scanf("%d",&n); if(n>0) sqroot=sqrt(n); printf("tThe sqroot of %d is %f",n,sqroot); getch(); }
  • 24. 24 Output: 2.3 Use of If-else Program 2.3.1 To find about the entered word correction using if-else. #include<stdio.h> #include<conio.h> void main() { clrscr(); char ch; printf("ntEnter a character (y): "); ch=getche(); if(ch=='Y'||ch=='y') printf("ntYou have enter Y"); else printf("ntYou have entered another word"); getch(); } Output: Program 2.3.2 To find that entered number is even or odd using if-else #include<stdio.h> #include<conio.h> void main() { clrscr(); int num; printf("nn Enter a number:"); scanf("%d",&num); if(num%2==0) printf("The number you have entered is Even.!!!"); else printf("The number you have entered is Odd.!!!"); getch(); }
  • 25. 25 Output: Program 2.3.3 To determine about leap year using if else condition. #include<stdio.h> #include<conio.h> #include<math.h> void main() { clrscr(); int num; printf("ntEnter year in the format of 0000:"); scanf("%d",&num); if(num%4==0) printf("ntThe Year which you have entered Leap Year.!!!"); else printf(“ntIts no Leap year..!!!”); getch(); } Output: 2.4 Use of If-else-If Program 2.4.1 To print grade against marks using if-else-if statement. #include<stdio.h> #include<conio.h> void main() { clrscr(); int marks; printf("ntEnter Marks:"); scanf("%d",&marks); if(marks>=80&&marks<=100) printf("ntYou have obtained Grade 'A' "); else if(marks>=70&&marks<=79)
  • 26. 26 printf("ntYou have obtained Grade 'B' "); else if(marks>=60&&marks<=69) printf("ntYou have obtained Grade 'C' "); else if(marks>=50&&marks<=59) printf("ntYou have obtained Grade 'D' "); else printf("nt Grade 'F' "); getch(); } Output: 2.5 Switch Statement Program 2.5.1 To determine about day using switch statement. #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("ntEnter a Day number:"); scanf("%d",&n); switch(n) { case 1: printf("ntFriday"); break; case 2: printf("ntSaturday"); break; case 3: printf("ntSunday"); break; case 4: printf("ntMonday"); break; case 5: printf("ntTuesday"); break; case 6: printf("ntWednesday"); break;
  • 27. 27 case 7: printf("ntThursday"); break; default: printf("ntInvalid Day number."); } getch(); } Output: Program 2.5.2 To find the area or circumference of the circle using switch condition. #include<stdio.h> #include<conio.h> void main() { clrscr(); float a,c,r; int num; printf("ntEnter a number=t 1 for area and 2 for circumference:"); scanf("%d",&num); printf("ntEnter the Radius:"); scanf("%f",&r); switch(num) { case 1: printf("ntFor Area.:"); a=3.1416*r*r; printf("ntThe Area is:%f",a); break; case 2: printf("ntFor Circumference.:"); c=2*3.1416*r; printf("ntThe Circumference is:%f",c); break; default: printf("ntWrong Number you have entered"); } getch(); }
  • 28. 28 Output: // OR Program 2.5.3 To find the result of arithmetic operators using switch statement. #include<stdio.h> #include<conio.h> void main() { clrscr(); float a,b,c; char optr; printf("ntEnter choice + - * / %: "); scanf("%c",&optr); printf("ntEnter first value: "); scanf("%f",&a); printf("ntEnter second value: "); scanf("%f",&b); switch(optr) { case '+': c=a+b; printf("ntThe Addition is:%f",c); break; case '-': c=a-b; printf("ntThe Subtration is:%f",c); break; case '*': c=a*b;
  • 29. 29 printf("ntThe Multiplication is:%f",c); break; case '/': c=a/b; printf("ntThe Division is:%f",c); break; case '%': c=int(a)%int(b); printf("ntThe Modulus is:%d",c); break; default: printf("ntWrong Operator..!!!!"); } getch(); } Output: Program 2.5.4 To determine about vowels and consonants using switch statement. #include<stdio.h> #include<conio.h> void main() { clrscr(); char letter; printf("ntEnter a letter:); scanf("%c",&letter); switch(letter) { case „a‟: case „A‟: case „e‟: case „E‟: case „i‟: case „I‟: case „o‟: case „O‟: case „u‟: case „U‟: printf("ntYou have entered a Vowel"); break;
  • 30. 30 default: printf("ntYou have entered Consonant"); getch(); } Output: 2.6 Use of conditional operator Program 2.6.1 To print maximum number using conditional operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); int num1,num2,result; printf("ntEnter first number: "); scanf("%d",&num1); printf("ntEnter second number: "); scanf("%d",&num2); //result=(num1>num2)?1:0; result=(num2<num1)?printf("ntFirst number is greater"):printf("ntSecond number is greater"); getch(); } Output: Program 2.6.2 To determine that number is even or odd using conditional operator. #include<stdio.h> #include<conio.h> void main() { int num,reslt; clrscr(); printf("ntEnter a number: ");
  • 31. 31 scanf("%d",&num); //reslt=(num%2==0)? 0:1; reslt=(num%2==0)? printf("ntEven"):printf("ntOdd"); getch(); } Output: Program 2.6.3 To calculate salary and tells the bonus using conditional operator. #include<stdio.h> #include<conio.h> void main() { clrscr(); float sal,bonus,rsal,result; printf("ntEnter Your current Salary Please:"); scanf("%f",&sal); result=(sal>10000)?printf("ntYour Bonus is 10%"):printf("ntYour Bonus is 5%"); bonus=sal*10/100; printf("nntYou will get %f bonus.",bonus); rsal=sal+bonus; printf("nntYour revised salary is:%f",rsal); getch(); } Output:
  • 32. 32 Exercise of chapter 2: 1. Write a program which prints out the ASCII and hex values of all characters input at the keyboard terminating only when the character `q' or `Q' is entered. 2. Write a program to keep count of the occurrence of a user specified character in a stream of characters of known length (e.g. 50 characters) input from the keyboard. Compare this to the total number of characters input when ignoring all but alphabetic characters. Note: The ASCII values of 'A'...'Z' are 65...90 and 'a'...'z' are 97...122. 3. Write a program to find the roots of a user specified quadratic equation. Recall the roots of ax bx c 02    are -b b 4ac 2a 2   The user should be informed if the specified quadratic is valid or not and should be informed how many roots it has, if it has equal or approximately equal roots (b2 == 4ac), if the roots are real (b2 - 4ac > 0) or if the roots are imaginary (b2 - 4ac < 0). In the case of imaginary roots the value should be presented in the form (x + i y). Note that C has a standard library function sqrt( ), which returns the square root of its operand, and whose prototype can be found both in the help system. 4. Write a program that allows the user to read a user specified number of double precision floating point numbers from the keyboard. Your program should calculate the sum and the average of the numbers input. Try and ensure that any erroneous input is refused by your program, e.g. inadvertently entering a non-numeric character etc. 5. Write and simulate a program using the C language: - Input 1 lowercase ASCII letter (between „a‟ and „z‟) - Change lowercase ASCII letter to uppercase ASCII letter. - Output them on screen. 6. Write a program that prompts the user for a string, and prints its reverse. 7. Write a C program which converts the number in seconds to hour, minute and seconds. If the number is less than 1000, the program should print the message “You should enter an integer number greater than or equal to 1000” Sample runs: Enter the number of seconds> 7322 7322 seconds is equivalent to 2 hours 2 minutes 2 seconds. Enter the number of seconds> 500 You should enter an integer number greater than or equal to 1000 8. Write a program that reads in five integers and then determines and prints the largest and the smallest integers in the group. Use only the programming techniques you have learned in the lecture. Sample run: Input 5 integers: 9 4 5 8 7 The largest value is 9
  • 33. 33 The smallest value is 4 9. Write a C program that reads three nonzero integers and determines and prints if they could be the sides of a right triangle. [Hint: Use Pythagorean Theorem] Sample runs: Enter three integers: 3 4 5 The three integers are the sides of a right triangle Enter three integers: 5 3 4 The three integers are the sides of a right triangle Enter three integers: 9 4 1 The three integers are not the sides of a right triangle 10. Write a program that reads an integer from keyboard. Assuming it is the number of month of the year, print out the name of that month. Your program should also check that the number is a valid month number. If it is not a valid number, you should print a warning message. Sample runs: Enter the month number> 11 NOVEMBER Enter the month number> 13 Not a valid month number!
  • 34. 34 Chapter# 3 Loop iterations or repetitions 3.1 For loop Program 3.1.1 To print the message "Red" 10 times using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); for (int t=0; t<10; t++) printf("tRed n"); getch(); } Output: Program 3.1.2 To print all Capital Alphabetic keys using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); char ch; for(ch='A';ch<='Z';ch++) printf("%c ",ch); getch(); }
  • 35. 35 Output: Program 3.1.3 To print first five odd numbers using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int num=1;num<=10;num+=2) printf("%d",num); getch(); } Output: Program 3.1.4 To print the sum of given numbers using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); int j,k,sum,n; printf("ntEnter serial numbers:"); scanf("%d",&n); sum=0; printf("ntIntegertt sum"); for(j=1;j<=n;j++) { sum=sum+j; printf("nt %dtt %d",j,sum); } getch(); }
  • 36. 36 Output: Program 3.1.5 To calculate the square-root given numbers using for loop. #include<stdio.h> #include<conio.h> #include<math.h> void main() { clrscr(); float j,sq,n; printf("ntEnter serial numbers:"); scanf("%f",&n); printf("tIntegertt Square root"); for(j=1;j<=n;j++) { sq=sqrt(j); printf("nt %f",j); printf("t %f",sq); } getch(); } Output: Program 3.1.6 To print the table of the given number using for loop. #include<stdio.h> #include<conio.h> void main()
  • 37. 37 { clrscr(); int c,r; printf("ntEnter a number:"); scanf("%d",&c); for(int n=1;n<=10;n++) { printf(“t”); r=n*c; printf("%d*%d=%dn",c,n,r); } getch(); } Output: Program 3.1.7 To find the factorial given number using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); int n,f; printf("ntEnter number: "); scanf("%d",&n); f=1; for(int c=n;c>=1;c--) { f=f*c; } printf("ntThe Factorial is: %d",f) getch(); }
  • 38. 38 Output: Program 3.1.8 To print a horizontal line of box using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); printf(“t”); for (int t=0; t<10; t++) { printf("="); } getch(); } Output: Program 3.1.9 To print the text within the boxes using multiple for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int i=1;i<=24;i++) { printf("#"); } printf("n"); printf("# University Of Gujrat #n"); for(int j=1;j<=24;j++) { printf("#"); } printf("n"); getch(); }
  • 39. 39 Output: 3.2 Nested loop Program 3.2.1 To print right side diagonal. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int outer=7;outer>=1;outer--) { for(int inner=1;inner<=outer;inner++) { printf(" "); } printf("#"); printf("n"); } getch(); } Output: Program 3.2.2 To print left side diagonal. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int outer=1;outer<=7;outer++) { for(int inner=1;inner<=outer;inner++) { printf(" ");
  • 40. 40 } printf("#"); printf("n"); } getch(); } Output: Program 3.2.3 To print the cross sign or symbol. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int i=1;i<=10;i++) { for(int j=1;j<=10;j++) if(i==j||(i+j)==11) printf("#"); else printf(" "); printf("n"); } getch(); } Output:
  • 41. 41 Program 3.2.4 To print right side triangle. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int outer=1;outer<=7;outer++) { for(int inner=1;inner<=outer;inner++) { printf("#"); } printf("n"); } getch(); } Output: Program 3.2.5 To print down-side triangle. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int outer=7;outer>=1;outer--) { for(int inner=1;inner<=outer;inner++) { printf("#"); } printf("n"); } getch(); } Output:
  • 42. 42 Program 3.2.6 To print the symbol (#). #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int i=1;i<=5;i++) { for(int j=1;j<=5;j++) { if(i*j%2==0) printf("="); else printf(" "); } printf("n"); } getch(); } Output: Program 3.2.7 To print the sum in a matrix shape using for loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); for(int i=1;i<=5;i++) { printf(“t”); for(int j=1;j<=5;j++) {
  • 43. 43 printf("%d",i+j); } printf("n"); } getch(); } Output: 3.3 While loop Program 3.3.1 To display ASCII value until user will not strike the enter key. #include<stdio.h> #include<conio.h> void main() { clrscr(); char ch='a'; while(ch!='r') { printf("n Enter Character:"); ch=getche(); printf("nn The ASCII value of %c=%d",ch,ch); } getch(); } Output: Program 3.3.2 To count the character until user does not strike the enter key. #include<stdio.h> #include<conio.h>
  • 44. 44 void main() { clrscr(); int count=0; printf("ntEnter Phrase:"); while(getche()!='r') { count++; } printf("ntNumber of Characters= %d",count); getch(); } Output: Program 3.3.3 To prints the number is even or odd until user not strike the “-1”. #include<stdio.h> #include<conio.h> #include<math.h> void main() { clrscr(); int i; while(i!=-1) { printf("ntEnter a Number:"); scanf("%d",&i); if((i%2)==0) { printf("ntNumber is even"); } else printf("ntNumber is Odd"); } getch(); }
  • 45. 45 Output: Program 3.3.4 To find the total of 5 numbers. #include<stdio.h> #include<conio.h> void main() { clrscr(); int total=0; int count=0; while(count<=4) { total=total+count; count++; printf("nt %d",total); } getch(); } Output: Program 3.3.5 To count characters, words, and digits using while loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); int wc=0;
  • 46. 46 int cc=-1; int dc=0; char ch; printf("ntEnter Phrase: "); while(ch!='r') { ch=getche(); if(ch==' ') wc++; else if(ch>=48&&ch<=57) dc++; else cc++; } printf("nntTotal Characters %d,Total Words %d,Total Digits %d",cc,++wc,dc); getch(); } Output: 3.4 Do-While loop Program 3.4.1 To check marks validation using do while loop. #include<stdio.h> #include<conio.h> void main() { clrscr(); int score; do { printf("ntEnter Marks: "); scanf("%d",&score); if(score<0||score>100) printf("ntInvalid score, you have entered.!!! nntPlease Enter Valid Marks b/w (1- 100).."); } while(score<0||score>100); if(score>=90&&score<=100) printf("ntA grade"); else if(score>=80&&score<=90) printf("ntB grade");
  • 47. 47 else if(score>=70&&score<=80) printf("ntC grade"); else if(score>=60&&score<=70) printf("ntD grade"); else if(score>=50&&score<=60) printf("ntE grade"); else printf("ntFail"); getch(); } Output: Exercise of Chapter 3: 1. Write a program to print out all the Fibonacci numbers using short integer variables until the numbers become too large to be stored in a short integer variable i.e. until overflow occurs. a. Use a for loop construction. b. Use a while loop construction. Note: Fibonacci numbers are (1,1,2,3,5,8,13,... 2. Write a program which simulates the action of a simple calculator. The program should take as input two integer numbers then a character which is one of +,-,*,/,%. The numbers should be then processed according to the operator input and the result printed out. Your program should correctly intercept any possible erroneous situations such as invalid operations, integer overflow, and division by zero. 3. Write a program that prompts the user for a sentence, and prints each word on its own line. 4. Write a function that outputs a right isosceles triangle of height and width n, so n = 6 would look like * ** *** **** ***** ******
  • 48. 48 5. Write a function that outputs a sideways triangle of height 2n-1 and width n, so the output for n = 4 would be: * ** *** **** *** ** * 6. Write a function that outputs a right-side-up triangle of height n and width 2n-1; the output for n = 6 would be * *** ***** ******* ********* *********** 7. Write a function to calculate if a number is prime. Return 1 if it is prime and 0 if it is not a prime. 8. Execute the following code and look at the result and then try to change the code in some way. (1) void main(){ char i; clrscr(); for(i=120;i<=128;i++){ printf("%d ",i); } getch(); } Output: Infinite loop (2) void main(){ int i; clrscr(); for(i=0,i++,i<=5;i++,i<=2;i=0,i<=5,i+=3){ printf("%d ",i); } getch(); } Output: 2 (3)
  • 49. 49 void main(){ int i=1; clrscr(); for(;;){ printf("%d ",i); } getch(); } Output: Infinite loop (4) void main(){ int i=2; clrscr(); for(i=0;i<=3;i++){ static int i; i=i+8; } printf("%d",i); getch(); } Output: 4 (5) extern int j; void main(){ int i=0; clrscr(); for(i=0;i<=2;i+=1){ int j=5; printf("%d ",j); j++; } getch(); } int j=25; Output: 5 5 5 (6) extern int j; void main(){ int i=0; clrscr(); for(i=0;i<=2;i+=1){ int j=5; printf("%d ",j); j++;
  • 51. 51 Chapter# 4 Functions: Program 4.1 To demonstrate about the functions. #include<stdio.h> #include<conio.h> void drawline(void); void main() { clrscr(); drawline(); printf("nt#University Of Gujrat#n"); drawline(); printf("n"); drawline(); printf("n"); printf("t# Faculty of Cs & It #n"); drawline(); getch(); } void drawline(void) { printf("t"); for(int i=1;i<=22;i++) printf("#"); } Output: Program 4.2
  • 52. 52 To prints right and left angle triangles using functions. #include<stdio.h> #include<conio.h> void leftangle(void); void rightangle(void); void main() { clrscr(); leftangle(); rightangle(); getch(); } void leftangle(void) { for(int i=1;i<=7;i++) { printf(“t”); for(int j=1;j<=i;j++) printf("#"); printf("n"); } } void rightangle(void) { for(int k=7;k>=1;k--) { printf(“t”); for(int l=1;l<=k;l++) printf("#"); printf("n"); } } Output: Program 4.3
  • 53. 53 To draws rectangle according to the size of the class room, faculty room, and exam hall using functions. #include<stdio.h> #include<conio.h> void drawline(int width,int length); void main() { clrscr(); printf("tClass room:n"); drawline(4,9); printf("tFaculty room:n"); drawline(5,7); printf("tExam Hall:n"); drawline(5,16); getch(); } void drawline(int width,int length) { for(int a=1;a<=width;a++) { printf("tt"); for(int b=1;b<=length;b++) printf("#"); printf("n"); } } Output: Program 4.4 To convert the upper to lower case and lower to upper letters. #include<stdio.h> #include<conio.h> char getlc(void);
  • 54. 54 void main() { clrscr(); char ch; printf("ntEnter UpperCase Letter: "); ch=getlc(); printf("ntResult in lower case letter is:%c",ch); printf("ntEnter lower Case Letter: "); ch=getlc(); printf("ntResult in lowe case letter is: %c",ch); getlc(); getch(); } char getlc(void) { char ch; ch=getche(); if(ch>=65&&ch<=90) ch=ch+32; else ch=ch-32; return(ch); } Output: Program 4.5 To calculate the difference between time. #include<stdio.h> #include<conio.h> int getmint(void); void main() { clrscr(); int mint1,mint2; printf("ntEnter first time(hour:minutes):"); mint1=getmint(); printf("ntEnter second time(hour:minutes):"); mint2=getmint(); printf("ntDifference in Minutes %d",mint2-mint1); getch();
  • 55. 55 } int getmint(void) { int hour,minut; scanf("%d:%d",&hour,&minut); return(hour*60+minut); } Output: Program 4.6 To calculates difference between two dates and result in days. #include<stdio.h> #include<conio.h> int ageday(void); void main() { clrscr(); int d1,d2; printf("ntEnter first date format year-month-day (5-3-10):"); d1=ageday(); printf("ntEnter Second date format year-month-day (3-3-10):"); d2=ageday(); printf("ntDifference in Days: %d",d2-d1); getch(); } int ageday(void) { int year,month,days; scanf("%d-%d-%d",&year,&month,&days); return((year*365)+(month*30)+days); } Output:
  • 56. 56 4.1 Using parameterized functions Program 4.1.1 To calculate difference between two dates and result in days. #include<stdio.h> #include<conio.h> int ageday(int year,int month,int days); void main() { int d1,d2; printf("ntThe first date is: 2003-03-10"); d1=ageday(03,03,10); printf("ntThe Second date is: 2005-03-10):"); d2=ageday(05,03,10); printf("nntDifference in Days: %d",d2-d1); getch(); } int ageday(int year,int month,int days) { return((year*365)+(month*30)+days); } Output: Exercise: 1. Write a program that can convert temperatures from the Fahrenheit scale to Celsius and back. The relationship is C = (5/9)(F - 32). Your program should read a temperature and which scale is used and convert it to the other, printing out the results. Write one or more functions to carry out the actual conversion. 2. Write a program that reads in the radius of a circle and prints the circle‟s diameter, circumference and area. Write functions for appropriate logical tasks in your program. You should #define all appropriate constants in your program. 3. Write and test a function to convert an unsigned integer to binary notation. Use the sizeof operator to make the program machine independent i.e. portable. 4. Write and test two functions, one that packs two character variables into one integer variable and another which unpacks them again to check the result.
  • 57. 57 5. Write and test a circular shift left function for one byte unsigned variables i.e. unsigned characters. e.g. 10011100 circular shift left by 2 yields 01110010. 6. An integer is said to be prime if it is divisible only by one and itself. Write a function which determines whether an integer is prime or not. To test your function write a program that prints out all prime numbers between 1 and 10,000. 7. Write and test a function to read in a signed integer from the standard input device. Your function should not be allowed to use the scanf function. The function should have the prototype int getint( void ) ; and should be able to accommodate the presence of a minus sign, a plus sign or no sign ( i.e. positive by default ). Note that the ASCII values of the digits 0 - 9 are consecutive, 48 - 57 and that if we wish to convert the digit „3‟ for example to an integer we simply subtract the ASCII value of digit „0‟ from its ASCII value i.e. „3‟ - „0‟ = 51 - 48 = 3. 8. Write and test a function to get a floating point number from the standard input device. The function should have the prototype float getfloat( void ) ; and should be able to accommodate normal floating point notation and exponential notation. You should make use of the getint() function in exercise 5. to read in the various components of the floating point number. 9. Write and test a function double power ( double x, int n ); to calculate the value of x raised to the power of n. (a) Use your own calculations. (b) Use the standard library function pow() ( for more information use help system ) paying particular attention to type compatibilities. 10. Write a recursive function to calculate and print out all the Fibonacci values up to and including the nth . Recall that the Fibonacci series is 1, 1, 2, 3, 5, 8, 13, ... .To test your program allow the user to enter the value of n and then print out the series. The program should run continuously until it is explicitly terminated by the user.
  • 58. 58 Chapter# 5 Arrays: 5.1 Basics of Array Program 5.1.1 Declaring and printing an array. #include<conio.h> #include<stdio.h> void main() { /*declaration and printing an Array*/ clrscr(); /*initializing array without passing the number of subscripts*/ int arr[]={25,30,20,10,35,45}; /*initialization of array with declaring the size*/ int arr1[4]={40,10,5,50}; for(int i=0;i<=5;i++) //printing the array 1 { printf("The Element no %d is %dn",i+1,arr[i]); } for( i=0;i<4;i++) { printf("Member %d is %dn",i+1,arr1[i]); } getch(); } Output: Program 5.1.2 Input data in an array from user.
  • 59. 59 #include<stdio.h> #include<conio.h> int main() { clrscr(); /*asking user to input data in array.*/ int arr[5]; //declaring the number of indexes is compulsory here. for(int i=0;i<5;i++) { printf("Enter the number %d: ",i+1); scanf("%d",&arr[i]); printf("n"); } for(i=0;i<=4;i++) { printf("Number %d is %d n",i+1,arr[i]); } getch(); } Output: Program 5.1.3 Finding sum and average of an array members. #include<stdio.h> #include<conio.h> void main() { /*Finding sum and average of Array members.*/ clrscr(); int sum=0; float avg; int marks[5]; for(int i=0;i<5;i++) {
  • 60. 60 printf("Enter the marks in subject %d ",i+1); scanf("%d",&marks[i]); printf("n"); } for(i=0;i<=4;i++) { sum=sum+marks[i]; } printf("Sum is %d. n",sum); avg=sum/5.0; printf("Average is %f ",avg); getch(); } Output: Program 5.1.4 Print the values of an array bay passing it in function. #include<conio.h> #include<stdio.h> void display(int a); void main() { /*printing the values of array by passing into the function*/ clrscr(); int arr[5]; for(int j=0;j<5;j++) { printf("Enter the number %d ",j+1); scanf("%d",&arr[j]); printf("n"); } for(int i=0;i<=4;i++) { display(arr[i]); //Passing array members by value }
  • 61. 61 getch(); } void display(int a) { printf("%dn",a); } Output: Progr5.1.5 Sorting of an array . #include<conio.h> #include<stdio.h> void main() { clrscr(); int arr[5]; for(int a=0;a<=4;a++) { printf("Enter the number %d: ",a+1); scanf("%d",&arr[a]); //scanning the value of array. } clrscr(); printf("nn Array before sorting is "); for(a=0;a<=4;a++) { printf("%d ",arr[a]); //printing the value of array before sorting. } int temp; printf("nn After sorting, it is t "); for(int i=0;i<=4;i++) { for(int j=i;j<=4;j++) { if(arr[i]>arr[j]) //Decision making { temp=arr[i];
  • 62. 62 arr[i]=arr[j]; //values interchanging arr[j]=temp; } } } for(int c=0;c<=4;c++) //Final loop { printf("%d ",arr[c]); //printing the list after sorting... } getch(); } Output: 5.2 String 5.2.1 Storing and printing a sentence using string. #include<conio.h> #include<stdio.h> void main() {clrscr(); char name[100]; printf("nEnter any sentence nn"); gets(name); printf("nYou Enter nn"); puts(name); getch(); } Output:
  • 63. 63 5.3 Structure Basics Program 5.3.1 Declaring structure #include<conio.h> #include<stdio.h> struct xyz { char name[10]; }; void main() { Clrscr(); xyz name; printf(“n Enter any sentence without space…….n”); scanf(“%s”,&name.name); getch(); } Output: Program 5.3.2 Storing more then one values in a structure. #include<conio.h> #include<stdio.h> struct xyz { char name[100],address[1000]; int number; }; void main() {
  • 64. 64 Clrscr(); xyz name; printf("nEnter Name of person = "); gets(name.name); printf("nEnter Adress of person = "); gets(name.adress); printf("nEnter Mobile number of person = "); scanf("%d",&name.number); printf("nEntered Name = "); puts(name.name); printf("nEntered Adress = "); puts(name.adress); printf("nEntered Mobile number = %d",name.number); getch(); } Output: 5.4 Array type variable and members of Structure Program 5.4.1 A program which stores data of 8 students. #include<conio.h> #include<stdio.h> struct rec { int sub[6],sum; float av_stu; }; void main() {clrscr(); int i,j; float av_class=0.0; : rec student[8]; for(i=0;i<=7;i++) {student[i].sum=0; printf("nStudent # %d",i+1); for(j=0;j<=5;j++)
  • 65. 65 { printf("nEnter marks of subject %d = ",j+1); scanf("%d",&student[i].sub[j]); student[i].sum=student[i].sum+student[i].sub[j]; } student[i].av_stu=student[i].sum/6.0; printf("nAverage of student # %d = %.2f ",i+1,student[i].av_stu); av_class=av_class+student[i].av_stu; } av_class=av_class/8.0; printf("nnAverage Class = %.2f",av_class); getch(); } Output:
  • 66. 66 Exercise: 1. Write a program in C to read a set of numbers and store in one-dimensional array and then to find the largest and the smallest number. Find also the difference between the two numbers. 2. Write a program in C that uses array to store the telephone no. of 20 students against their roll no. Input a Roll no, and then search the arrays for the student‟s telephone number. 3. Find the sum of the numbers of an array 4. Find the highest value in an array 5. Linear Search Technique in an array 6. Write a C program to bubble sort. 7. Write a C program to Selection Sort. 8. Write a C program to Insertion sort. 9. Write a C program to accept a sting as input and convert the lower case letters to uppercase & vice-versa of that string. 10. Write a program in C to find the number of vowels in each word of a given text using pointer. 11. String Operation using array:String Copy, catenation, compare, find length 12. Write a C program to accept a sting as input and convert the lower case letters to uppercase & vice-versa of that string. 13. Write a program in C to read a set of names, roll number, gender, height and weight of the student from the keyboard and to sort them in an ascending order of name using a structure.
  • 67. 67 Chapter# 6 Pointers: 6.1 pointer Basics Program 6.1.1 Direct and indirect value of an variable. #include<conio.h> #include<stdio.h> void main() { clrscr(); /* Basics Of Pointer */ int a=10; int *ap=&a; printf("Value in A is %dn",a); printf("Address of A is %dn",&a); printf("Indirect value of A is %dn",*ap); printf("Indirect adderss of A is %dn",ap); printf("Address of pointer is %dn",&ap); getch(); } Output: Program 6.1.2 Printing the values call by reference and call by value . #include<conio.h> #include<stdio.h> void disp1(int a, int b); void disp2(int *a, int *b); void main() { clrscr(); /*Pointer Introduction*/ int a=10,b=21;
  • 68. 68 disp1(a,b); disp2(&a,&b);//also can initialize int ap=&a and int bp=&b and pass ap and bp getch(); } void disp1(int a, int b) { printf("Calling by value.n%dn%dn",a,b); } void disp2(int *a, int *b) { printf("Calling by Referance.n%dn%d",*a,*b); } Output: Program 6.1.2 Calculating the area and perimeter of a circle. #include<conio.h> #include<stdio.h> void arp(float , float *, float *); void main() { /*Calculating Area and Perimeter by help of Pointer*/ clrscr(); float rad,a,p; printf("nEnter the Radius of circle: "); scanf("%f",&rad); arp(rad,&a,&p); printf("Area is %f.n",a); printf("Perimeter is %f",p); getch(); } void arp(float r,float *a, float *p) {
  • 69. 69 *a=3.14*r*r; *p=2*3.14*r; } Output: 6.2 pointer of Array Program 6.2.1 Passing array to a function using pointer. #include<conio.h> #include<stdio.h> void main() { clrscr(); int arr[5]; for(int a=0;a<=4;a++) { printf("Enter the number %d: ",a+1); scanf("%d",&arr[a]); //scanning the value of array. } clrscr(); printf("nn Array before sorting is "); for(a=0;a<=4;a++) { printf("%d ",arr[a]); //printing the value of array before sorting. } int temp; printf("nn After sorting, it is t "); for(int i=0;i<=4;i++) { for(int j=i;j<=4;j++) { if(arr[i]>arr[j]) //Decision making {
  • 70. 70 temp=arr[i]; arr[i]=arr[j]; //values interchanging arr[j]=temp; } } } for(int c=0;c<=4;c++) //Final loop { printf("%d ",arr[c]); //printing the list after sorting... } getch(); Output: Exercise: 1. Write a program to display the contents of two dimensional array using pointer. 2. Write a program to demonstrate how a pointer to a function is declared to perform simple arithmetic operation such as addition, subtraction, multiplication and division of two numbers. 3. Write a program in C to compare two given strings using pointers.
  • 71. 71 Chapter# 7 File Handling: 7.1 Basics of File Handling Program 7.1.1 Reading from a file. #include<conio.h> #include<stdio.h> void main() { clrscr(); /* File Handling basics */ FILE *fp=fopen("C:1.txt","r"); if(fp==NULL) Output: printf("Error"); else { char ch; while(1) { ch=fgetc(fp); printf("%c",ch); if(ch==EOF) break; } } fclose(fp); getch(); } Output: Program 7.1.2 Writing to a file. #include<conio.h> #include<stdio.h> void main() { clrscr(); /* File Handling basics */
  • 72. 72 FILE *fp=fopen("C:1.txt","w"); if(fp==NULL) printf("Error"); else { char ch; while(1) { ch=getche(); if(ch=='.') break; else fputc(ch,fp); } } fclose(fp); getch(); } Output: Program 7.1.3 writing data to a file in append mode. #include<conio.h> #include<stdio.h> void main() { clrscr(); /* File Handling basics */ FILE *fp=fopen("C:1.txt","a"); if(fp==NULL) printf("Error"); else { char ch; while(1) { ch=getche(); if(ch=='.') //finishing when user enters a dot break; else fputc(ch,fp); }
  • 73. 73 } fclose(fp); getch(); } Output: Program 7.1.4 File Copying with File Handling. #include<conio.h> #include<stdio.h> #include<stdlib.h> void main() { clrscr(); /* File Copying */ char ch; FILE *fp=fopen("C:1.txt","r"); if(fp==NULL) { printf("Error"); exit(1); //terminating when file opening Error } FILE *ft=fopen("C:2.txt","w"); if(ft==NULL) { printf("Error"); exit(2); } while(1) { ch=fgetc(fp); if(ch==EOF) break; else fputc(ch,ft); } printf("Copying completed successfully."); fclose(ft); fclose(fp); getch(); } Output:
  • 74. 74 Program 7.1.5 Using Structure and Binary modes in File Handling. #include<conio.h> #include<stdio.h> #include<stdlib.h> void main() { clrscr(); /* Using Structure and Binary modes in File Handling */ FILE *fp; char ch='y'; struct std //structure declaration { char name[20]; int age; float marks; }; struct std n; //object decleration fp=fopen("C:Std.dat","wb"); //file opening in write binary mode if(fp==NULL) { puts("Cannot open the source file"); exit(1); } while(ch=='y') {
  • 75. 75 printf("Enter the Name: "); gets(n.name); printf("nEnter the age: "); scanf("%d",&n.age); printf("nEnter the marks: "); scanf("%d",&n.marks); /*writing to file using binary functions and fwrite */ fwrite(&n,sizeof(n),1,fp); printf("Enter Y if want to add another record.n"); fflush(stdin); ch=getche(); } fclose(fp); getch(); } Output: Exercise: 1. Write a program in C to create a product inventory file containing product name, cost and quantity and then read the product inventory file. 2. Write a program in C using random access file function to create a database of the students information such roll number, name, sex, address and the program should have the following facilities. a. to list the entire database b. to display a particular record c. to delete a record.
  • 76. 76 Chapter# 8 Graphics: Program 8.1.1 Initialization and changing background color. #include<graphics.h> #include<conio.h> void main() { clrscr(); int d,m; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); setbkcolor(4); getch(); closegraph(); } Output: Program 8.1.2 Printing text in graphics mode with different colors. #include<graphics.h>
  • 77. 77 #include<conio.h> void main() {clrscr(); int d,m; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); cleardevice(); setbkcolor(4); outtext("University of Gujrat."); setcolor(1); outtext("University of Gujrat."); setcolor(2); outtext("University of Gujrat."); getch(); closegraph(); } Output: Program 8.1.3 Printing text in graphics mode with different colors at different position . #include<graphics.h> #include<conio.h> void main() {clrscr(); int d,m; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); cleardevice(); setbkcolor(4); outtextxy(10,20,"University of Gujrat."); setcolor(1); outtextxy(50,50,"University of Gujrat."); setcolor(2); outtextxy(80,80,"University of Gujrat."); getch(); closegraph(); }
  • 78. 78 Output: Program 8.1.4 Changing fonts and direction of text in graphics mode. #include<conio.h> #include<graphics.h> void main() { int d,m; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); cleardevice(); Setbkcolor(5); Setcolor(1); settextstyle(1,0,5); outtextxy(75,8,“Pakistan."); Setcolor(15); settextstyle(1,1,5); outtextxy(75,40,“Pakistan."); getch(); closegraph(); } Output:
  • 79. 79 Program 8.1.5 Blinking text in graphics. #include<graphics.h> #include<conio.h> #include<dos.h> void main() {clrscr(); int d,m,i=1; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); cleardevice(); setbkcolor(4); settextstyle(7,0,4); while(!kbhit()) { setcolor(i); outtextxy(50,100,"University of Gujrat."); delay(150); i++;} getch(); closegraph(); } Output:
  • 80. 80 8.2 Objects Graphic Program 8.2.1 Object functions in graphics. #include<conio.h> #include<graphics.h> void main() {int d,m; d=DETECT; initgraph(&d,&m,"c:turboc3bgi"); cleardevice(); outtextxy(35,65,"circle"); circle(50,40,15); outtextxy(150,60,"Arc"); arc(155,40,0,180,15); outtextxy(42,160,"Rectangle"); rectangle(35,100,120,150); outtextxy(185,120,"Line"); line(140,100,230,100); getch(); closegraph(); }
  • 81. 81 Output: References: 1. Let us C. 2. Turbo C. 3. Past Students Assignments. 4. Past Students Exams.