You are on page 1of 82

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:-

Pointer : Store and retrieve elements from an array :


------------------------------------------------------------
Input the number of elements to store in the array :5
Input 5 number of elements in the array :
element - 0 : 5
element - 1 : 7
element - 2 : 2
element - 3 : 9
element - 4 : 8
The elements you entered are :
element - 0 : 5
element - 1 : 7
element - 2 : 2
element - 3 : 9
element - 4 : 8
Q13. Program to demonstrate function pointers.

#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:-

Address of variable = 0x7ffcfd0b2e64


Address of a function = 0x55f8e8abb169
Q14. Program to perform Addition Subtraction Multiplication
Division using array of function pointers.

#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

Enter detail of student #2


Enter First Name: Dolly
Enter Last Name: gurjar
Enter ID: 80
Enter Score: 8

Enter detail of student #3


Enter First Name: Pranjal
Enter Last Name: Gurjar
Enter ID: 60
Enter Score: 7

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("Enter The Information of Students :\n\n");

printf("Enter Name : ");


scanf("%s",s.name);

printf("Enter Roll No. : ");


scanf("%d",&s.roll);

printf("Enter marks : ");


scanf("%f",&s.marks);

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);

printf("Char data type takes %ld %s\n", c_size, unit(c_size));


printf("Int data type takes %ld %s\n", i_size, unit(i_size));
printf("Long data type takes %ld %s\n", l_size, unit(l_size));
printf("Float data type takes %ld %s\n", f_size, unit(f_size));
printf("Double data type takes %ld %s\n", d_size,
unit(d_size));
}
Output:-
Char data type takes 1 byte
Int data type takes 4 bytes
Long data type takes 8 bytes
Float data type takes 4 bytes
Double data type takes 8 bytes
Q22. Program to demonstrate malloc and calloc.

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

// deallocating the memory


free(ptr);

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()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

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"};

void weekday(int *m);


..int main()
{
int m;
printf("Enter the week day:");

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;

printf("Enter Radius of Circle\n");


scanf("%f", &r);

area = PI * r * r;

printf("Area of Circle is %f\n", area);

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;

/* Input path of files to merge to third file */


printf("Enter source file path: ");
scanf("%s", path);

/* Open source files in 'r' mode */


file = fopen(path, "r");

/* Check if file opened successfully */


if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");

exit(EXIT_FAILURE);
}

/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;

/* Check new line */


if (ch == '\n' || ch == '\0')
lines++;

/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}

/* Print file statistics */


printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);

/* Close files to release resources */


fclose(file);

return 0;
}
Output:-
Enter source file path: data\file3.txt

Total characters = 106


Total words = 18
Total lines =3
Q29. Write a program in C to append multiple lines at the end
of a text file.
#include <stdio.h>

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

:: The lines are ::


test line 1
test line 2
test line 3
test line 4
The content of the file test.txt is :

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;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

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>

#define DATA_SIZE 1000

int main()
{
/* Variable to store user content */
char data[DATA_SIZE];

/* File pointer to hold reference to our file */


FILE * fPtr;

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

/* Input contents from user to store in file */


printf("Enter contents to store in file : \n");
fgets(data, DATA_SIZE, stdin);

/* Write data to file */


fputs(data, fPtr);

/* Close file to save file data */


fclose(fPtr);

/* 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");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)


{
puts("Could not open files");
exit(0);
}

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");

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;

printf("\n\n Encrypt a text file :\n");


printf("--------------------------\n");

printf(" Input the name of file to encrypt : ");


scanf("%s",fname);

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;

// location of left, top, right, bottom


int left = 150, top = 150;
int right = 450, bottom = 450;

// initgraph initializes the graphics system


// by loading a graphics driver from disk
initgraph(&gd, &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;

initgraph(&gd, &gm, "C:\\TC\\BGI");

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");

/* get mid positions in x and y-axis */


x = getmaxx()/2;
y = 30;

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);

/* delay for 50 milli seconds */


delay(50);

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

/* initialize graphic mode */


initgraph(&gd, &gm, "X:\\TC\\BGI");
/* maximum pixel in horizontal axis */
maxx = getmaxx();
/* mid pixel in vertical axis */
midy = getmaxy()/2;

for (i=0; i < maxx-150; i=i+5) {


/* clears screen */
cleardevice();

/* draw a white road */


setcolor(WHITE);
line(0, midy + 37, maxx, midy + 37);

/* Draw Car */
setcolor(YELLOW);
setfillstyle(SOLID_FILL, RED);

line(i, midy + 23, i, midy);


line(i, midy, 40 + i, midy - 20);
line(40 + i, midy - 20, 80 + i, midy - 20);
line(80 + i, midy - 20, 100 + i, midy);
line(100 + i, midy, 120 + i, midy);
line(120 + i, midy, 120 + i, midy + 23);
line(0 + i, midy + 23, 18 + i, midy + 23);
arc(30 + i, midy + 23, 0, 180, 12);
line(42 + i, midy + 23, 78 + i, midy + 23);
arc(90 + i, midy + 23, 0, 180, 12);
line(102 + i, midy + 23, 120 + i, midy + 23);
line(28 + i, midy, 43 + i, midy - 15);
line(43 + i, midy - 15, 57 + i, midy - 15);
line(57 + i, midy - 15, 57 + i, midy);
line(57 + i, midy, 28 + i, midy);
line(62 + i, midy - 15, 77 + i, midy - 15);
line(77 + i, midy - 15, 92 + i, midy);
line(92 + i, midy, 62 + i, midy);
line(62 + i, midy, 62 + i, midy - 15);
floodfill(5 + i, midy + 22, YELLOW);
setcolor(BLUE);
setfillstyle(SOLID_FILL, DARKGRAY);
/* Draw Wheels */
circle(30 + i, midy + 25, 9);
circle(90 + i, midy + 25, 9);
floodfill(30 + i, midy + 25, BLUE);
floodfill(90 + i, midy + 25, BLUE);
/* Add delay of 0.1 milli seconds */
delay(100);
}

closegraph();
return 0;
}
Output:-

You might also like