You are on page 1of 52

Defining and initializing strings, Reading and writing a string, Processing

of string, Character arithmetic, String manipulation functions


// STRING MANIPULATION AND TYPE CASTING FUNCTIONS
1. stricmp

#include <stdio.h>
#include <string.h>
int main(void)
{
/* Compare two strings as lowercase */
if (0 == stricmp("hello", "HELLO"))
printf("The strings are equivalent.\n");
else
printf("The strings are not equivalent.\n");
return 0;
}
2. itoa

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

int main()
{
int a=54325;
char buffer[20];
itoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);

itoa(a,buffer,10); // here 10 means decimal


printf("Decimal value = %s\n", buffer);

itoa(a,buffer,16); // here 16 means Hexadecimal


printf("Hexadecimal value = %s\n", buffer);
return 0;
}
3. strlwr

#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
4. strupr

#include<stdio.h>
#include<string.h>

int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
return 0;
}
5. strrev

#include<stdio.h>
#include<string.h>

int main()
{
char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));

return 0;
}
6. ftoa

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

int main()
{
char res[20];
float n = 233.007;
ftoa(n, res, 4);
printf("\n\"%s\"\n", res);
return 0;
}

//STRING MANIPULATION WITHOUT FUNCTIONS


1. String reverse

#include<stdio.h>
#include<string.h>

int main() {
char str[100], temp;
int i, j = 0;

printf("\nEnter the string :");


gets(str);

i = 0;
j = strlen(str) - 1;

while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}

printf("\nReverse string is :%s", str);


return (0);
}

2. String copy
3. #include <stdio.h>
4. int main()
5. {
6. char s1[100], s2[100], i;
7.
8. printf("Enter string s1: ");
9. scanf("%s",s1);
10.
11. for(i = 0; s1[i] != '\0'; ++i)
12. {
13. s2[i] = s1[i];
14. }
15.
16. s2[i] = '\0';
17. printf("String s2: %s", s2);
18.
19. return 0;
20.}

3. String compare

#include<stdio.h>

int main() {
char str1[30], str2[30];
int i;

printf("\nEnter two strings :");


gets(str1);
gets(str2);

i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
printf("str1 < str2");
else
printf("str1 = str2");

return (0);
}

4. String concatenation

#include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

// calculate the length of string s1


// and store it in i
for(i = 0; s1[i] != '\0'; ++i);

for(j = 0; s2[j] != '\0'; ++j, ++i)


{
s1[i] = s2[j];
}

s1[i] = '\0';
printf("After concatenation: %s", s1);

return 0;
}

5. String uppercase and lowercase

void stringLwr(char *s);


void stringUpr(char *s);

int main()
{
char str[100];

printf("Enter any string : ");


scanf("%[^\n]s",str);//read string with spaces

stringLwr(str);
printf("String after stringLwr : %s\n",str);

stringUpr(str);
printf("String after stringUpr : %s\n",str);
return 0;
}

/******** function definition *******/


void stringLwr(char *s)
{
int i=0;
while(s[i]!='\0')
{
if(s[i]>='A' && s[i]<='Z'){
s[i]=s[i]+32;
}
++i;
}
}

void stringUpr(char *s)


{
int i=0;
while(s[i]!='\0')
{
if(s[i]>='a' && s[i]<='z'){
s[i]=s[i]-32;
}
++i;
}
}

String Conversion Functions, Pointer declaration and initialization, Types


of pointers - dangling , wild, null, generic (void)
Write a program to find Average marks of student using pointers?
ANS- #include<stdio.h>
void main()
{
int m1,m2,m3,total;
float per;
Int *p,*p1,*p2;

printf("Enter 3 Nos.");
scanf("%d%d%d",&m1,&m2,&m3);
p=&m1;p1=&m2;p2=&m3;
Total=*p+*p1+*p2;
per=total*100/300;
printf(\npercentage marks %f,per
getch();
}

Explain the various string Conversion function?


Ans-. itoa
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int a=54325;
char buffer[20];
itoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);

