Q1. Program To Create, Initialize, Assign and Access A Pointer Variable
Q1. Program To Create, Initialize, Assign and Access A Pointer Variable
Q1. Program To Create, Initialize, Assign and Access A Pointer Variable
#include <stdio.h>
int main()
{int num;
int *pNum;
pNum=& num; num=50;
printf("Using variable num:\n");
printf("value of num: %d\naddress of num: %u\n",num,&num);
printf("Using pointer variable:\n");
printf("value of num: %d\naddress of num: %u\n",*pNum,pNum);
return 0;}
OUTPUT:-
Using variable num:
value of num: 50
address of num: 1092188940
Using pointer variable:
value of num: 50
address of num: 1092188940
Q2. Program to swap two numbers using pointers
#include <stdio.h>
int main()
{
int x, y,
*a,
*b, temp;
printf("Enter the value of x and y\n");
scanf("%d%d"
, &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n"
, x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping\nx = %d\ny = %d\n"
, x, y);
return 0;
}
OUTPUT:-
Enter the value of x and y
10
20
Before Swapping
x = 10
y = 20
After Swapping
x = 20
y = 10
Q3. Program to change the value of constant integer using pointers.
#include <stdio.h>
int main()
{
const int a=5;
int *p;
p=&a;
printf("Before changing value of a: %d"
,a);
//assign value using pointer
*p=10;
printf("\nAfter changing value of a: %d"
,a);
return 0;
}
Output
Before changing value of a: 5
After changing value of a: 10
Q4. Program to print a string using pointer
#include<stdio.h>
int main()
{
char str[6] =
"Hello";
char *ptr;
int i;
//string name itself a base address of the string
ptr = str; //ptr references str
for(i = 0; ptr[i] !=
'\0'; i++)
printf("&str[%d] = %p\n"
,i,ptr+i);
return 0;
}
OUTPUT
&str[0] = 0x7ffe4cabe102
&str[1] = 0x7ffe4cabe103
&str[2] = 0x7ffe4cabe104
&str[3] = 0x7ffe4cabe105
&str[4] = 0x7ffe4cabe106
Q5. Program to count vowels and consonants in a string using pointer.
#include <stdio.h>
int main() {
char str[100];
char *ptr;
int cntV,cntC;
printf("Enter a string: ");
gets(str);
ptr=str;
cntV=cntC=0;
while(*ptr!='\0') {
if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U' ||*ptr=='a'
||*ptr=='e'||*ptr=='i' ||*ptr=='o' ||*ptr=='u')
cntV++;
else
cntC++;
ptr++;}
printf("Total number of VOWELS: %d, CONSONANT: %d\n",cntV,cntC);
return 0;
}
OUTPUT
Enter a string: Gautam
Total number of VOWELS: 3, CONSONANT: 3
Q6. Program to find sum of elements of array using pointer
#include <stdio.h>
#include <malloc.h>
int main()
{
int i, n, sum = 0;
int *a;
printf("Enter the size of array A \n");
scanf("%d"
, &n);
a = (int *) malloc(n * sizeof(int));
printf("Enter Elements of the List \n");
for (i = 0; i < n; i++) {
scanf("%d"
, a + i);
}
for (i = 0; i < n; i++) {
sum = sum + *(a + i);
}
printf("Sum of all elements in array = %d\n"
, sum);
return 0;
}
OUTPUT
Enter the size of array A
3
Enter Elements of the List
10
20
30
Sum of all elements in array = 60
Q7. Program to swap two numbers using pointers
#include <stdio.h>
void swap (int *x, int *y)
{ int t;
t = *x;
*x=*y;
*y=t;
printf("\n after swap value of a = % d, b = %d", *x, *y);
}
void main()
{int a,b;
printf(" Enter 2 nos: \n");
scanf("%d%d", &α , &b);
printf(" before Swap value of a = %d, b = %d ", a,b);
swap (&a, &b);
printf ("\n after swap value of a=%d, b= %d\n", a,b);
}
OUTPUT
Enter 2 no.s
58
Before a= 5 ,b= 8
After a = 8 , b=5
Q8. Compare strings using pointer.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20];
char str2[20];
int value;
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
value=strcmp(str1,str2);
if(value==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
}
OUTPUT
Enter the first string : 10
Enter the second string : 10
strings are same
Q9. Find smallest number in array using pointer.
#include<stdio.h>
int main()
{
int N; printf("enter the size of array : \n");
scanf("%d",&N);
int a[N], i,*small;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &a[i]);
small = &a[0];
for(i = 1; i < N; i++){
if( *(a + i) < *small)*small = *(a + i);}
printf("Smallest Element In The Array: %d\n",*small);
return 0;}
OUTPUT
/tmp/PSvbe1B7Zn.o
enter the size of array :
3
Enter 3 integer numbers
123
Smallest Element In The Array: 1
Q10. Find largest element in array using pointer.
#include <stdio.h>
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 50): ");
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);}
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];}}
printf("Largest element = %.2lf", arr[0]);
return 0;
}
OUTPUT
Enter the number of elements (1 to 50): 3
Enter number1: 3
Enter number2: 4
Enter number3: 2
Largest element = 4.00
Q11. Find sum of all matrix elements using pointer.
#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function declaration to input, add and print matrix */
void matrixInput(int mat[][COLS]);
void matrixPrint(int mat[][COLS]);
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);
int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];
// Input elements in first matrix
printf("Enter elements in first matrix of size %dx%d: \n", ROWS,
COLS);
matrixInput(mat1);
// Input element in second matrix
printf("\nEnter elemetns in second matrix of size %dx%d: \n",
ROWS, COLS);
matrixInput(mat2);
// Finc sum of both matrices and print result
matrixAdd(mat1, mat2, res);
printf("\nSum of first and second matrix: \n");
matrixPrint(res);
return 0;
}
/**
* Function to read input from user and store in matrix.
*
* @mat Two dimensional integer array to store input.
*/
void matrixInput(int mat[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// (*(mat + i) + j) is equal to &mat[i][j]
scanf("%d", (*(mat + i) + j));
}
}
}
/**
* Function to print elements of matrix on console.
*
* @mat Two dimensional integer array to print.
*/
void matrixPrint(int mat[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// *(*(mat + i) + j) is equal to mat[i][j]
printf("%d ", *(*(mat + i) + j));
}
printf("\n");
}
}
/**
* Function to add two matrices and store their result in given res
* matrix.
*
* @mat1 First matrix to add.
* @mat2 Second matrix to add.
* @res Resultant matrix to store sum of mat1 and mat2.
*/
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS])
{
int i, j;
// Iterate over each matrix elements
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// res[i][j] = mat1[i][j] + mat2[i][j]
*(*(res + i) + j) = *(*(mat1 + i) + j) + *(*(mat2 + i) + j);
}
}
}
Output :-
Enter elements in first matrix of size 3x3:
123
456
789
Enter elemetns in second matrix of size 3x3:
789
456
123
Sum of first and second matrix:
8 10 12
8 10 12
8 10 12
Q12. Program to create a pointer array store elements in it
and display.
#include <stdio.h>
int main()
{
int arr1[25], i,n;
printf("\n\n Pointer : Store and retrieve elements
from an array :\n");
printf("-------------------------------------------
-----------------\n");
printf(" Input the number of elements to store in
the array :");
scanf("%d",&n);
printf(" Input %d number of elements in the array
:\n",n);
for(i=0;i<n;i++)
{
printf(" element - %d : ",i);
scanf("%d",arr1+i);
}
printf(" The elements you entered are : \n");
for(i=0;i<n;i++)
{
printf(" element - %d : %d \n",i,*(arr1+i));
}
return 0;
}
Output:-
#include <stdio.h>
void test() {
// test function that does nothing
return ;
}
int main() {
int a = 5;
// printing the address of variable a
printf("Address of variable = %p\n", &a);
// printing the address of function main()
printf("Address of a function = %p", test);
return 0;
}
Output:-
#include <stdio.h>
int main()
{
int no1,no2;
int *ptr1,*ptr2;
int sum,sub,mult;
float div;
printf("Enter number1:\n");
scanf("%d",&no1);
printf("Enter number2:\n");
scanf("%d",&no2);
ptr1=&no1;//ptr1 stores address of no1
ptr2=&no2;//ptr2 stores address of no2
sum=(*ptr1) + (*ptr2);
sub=(*ptr1) - (*ptr2);
mult=(*ptr1) * (*ptr2);
div=(*ptr1) / (*ptr2);
printf("sum= %d\n",sum);
printf("subtraction= %d\n",sub);
printf("Multiplication= %d\n",mult);
printf("Division= %f\n",div);
return 0;
}
Output:-
Enter number1:
10
Enter number2:
5
sum= 15
subtraction= 5
Multiplication= 50
Division= 2.000000
Q15. Program to display details of student two (Name, roll
no, marks) using structure
#include <stdio.h>
struct student
{
char name[50];
int roll
float marks;
} s;
int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}
Output:-
Enter information:
Enter name: Piyush
Enter roll number: 40
Enter marks: 60
Displaying Information:
Name: Piyush
Roll number: 40
Marks: 60.0
Q16. Program to display details of employee using array of
structure.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[30];
int id;
double salary;
} Employee;
int main()
{
//number of employees
int n=2;
//array to store structure values of all employees
Employee employees[n];
//Taking each employee detail as input
printf("Enter %d Employee Details \n \n",n);
for(int i=0; i<n; i++){
printf("Employee %d:- \n",i+1);
//Name
printf("Name: ");
scanf("%[^\n]s",employees[i].name);
//ID
printf("Id: ");
scanf("%d",&employees[i].id);
//Salary
printf("Salary: ");
scanf("%lf",&employees[i].salary);
//to consume extra '\n' input
char ch = getchar();
printf("\n");
}
//Displaying Employee details
printf("-------------- All Employees Details ---------------\n");
for(int i=0; i<n; i++){
printf("Name \t: ");
printf("%s \n",employees[i].name);
printf("Id \t: ");
printf("%d \n",employees[i].id);
printf("Salary \t: ");
printf("%.2lf \n",employees[i].salary);
printf("\n");
}
return 0;
}
Output:-
Enter 2 Employee Details
Employee 1:-
Name: rohan
Id: 01
Salary: 5000
Employee 2:-
Name: suhavi
Id: 30
Salary: 10000
-------------- All Employees Details ---------------
Name : rohan
Id :1
Salary : 5000.00
Name : suhavi
Id : 30
Salary : 10000.00
Q17. Program to access member of structures using pointers.
#include<stdio.h>
struct student
{
char *name;
int age;
float per;
};
int main()
{
struct student o={"RAM",25,75.5};
struct student *ptr=&o;
printf("\nName : %s",(*ptr).name);
printf("\nAge : %d",ptr->age);
printf("\nPercent : %f",ptr->per);
return 0;
}
Output:-
Name : RAM
Age : 25
Percent : 75.500000
Q18. Program for passing structure to a function.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:-
Id is: 1
Name is: Raju
Percentage is: 86.500000
Q19. Program for returning a structure from a function.
#include <stdio.h>
// creating a student structure template
struct student {
char firstname[64];
char lastname[64];
char id[64];
int score;
};
// function declaration
struct student getDetail(void);
void displayDetail(struct student std);
int main(void) {
// creating a student structure array variable
struct student stdArr[3];
// other variables
int i;
// taking user input
for (i = 0; i < 3; i++) {
printf("Enter detail of student #%d\n", (i+1));
stdArr[i] = getDetail();
}
// output
for (i = 0; i < 3; i++) {
printf("\nStudent #%d Detail:\n", (i+1));
displayDetail(stdArr[i]);
}
return 0;
}
struct student getDetail(void) {
// temp structure variable
struct student std;
printf("Enter First Name: ");
scanf("%s", std.firstname);
printf("Enter Last Name: ");
scanf("%s", std.lastname);
printf("Enter ID: ");
scanf("%s", std.id);
printf("Enter Score: ");
scanf("%d", &std.score);
return std;
}
void displayDetail(struct student std) {
printf("Firstname: %s\n", std.firstname);
printf("Lastname: %s\n", std.lastname);
printf("ID: %s\n", std.id);
printf("Score: %d\n", std.score);
}
Output:-
/tmp/PKzHV1ICGU.o
Enter detail of student #1
Enter First Name: Piyush
Enter Last Name: Gurjar
Enter ID: 50
Enter Score: 9
Student #1 Detail:
Firstname: Piyush
Lastname: Gurjar
ID: 50
Score: 9
Student #2 Detail:
Firstname: Dolly
Lastname: gurjar
ID: 80
Score: 8
Student #3 Detail:
Firstname: Pranjal
Lastname: Gurjar
ID: 60
Score: 7
Q20. Program to display details of student two (Name, roll
no, marks) with the help of union.
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output:-
Enter The Information of Students :
Enter Name : Piyush
Enter Roll No. : 23
Enter marks : 100
Displaying Information
Name: Piyush
Roll: 23
Marks: 100.00
Q21. Program to demonstrate the memory allocation in
structure and union.
#include <stdio.h>
char * unit(size) {
return size > 1 ? "bytes" : "byte";
}
int main() {
unsigned long c_size = sizeof(char);
unsigned long i_size = sizeof(int);
unsigned long l_size = sizeof(long);
unsigned long f_size = sizeof(float);
unsigned long d_size = sizeof(double);
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
return 0;
}
Output:-
Enter number of elements: 3
Enter elements: 100
20
30
Sum = 150
Q23. Program to allocate memory of array at run time.
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output:-
Enter number of elements:5
Entered number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
Q24. Program to print the day of week.
#include <stdio.h>
#include <stdio.h>
char
*(a[7])={"monday","tuesday","wednesday","thursday","friday
","saturday","sunday"};
scanf("%d",&m);
weekday(&m);
return 0;
}
void weekday(int *m)
{
if(*m>7 || *m<1)
{
printf("invalid input");
}
else
printf("%s",a[*m-1]);
}
Output:-
Enter the week day:2
Tuesday
Q25. Program to print month of a year
#include <stdio.h>
int main() {
int mno;
printf("\nInput a number between 1 to 12 to get the
month name: ");
scanf("%d", &mno);
switch(mno) {
case 1 : printf("January\n"); break;
case 2 : printf("February\n"); break;
case 3 : printf("March\n"); break;
case 4 : printf("April\n"); break;
case 5 : printf("May\n"); break;
case 6 : printf("June\n"); break;
case 7 : printf("July\n"); break;
case 8 : printf("August\n"); break;
case 9 : printf("September\n"); break;
case 10 : printf("October\n"); break;
case 11 : printf("November\n"); break;
case 12 : printf("December\n"); break;
default : printf("Input a number between 1 to 12.");
}
return 0;
}
Output:-
Input a number between 1 to 12 to get the month name: 6
June
Q26. Program to calculate area of circle using macro
#include<stdio.h>
#define PI 3.14
int main()
{
float r, area;
area = PI * r * r;
return 0;
}
Output:-
Enter Radius of Circle
20
Area of Circle is 1256.000000
Q27. Program to calculate area of circle using macro function
#include<stdio.h>
float area(int r)
{
return (22*r*r)/7;
}
int main()
{
int r;
float a;
printf("enter radius of the circle: ");
scanf("%d",&r);
a=area(r);
printf("area of the circle: %f\n",a);
return 0;
}
Output:-
enter radius of the circle: 30
area of the circle: 2828.000000
Q28. Program to count number of words, number of
character and number of lines from a given text file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}
return 0;
}
Output:-
Enter source file path: data\file3.txt
int main ()
{
FILE * fptr;
int i,n;
char str[100];
char fname[20]="test.txt";
char str1;
printf("\n\n Write multiple lines in a text file and read the file :\n");
printf("------------------------------------------------------------\n");
printf(" Input the number of lines to be written : ");
scanf("%d", &n);
printf("\n :: The lines are ::\n");
fptr = fopen (fname,"w");
for(i = 0; i < n+1;i++)
{
fgets(str, sizeof str, stdin);
fputs(str, fptr);
}
fclose (fptr);
/*-------------- read the file -------------------------------------*/
fptr = fopen (fname, "r");
printf("\n The content of the file %s is :\n",fname);
str1 = fgetc(fptr);
while (str1 != EOF)
{
printf ("%c", str1);
str1 = fgetc(fptr);
}
printf("\n\n");
fclose (fptr);
return 0;
}
Output:-
Write multiple lines in a text file and read the file :
------------------------------------------------------------
Input the number of lines to be written : 4
test line 1
test line 2
test line 3
test line 4
Q30. Write a program in C to copy a file in another name
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:-
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt
Q31.Program to demonstrate file operation for Creating a
new file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Variable to store user content */
char data[DATA_SIZE];
/*
* Open file in w (write) mode.
* "data/file1.txt" is complete path to create file
*/
fPtr = fopen("data/file1.txt", "w");
/* fopen() return NULL if last operation was unsuccessful */
if(fPtr == NULL)
{
/* File not created hence exit */
printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
/* Success message */
printf("File created and saved successfully. :) \n");
return 0;
}
Output:-
Enter contents to store in file :
Hurray!!! I learned to create file in C programming. I also learned to
write contents to file. Next, I will learn to read contents from file on
Codeforwin. Happy coding ;)
File created and saved successfully. :)
32. Write a program in C to merge two files and write it in a
new file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Output:-
Merged file1.txt and file2.txt into file3.txt
Q33.Write a program in C to encrypt a text file.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char fname[20], ch;
FILE *fpts, *fptt;
fpts=fopen(fname, "r");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(1);
}
fptt=fopen("temp.txt", "w");
if(fptt==NULL)
{
printf(" Error in creation of file temp.txt ..!!");
fclose(fpts);
exit(2);
}
while(1)
{
ch=fgetc(fpts);
if(ch==EOF)
{
break;
}
else
{
ch=ch+100;
fputc(ch, fptt);
}
}
fclose(fpts);
fclose(fptt);
fpts=fopen(fname, "w");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(3);
}
fptt=fopen("temp.txt", "r");
if(fptt==NULL)
{
printf(" File does not exists or error in opening..!!");
fclose(fpts);
exit(4);
}
while(1)
{
ch=fgetc(fptt);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fpts);
}
}
printf(" File %s successfully encrypted ..!!\n\n", fname);
fclose(fpts);
fclose(fptt);
}
Output:-
Encrypt a text file :
--------------------------
Input the name of file to encrypt : test.txt
File test.txt successfully encrypted ..!!
34.Write a program in C to decrypt a previously encrypted
file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
char c;
clrscr();
printf("Enter the text to be stored in the file.\n");
printf("Use ^Z or F6 at the end of the text and press ENTER :
\n\n");
fptr = fopen("ENCDEC.DAT","w");
while((c = getchar()) != EOF)
fputc(c, fptr);
fclose(fptr);
printf("\n\nData output in encrypted form : \n\n");
fptr = fopen("ENCDEC.DAT", "r");
while((c = fgetc(fptr)) != EOF)
printf("%c", c + 1);
fclose(fptr);
printf("\n\nData output in decrypted form : \n\n");
fptr = fopen("ENCDEC.DAT", "r");
while((c = fgetc(fptr)) != EOF)
printf("%c", c);
fclose(fptr);
getch();
}
Output:-
Enter the text to be stored in the file.
Use ^Z or F6 at the end of the text and press ENTER :
Computer Practice - II
D.D. Publications
^Z
Data output in encrypted form :
Dpnqvufs!Qsbdujdf!.!JJ
E/E/!Qvcmjdbujpot
Data output in decrypted form :
Computer Practice - II
D.D. Publications
35.Write a program in C to remove a file from the disk.
#include <stdio.h>
void main()
{
int status;
char fname[20];
printf("\n\n Remove a file from the disk :\n");
printf("----------------------------------\n");
printf(" Input the name of file to delete : ");
scanf("%s",fname);
status=remove(fname);
if(status==0)
{
printf(" The file %s is deleted successfully..!!\n\n",fname);
}
else
{
printf(" Unable to delete file %s\n\n",fname);
}
}
Output:-
Remove a file from the disk :
----------------------------------
Input the name of file to delete : file.txt
The file.txt is remove successfully
Q36.Program to draw a circle and fill Red color in it.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
int main()
{
int gdriver = DETECT,gmode;
initgraph(&gdriver,&gmode,"C:\\TC\\BGI");
setfillstyle(SOLID_FILL,Red);
circle(200,200,50);
floodfill(202,202,15);
getch();
}
Output:-
Q37.Write a program to draw a rectangle.
#include <graphics.h>
// Driver code
int main()
{
// gm is Graphics mode which is a computer display
// mode that generates image using pixels.
// DETECT is a macro defined in "graphics.h" header file
int gd = DETECT, gm;
// rectangle function
rectangle(left, top, right, bottom);
getch();
// closegraph function closes the graphics
// mode and deallocates all memory allocated
// by graphics system .
closegraph();
return 0;
}
Output:-
Q38.Write a program to implement traffic signal.
#include<graphics.h>
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
main()
{
int gd = DETECT, gm, midx, midy;
midx = getmaxx()/2;
midy = getmaxy()/2;
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 3);
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy-10, "Traffic Light Simulation");
outtextxy(midx, midy+10, "Press any key to start");
getch();
cleardevice();
setcolor(WHITE);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy-50, 22);
setfillstyle(SOLID_FILL,RED);
floodfill(midx, midy-50,WHITE);
setcolor(BLUE);
outtextxy(midx,midy-50,"STOP");
delay(2000);
graphdefaults();
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy, 20);
setfillstyle(SOLID_FILL,YELLOW);
floodfill(midx, midy,WHITE);
setcolor(BLUE);
outtextxy(midx-18,midy-3,"READY");
delay(2000);
cleardevice();
setcolor(WHITE);
rectangle(midx-30,midy-80,midx+30,midy+80);
circle(midx, midy+50, 22);
setfillstyle(SOLID_FILL,GREEN);
floodfill(midx, midy+50,WHITE);
setcolor(BLUE);
outtextxy(midx-7,midy+48,"GO");
setcolor(RED);
settextstyle(SCRIPT_FONT, HORIZ_DIR, 4);
outtextxy(midx-150, midy+100, "Press any key to exit...");
getch();
closegraph();
return 0;
}
Output:-
Q39.Write a program to move a circle using suitable
annimations.
#include <stdio.h>
#include <graphics.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int i, x, y, flag=0;
initgraph(&gd, &gm, "C:\\TC\\BGI");
while (!kbhit()) {
if(y >= getmaxy()-30 || y <= 30)
flag = !flag;
/* draws the gray board */
setcolor(RED);
setfillstyle(SOLID_FILL, RED);
circle(x, y, 30);
floodfill(x, y, RED);
/* clears screen */
cleardevice();
if(flag){
y = y + 5;
} else {
y = y - 5;
}
}
closegraph();
return 0;
}
Output:-
Q40.Write a pogram to simulate a moving car. Draw car
using simple shapes like line, circle and polygon.
#include <stdio.h>
#include <graphics.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int i, maxx, midy;
/* Draw Car */
setcolor(YELLOW);
setfillstyle(SOLID_FILL, RED);
closegraph();
return 0;
}
Output:-