itoa(a,buffer,10); // here 10 means decimal


printf("Decimal value = %s\n", buffer);

itoa(a,buffer,16); // here 16 means Hexadecimal


printf("Hexadecimal value = %s\n", buffer);
return 0;
}
ftoa
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char res[20];
float n = 233.007;
ftoa(n, res, 4);
printf("\n\"%s\"\n", res);
return 0;
}
atoi
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char str[]="12";
int val;
printf("%s",str);
val=atoi(str);
printf("%d",val);
getch();
}
atof
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
char str[]="12.5";
float val;
printf("%s",str);
val="12.5";
val=atof(str);
printf("%f",val);
getch();
}

Give the difference between itoa() and ftoa() functions?

Ans-

. itoa . ftoa
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>

int main() int main()


{ {
int a=54325; char res[20];
char buffer[20]; float n = 233.007;
itoa(a,buffer,2); // here 2 means ftoa(n, res, 4);
binary printf("\n\"%s\"\n", res);
printf("Binary value = %s\n", return 0;
buffer); }

itoa(a,buffer,10); // here 10 means


decimal
printf("Decimal value = %s\n",
buffer);

itoa(a,buffer,16); // here 16 means


Hexadecimal
printf("Hexadecimal value = %s\n",
buffer);
return 0;
}

write short note on


i)ftoa()
ans-. ftoa
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char res[20];
float n = 233.007;
ftoa(n, res, 4);
printf("\n\"%s\"\n", res);
return 0;
}

Pointer expressions and arithmetic, Pointer operators, Operations on


pointers, Passing pointer to a function
Q:1 C program to swap two numbers using pointers.

#include <stdio.h>

// function : swap two numbers using pointers


void swap(int *a,int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}

int main()
{
int num1,num2;

printf("Enter value of num1: ");


scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);

//print values before swapping


printf("Before Swapping: num1=%d, num2=%d\n",num1,num2);

//call function by passing addresses of num1 and num2


swap(&num1,&num2);

//print values after swapping


printf("After Swapping: num1=%d, num2=%d\n",num1,num2);

return 0;
}

Q: 2 WAP in C program to change the value of constant integer using pointers.

#include <stdio.h>
int main()
{
const int a=10; //declare and assign constant integer
int *p; //declare integer pointer
p=&a; //assign address into pointer p
printf("Before changing - value of a: %d",a);

//assign value using pointer


*p=20;

printf("\nAfter changing - value of a: %d",a);


printf("\nWauuuu... value has changed.");

return 0;
}
Q: 3 C program to print a string character by character using pointer
/*C program to print a string using pointer.*/
#include <stdio.h>
int main()
{
char str[100];
char *ptr;

printf("Enter a string: ");


gets(str);

//assign address of str to ptr


ptr=str;

printf("Entered string is: ");


while(*ptr!='\0')
printf("%c",*ptr++);

return 0;
}

Q: 4 C program to count vowels and consonants in a string using pointer


/*C 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);
//assign address of str to ptr
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++;
//increase the pointer, to point next character
ptr++;
}

printf("Total number of VOWELS: %d, CONSONANT: %d\n",cntV,cntC);


return 0;
}

Q:5 C program to show pointer arithmetic


#include<stdio.h>
#include<conio.h>

void main() {
int int_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;

/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;

printf("Address of int_var = %u\n", int_ptr);


printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);

/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n", int_ptr);
printf("After increment address in char_ptr = %u\n", char_ptr);
printf("After increment address in float_ptr = %u\n\n", float_ptr);

/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;

printf("After addition address in int_ptr = %u\n", int_ptr);


printf("After addition address in char_ptr = %u\n", char_ptr);
printf("After addition address in float_ptr = %u\n\n", float_ptr);

getch();
return 0;
}

Pointer and one dimensional array, Pointer to a group of one dimensional


arrays, Array of pointers
Array and Pointer Example in C
#include <stdio.h>
int main( )
{
/*Pointer variable*/
int *p;

/*Array declaration*/
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;

/* Assigning the address of val[0] the pointer


* You can also write like this:
* p = var;
* because array name represents the address of the first element
*/
p = &val[0];

for ( int i = 0 ; i<7 ; i++ )


{
printf("val[%d]: value is %d and address is %p\n", i, *p, p);
/* Incrementing the pointer so that it points to next element
* on every increment.
*/
p++;
}
return 0;
}
Output:
val[0]: value is 11 and address is 0x7fff51472c30
val[1]: value is 22 and address is 0x7fff51472c34
val[2]: value is 33 and address is 0x7fff51472c38
val[3]: value is 44 and address is 0x7fff51472c3c
val[4]: value is 55 and address is 0x7fff51472c40
val[5]: value is 66 and address is 0x7fff51472c44
val[6]: value is 77 and address is 0x7fff51472c48

Summation of Array using Pointer in C


#include<stdio.h>
#include<conio.h>
int main()
{
int numArray[10];
int i, sum = 0;
int *ptr;

printf("\nEnter 10 elements : ");

for (i = 0; i < 10; i++)


scanf("%d", &numArray[i]);

ptr = numArray;

for (i = 0; i < 10; i++)


{
sum = sum + *ptr;
ptr++;
}

printf("The sum of array elements : %d", sum);


}
Output:
Enter 10 elements : 11 12 13 14 15 16 17 18 19 20
The sum of array elements is 155
C program to find the maximum number within n given numbers using
pointers.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[5],*p,i,h=0;
clrscr();

p=a;
for(i=0;i<5;i++)
{
printf("\nENTER NUMBER %d: ",i+1);
scanf("%d",(p+i));
}
h=*p;
for(i=1;i<5;i++)
{
if(*(p+i)>h)
h=*(p+i);
}
printf("\nTHE HIGHEST NUMBER IS %d",h);
getch();
}
Output:
Enter number : 8
Enter number : 1
Enter number : 4
Enter number : 6
Enter number : 10
The highest number is: 10

Three integers which are stored in an array of pointers


#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */
}

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

return 0;
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
array of pointers to character to store a list of strings
#include <stdio.h>

const int MAX = 4;

int main () {

char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};

int i = 0;

for ( i = 0; i < MAX; i++) {


printf("Value of names[%d] = %s\n", i, names[i] );
}

return 0;
}
Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

Array of pointer
#include <stdio.h>

#include <stdio.h>
int main()
{
char *fruit[] = {
"watermelon",
"banana",
"pear",
"apple",
"coconut",
"grape",
"blueberry"
};
int x;

for(x=0;x<7;x++)
puts(fruit[x]);
return(0);
}
Output:
watermelon
banana
pear
apple
coconut
grape
blueberry

Pointer to array
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
}
Output:
12345

Declaration of a structure, Definition and initialization of structures,


Accessing structures
Program 1: Write a C program to store information of one student using
structure.
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
int main()
{
printf("Enter information:\n");

printf("Enter name: ");


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

printf("Enter roll number: ");


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

printf("Enter marks: ");


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

printf("Displaying Information:\n");

printf("Name: ");
puts(s.name);

printf("Roll number: %d\n",s.roll);

printf("Marks: %.1f\n", s.marks);

return 0;
}

Program 2: Write a C program to store the information of 10 students


using structure.
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];

int main()
{
int i;

printf("Enter information of students:\n");


// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;

printf("\nFor roll number%d,\n",s[i].roll);

printf("Enter name: ");


scanf("%s",s[i].name);

printf("Enter marks: ");


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

printf("\n");
}

printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}
Program 3: Write a C program to add two distances in inch- feet system
using structure.
#include <stdio.h>

struct Distance
{
int feet;
float inch;
} d1, d2, sumOfDistances;

int main()
{
printf("Enter information for 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);

printf("\nEnter information for 2nd distance\n");


printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);

sumOfDistances.feet = d1.feet+d2.feet;
sumOfDistances.inch = d1.inch+d2.inch;

// If inch is greater than 12, changing it to feet.

if (sumOfDistances.inch>12.0)
{
sumOfDistances.inch = sumOfDistances.inch-12.0;
++sumOfDistances.feet;
}

printf("\nSum of distances = %d\'-%.1f\"",sumOfDistances.feet,


sumOfDistances.inch);
return 0;
}

Program 4: Write a C program to Add Two Complex Numbers using


structure.
#include <stdio.h>
struct complex
{
float real;
float imag;
} complex;
complex add(complex n1,complex n2);

int main()
{
complex n1, n2, temp;

printf("For 1st complex number \n");


printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary part respectively:\n");
scanf("%f %f", &n2.real, &n2.imag);

temp = add(n1, n2);


printf("Sum = %.1f + %.1fi", temp.real, temp.imag);

return 0;
}

complex add(complex n1, complex n2)


{
complex temp;

temp.real = n1.real + n2.real;


temp.imag = n1.imag + n2.imag;

return(temp);
}

Program 5: Write a C Program to Calculate Difference Between Two Time


Periods using structure
#include <stdio.h>
struct TIME
{
int seconds;
int minutes;
int hours;
};
void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct
TIME *diff);

int main()
{
struct TIME startTime, stopTime, diff;

printf("Enter start time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &startTime.hours, &startTime.minutes,
&startTime.seconds);

printf("Enter stop time: \n");


printf("Enter hours, minutes and seconds respectively: ");
scanf("%d %d %d", &stopTime.hours, &stopTime.minutes,
&stopTime.seconds);

// Calculate the difference between the start and stop time period.
differenceBetweenTimePeriod(startTime, stopTime, &diff);

printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours,


startTime.minutes, startTime.seconds);
printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds);
printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);

return 0;
}

void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct


TIME *diff)
{
if(stop.seconds > start.seconds){
--start.minutes;
start.seconds += 60;
}

diff->seconds = start.seconds - stop.seconds;


if(stop.minutes > start.minutes){
--start.hours;
start.minutes += 60;
}

diff->minutes = start.minutes - stop.minutes;


diff->hours = start.hours - stop.hours;
}

Structures and pointers, Nested structures, Declaration of a union,


Definition and initialization of unions
Program 1: WAP to create one structure inside other structure.
Solution:
#include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;

int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n", stu_data.clg_data.college_id);


printf(" College Name is: %s \n", stu_data.clg_data.college_name);
return 0;
}

Program 2: WAP to create structure of book( Title,Author,Book_Id) and


display the information of two books by using pointer to structure
Solution:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );

/* print Book2 info by passing address of Book2 */


printBook( &Book2 );

return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}

Program 3: WAP to create a union named student with members name,


subject and percentage storing record of 2 students.
#include <stdio.h>
#include <string.h>

union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}

Program 4: WAP to display the total memory size occupied by the union
Solution:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Program 5: WAP to access different members of a union using dot
operator.
Solution:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);
return 0;
}

Program 6:WAP to demonstrate difference between structure and union in


terms of size of memory
Solution:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}
Program 7:Write a program to display age and weight of a person using
pointer to structures.
Solution:
#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of
person1

printf("Enter age: ");


scanf("%d",&(*personPtr).age);

printf("Enter weight: ");


scanf("%f",&(*personPtr).weight);

printf("Displaying age and weight: ");


printf("%d%f",(*personPtr).age,(*personPtr).weight);

return 0;
}
Program 8:WAP to access structure member through pointer using
dynamic memory allocation
Solution:
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};
int main()
{
struct person *ptr;
int i, num;

printf("Enter number of persons: ");


scanf("%d", &num);

ptr = (struct person*) malloc(num * sizeof(struct person));


// Above statement allocates the memory for n structures with pointer
personPtr pointing to base address */

for(i = 0; i < num; ++i)


{
printf("Enter name, age and weight of the person respectively:\n");
scanf("%s%d%f", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->weight);
}

printf("Displaying Information:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);

return 0;
}
Program 9:Write a program to store record of an employee using nested
structure.
Solution:
#include<stdio.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};
void main()
{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);

}
Program 10:Write a program access members of a union through pointer
Solution:
union test
{
int x;
char y;
};

int main()
{
union test p1;
p1.x = 65;

// p2 is a pointer to union p1
union test *p2 = &p1;

// Accessing union members using pointer


printf("%d %c", p2->x, p2->y);
return 0;

}
Dynamic memory management functions (malloc, Calloc, Realloc and
Free), Memory leak
Q1: Write a C program to input and print text using Dynamic Memory
Allocation.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int n;
char *text;

printf("Enter limit of the text: ");


scanf("%d",&n);

/*allocate memory dynamically*/


text=(char*)malloc(n*sizeof(char));

printf("Enter text: ");


scanf(" "); /*clear input buffer*/
gets(text);

printf("Inputted text is: %s\n",text);

/*Free Memory*/
free(text);
return 0;
}

Q2: Write a C program to read a one dimensional array, print sum of all
elements along with inputted array elements using Dynamic Memory
Allocation.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *arr;
int limit,i;
int sum=0;

printf("Enter total number of elements: ");


scanf("%d",&limit);

/*allocate memory for limit elements dynamically*/


arr=(int*)malloc(limit*sizeof(int));

if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}

printf("Enter %d elements:\n",limit);
for(i=0; i<limit; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
/*calculate sum*/
sum=sum + *(arr+i);
}

printf("Array elements are:");


for(i=0; i<limit; i++)
printf("%3d ",*(arr+i));

printf("\nSum of all elements: %d\n",sum);


return 0;
}

Q3: Write a C program to read and print the student details using structure and
Dynamic Memory Allocation.
#include <stdio.h>
#include <stdlib.h>

/*structure declaration*/
struct student
{
char name[30];
int roll;
float perc;
};

int main()
{
struct student *pstd;

/*Allocate memory dynamically*/


pstd=(struct student*)malloc(1*sizeof(struct student));

.
if(pstd==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}

/*read and print details*/


printf("Enter name: ");
gets(pstd->name);
printf("Enter roll number: ");
scanf("%d",&pstd->roll);
printf("Enter percentage: ");
scanf("%f",&pstd->perc);

printf("\nEntered details are:\n");


printf("Name: %s, Roll Number: %d, Percentage: %.2f\n",pstd->name,pstd-
>roll,pstd->perc);

return 0;
}

Q4: write a C program to create memory for int, char and float variable at run
time.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *iVar;
char *cVar;
float *fVar;

/*allocating memory dynamically*/

iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));

printf("Enter integer value: ");


scanf("%d",iVar);

printf("Enter character value: ");


scanf(" %c",cVar);

printf("Enter float value: ");


scanf("%f",fVar);

printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);

/*free allocated memory*/


free(iVar);
free(cVar);
free(fVar);

return 0;
}
Q5: Write a C program find largest element Using Dynamic Memory
Allocation.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, num;
float *data;

printf("Enter total number of elements(1 to 100): ");


scanf("%d", &num);

// Allocates the memory for 'num' elements.


data = (float*) calloc(num, sizeof(float));

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

printf("\n");

// Stores the number entered by the user.


for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}

// Loop to store largest number at address data


for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
if(*data < *(data + i))
*data = *(data + i);
}

printf("Largest element = %.2f", *data);

return 0;
}
Q6: Write a program to copy a string to another using dynamic memory
allocation concept.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *mem_alloc;
/* memory allocated dynamically */
mem_alloc = calloc( 15, sizeof(char) );

if( mem_alloc== NULL )


{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc, "hello welocome");
}

printf("Dynamically allocated memory content : %s\n", mem_alloc );


free(mem_alloc);
}
Q7: Write a program to copy one string to another using dynamic memory
allocation and reallocate the size of the string and then display the result.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
char *mem_alloc;
/* memory allocated dynamically */
mem_alloc = malloc( 20 * sizeof(char) );

if( mem_alloc == NULL )


{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"Hello LPU");
}

printf("Dynamically allocated memory content : " \ "%s\n", mem_alloc );


mem_alloc=realloc(mem_alloc,100*sizeof(char));

if( mem_alloc == NULL )


{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"space is extended upto 100 characters");
}

printf("Resized memory : %s\n", mem_alloc );


free(mem_alloc);
}

The FILE structure, Categories of files, Text and binary files


1. Write a C program to copy the contents of one file into another using
fputc
#include<stdio.h>
#include<process.h>
void main() {
FILE *fp1, *fp2;
char a;
clrscr();

fp1 = fopen("test.txt", "r");


if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}

fp2 = fopen("test1.txt", "w");


if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}

do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);

fcloseall();
getch();
}
Output:

Content will be written successfully to file

2. Write a C Program to read last n characters of the file using


appropriate file function.

#include<stdio.h>

int main() {

FILE *fp;
char ch;
int num;
long length;

printf("Enter the value of num : ");


scanf("%d", &num);

fp = fopen("test.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}

fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);

do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return(0);
}

Output:

Enter the value of n : 4


.com
3. Write a C program to convert the file contents in Upper-case &
Write Contents in a output file.

#include<stdio.h>
#include<process.h>

void main() {
FILE *fp1, *fp2;
char a;
clrscr();

fp1 = fopen("test.txt", "r");


if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}

fp2 = fopen("test1.txt", "w");


if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}

do {
a = fgetc(fp1);
a = toupper(a);
fputc(a, fp2);
} while (a != EOF);

fcloseall();
getch();
}

4. Write a C Program to Compare two text/data files in C


Programming.

#include<stdio.h>

int main() {
FILE *fp1, *fp2;
int ch1, ch2;
char fname1[40], fname2[40];

printf("Enter name of first file :");


gets(fname1);

printf("Enter name of second file:");


gets(fname2);

fp1 = fopen(fname1, "r");


fp2 = fopen(fname2, "r");

if (fp1 == NULL) {
printf("Cannot open %s for reading ", fname1);
exit(1);
} else if (fp2 == NULL) {
printf("Cannot open %s for reading ", fname2);
exit(1);
} else {
ch1 = getc(fp1);
ch2 = getc(fp2);

while ((ch1 != EOF) && (ch2 != EOF) && (ch1 == ch2)) {


ch1 = getc(fp1);
ch2 = getc(fp2);
}

if (ch1 == ch2)
printf("Files are identical n");
else if (ch1 != ch2)
printf("Files are Not identical n");

fclose(fp1);
fclose(fp2);
}
return (0);
}

5. Write a C Program to Write on Data File and Read From Data File

#include<stdio.h>

struct Student {
int roll;
char name[12];
int percent;
} s1 = { 10, "SMJC", 80 };

int main() {
FILE *fp;
struct Student s2;

//Write details of s1 to file


fp = fopen("ip.txt", "w");
fwrite(&s1, sizeof(s1), 1, fp);
fclose(fp);

fp = fopen("ip.txt", "r");
fread(&s2, sizeof(s2), 1, fp);
fclose(fp);

printf("\nRoll : %d", s2.roll);


printf("\nName : %s", s2.name);
printf("\nPercent : %d", s2.percent);

return (0);
}

Output:
Roll : 10
Name : SMJC
Percent : 80

6. Write a C Program to Copy Text From One File to Other File

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

void main() {
FILE *fp1, *fp2;
char ch;
clrscr();
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output.txt", "w");

while (1) {
ch = fgetc(fp1);

if (ch == EOF)
break;
else
putc(ch, fp2);
}

printf("File copied Successfully!");


fclose(fp1);
fclose(fp2);
}

7. Write a program to display same source code as output in c


programming.

#include<stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen(__FILE__, "r");

do {
ch = getc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return 0;
}

Output:

#include<stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen(__FILE__, "r");

do {
ch = getc(fp);
putchar(ch);
} while (ch != EOF);

fclose(fp);
return 0;
}

Reading, Writing and Appending files


C program to find number of lines in a file
#include <stdio.h>
#define FILENAME "test.txt"
int main()
{
FILE *fp;
char ch;
int linesCount=0;
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL)
{
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
}
C program to create , open and close file
#include< stdio.h >
int main()
{

FILE *fp; /* file pointer*/


char fName[20];
printf("Enter file name to create :");
scanf("%s",fName);
/*creating (open) a file, in w: write mode*/
fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
return 0;
}

C program to create, write and read text in/from file

#include< stdio.h >


int main()
{

FILE *fp; /* file pointer*/


char fName[20];

printf("\nEnter file name to create :");


scanf("%s",fName);

/*creating (open) a file*/


fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}

printf("File created successfully.");


/*writting into file*/
putc('A',fp);
putc('B',fp);
putc('C',fp);

printf("\nData written successfully.");


fclose(fp);

/*again open file to read data*/


fp=fopen(fName,"r");
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n");
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
fclose(fp);
return 0;
}

C Program to Copy File into Another file


#include <stdio.h>

int main(int argc,char **argv)


{
FILE *fp1, *fp2;
char ch;
int pos;

if ((fp1 = fopen(argv[1],"r")) == NULL)


{
printf("\nFile cannot be opened");
return;
}
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen(argv[2], "w");
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
fcloseall();
return 0;
}

C Program to Count the number of words and characters in a file


#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr;
char ch;
int wrd=1,charctr=1;
char fname[20];
printf("\n\n Count the number of words and characters in a file :\n");
printf("---------------------------------------------------------\n");
printf(" Input the filename to be opened : ");
scanf("%s",fname);
fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf(" File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf(" The content of the file %s are : ",fname);
while(ch!=EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
ch=fgetc(fptr);
}
printf("\n The number of words in the file %s are : %d\n",fname,wrd-2);
printf(" The number of characters in the file %s are :
%d\n\n",fname,charctr-1);
}
fclose(fptr);
return 0;
}

C Program 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];
char str1;

printf("\n\n Append multiple lines at the end of a text file :\n");


printf("------------------------------------------------------\n");
printf(" Input the file name to be opened : ");
scanf("%s",fname);
fptr = fopen(fname, "a");
printf(" Input the number of lines to be written : ");
scanf("%d", &n);
printf(" The lines are : \n");
for(i = 0; i < n+1;i++)
{
fgets(str, sizeof str, stdin);
fputs(str, fptr);
}
fclose (fptr);
//----- Read the file after appended -------
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);
//------- End of reading ------------------
return 0;
}
C Program to Merge two files and write it in a new file
#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fold1, *fold2, *fnew;
char ch, fname1[20], fname2[20], fname3[30];

printf("\n\n Merge two files and write it in a new file :\n");


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

printf(" Input the 1st file name : ");


scanf("%s",fname1);
printf(" Input the 2nd file name : ");
scanf("%s",fname2);
printf(" Input the new file name where to merge the above two files : ");
scanf("%s",fname3);
fold1=fopen(fname1, "r");
fold2=fopen(fname2, "r");
if(fold1==NULL || fold2==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
}
fnew=fopen(fname3, "w");
if(fnew==NULL)
{
// perror("Error Message ");
printf(" File does not exist or error in opening...!!\n");
exit(EXIT_FAILURE);
}
while((ch=fgetc(fold1))!=EOF)
{
fputc(ch, fnew);
}
while((ch=fgetc(fold2))!=EOF)
{
fputc(ch, fnew);
}
printf(" The two files merged into %s file successfully..!!\n\n", fname3);
fclose(fold1);
fclose(fold2);
fclose(fnew);
}

C Program to Remove a file from the disk


#include <stdio.h>
int 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);
}

return 0;
}

C Program to Write to a text file using fprintf()


#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
C Program to Read from a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

C Program to Writing to a binary file using fwrite()

#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
C program to Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

You might also like