294 Computer Programming In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/ write) is returned. /* Open, Read and close a file: reading string by string */ # include <stdio.h> int main( ) { FILE *fp ; char data[50] ; printf(“Opening the file kiran.c in read mode”) ; fp = fopen(“kiran.c”, “r”) ; if ( fp == NULL ) { printf(“Could not open file kiran.c”) ; } printf(“Reading the file kiran.c”) ; while( fgets (data, 50, fp ) != NULL) printf( “%s”, data ) ; printf(“Closing the file kiran.c”) ; fclose(fp) ; } Output: Opening the file kiran.c in read mode Reading the file kiran.c Hai, How are you? Closing the file kiran.c CU IDOL SELF LEARNING MATERIAL (SLM)
File Management 295 / * Open, write and close a file : */ # include <stdio.h> # include <string.h> int main( ) { FILE *fp ; char data[50]; // opening an existing file printf(“Opening the file kiran.c in write mode”) ; fp = fopen(“kiran.c”, “w”) ; if ( fp == NULL ) { printf(“Could not open file kiran.c”) ; } printf(“\\n Enter some text from keyboard” \\ “to write in the file kiran.c”) ; // getting input from user while (strlen ( gets( data ) ) > 0) { // writing in the file fputs(data, fp) ; fputs(“\\n”, fp) ; } // closing the file printf(“Closing the file kiran.c” ; fclose(fp) ; } CU IDOL SELF LEARNING MATERIAL (SLM)
296 Computer Programming Output: OpenIng The File Kiran.c In Write Mode Enter Some Text From Keyboard To Write In The File Kiran.c Hai, How are you? Closing the file kiran.c 12.3.12 fseek() The fseek() function is used to set the file position indicator for the stream to a new position. This function accepts three arguments. The first argument is the FILE stream pointer returned by the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END. These three values (in order) depict the start of the file, the current position and the end of the file. Upon success, this function returns 0, otherwise it returns -1. int fseek(FILE *stream, long offset, int whence); To perform Input/Output Operation on files we need below functions. Table 12.4: Input/Output Functions S. No. Function Operation Syntax 1 getc() Read a character from a file getc( fp) 2 putc() Write a character in file putc(c, fp) 3 fprintf() To write set of data in file fprintf(fp, “control string”, list) 4 fscanf() To read set of data from file. fscanf(fp, “control string”, list) 5 getw() To read an integer from a file. getw(fp) 6 putw() To write an integer in file. putw(integer, fp) #include<stdio.h> #include<string.h> #define SIZE 1 #define NUMELEM 5 CU IDOL SELF LEARNING MATERIAL (SLM)
File Management 297 void main(void) { FILE* fd = NULL; char buff[100]; memset(buff,0,sizeof(buff)); fd = fopen(“kiran.txt”, “rw+”); if(NULL == fd) { printf(“\\n fopen() Error!!!\\n”); return 1; } printf(“\\n File opened successfully through fopen()\\n”); if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd)) { printf(“\\n fread() failed\\n”); return 1; } printf(“\\n Some bytes successfully read through fread()\\n”); printf(“\\n The bytes read are [%s]\\n”,buff); if(0 != fseek(fd,11,SEEK_CUR)) { printf(“\\n fseek() failed\\n”); return 1; } printf(“\\n fseek() successful\\n”); if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd)) CU IDOL SELF LEARNING MATERIAL (SLM)
298 Computer Programming { printf(“\\n fwrite() failed\\n”); return 1; } printf(“\\n fwrite() successful, data written to text file\\n”); fclose(fd); printf(“\\n File stream closed through fclose()\\n”); getch( ); } The code above assumes that you have a test file “kiran.txt” placed in the same location from where this executable will be run. Initially the content in file is: $ cat kiran.txt hello everybody Now, run the code : $ ./fileHandling File opened successfully through fopen() Some bytes successfully read through fread() The bytes read are [hello] fseek() successful fwrite() successful, data written to text file File stream closed through fclose() Again check the contents of the file kiran.txt. As you see below, the content of the file was modified. $ cat kiran.txt hello everybody hello CU IDOL SELF LEARNING MATERIAL (SLM)
File Management 299 Inbuilt File Handling Functions in C Language C programming language offers many inbuilt functions for handling files. They are given below: Table 12.5: File Handing Functions File handling functions Description fopen () fopen () function creates a new file or opens an existing file. fclose () fclose () function closes an opened file. getw () getw () function reads an integer from file. putw () putw () functions writes an integer to file. getc (), fgetc () getc () and fgetc () functions read a character from file. putc (), fputc () putc () and fputc () functions write a character to file. fgets () fgets () function reads string from a file, one line at a time. fputs () fputs () function writes string to a file. feof () feof () function finds end of file. fgetchar () fgetchar () function reads a character from keyboard. fgetc () fgetc () function reads a character from file. fprintf () fprintf () function writes formatted data to a file. fscanf () fscanf () function reads formatted data from a file. fgetchar () fgetchar () function reads a character from keyboard. fputchar () fputchar () function writes a character from keyboard. fseek () fseek () function moves file pointer position to given location. SEEK_SET SEEK_SET moves file pointer position to the beginning of the file. SEEK_CUR SEEK_CUR moves file pointer position to given location. SEEK_END SEEK_END moves file pointer position to the end of file. ftell () ftell () function gives current position of file pointer. rewind () rewind () function moves file pointer position to the beginning of the file. scanf () scanf () function reads formatted data from keyboard. sscanf () sscanf () function Reads formatted input from a string. remove () remove () function deletes a file. fflush () fflush () function flushes a file. CU IDOL SELF LEARNING MATERIAL (SLM)
300 Computer Programming 12.4 Summary So far the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: 1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”) 2. Opening an existing file (fopen) 3. Reading from file (fscanf or fgetc) 4. Writing to a file (fprintf or fputs) 5. Moving to a specific location in a file (fseek, rewind) 6. Closing a file (fclose) The text in the brackets denotes the functions used for performing those operations. 12.5 Key Words/Abbreviations File: While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. Append: Append mode is used to append or add data to the existing data of file (if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file. ASCII: Abbreviated from American Standard Code for Information Interchange. 12.6 Learning Activity 1. Write a program in C to copy contents of one file into other file.. ....................................................................................................................................... ....................................................................................................................................... 2. Write a program in C to write a string into file 5 times. ....................................................................................................................................... ....................................................................................................................................... CU IDOL SELF LEARNING MATERIAL (SLM)
File Management 301 3. Write a program in C to combine contents of two files in third file. ....................................................................................................................................... ....................................................................................................................................... 12.7 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. Write a short note on file handling in C. 2. What are the two types of file handling in C? 3. Explain different input/output functions for C. 4. Explain different file operations in C language. 5. Explain different file Modes in C Language. 6. Explain difference between text file and binary file handling in C programming language. 7. Distinguish between (1) fprintf() (ii) fscanf() 8. Explain what are different methods to read text file with syntax and suitable example. 9. Explain how to read and write binary files with suitable example. 10. Explain what are different methods to write into a file with syntax and suitable example. 11. Explain fopen( ), fclose( ) functions with suitable example. 12. Explain fgetc( ) and fgets( ) functions with suitable examples. 13. Explain getw( ) and putw( ) functions with suitable example. 14. Explain fread( ) and fwrite( ) and fseek( ) functions with suitable example. B. Multiple Choice/Objective Type Questions 1. What is the function of the mode ‘w+’? (a) create text file for writing, discard previous contents if any (b) create text file for update, discard previous contents if any (c) create text file for writing, do not discard previous contents if any (d) create text file for update, do not discard previous contents if any CU IDOL SELF LEARNING MATERIAL (SLM)
302 Computer Programming 2. EOF is an integer type defined in stdio. hand has a value ____________. (a) 1 (b) 0 (c) NULL (d) – 1 3. fwrite() can be used only with files that are opened in binary mode. (a) true (b) false 4. Which of the following true about FILE *fp? (a) FILE is a keyword in C for representing files and fp is a variable of FILE type. (b) FILE is a stream (c) FILE is a buffered stream (d) FILE is a structure and fp is a pointer to the structure of FILE typ 5. The first and second arguments of fopen() are (a) A character string containing the name of the file & the second argument is the mode (b) A character string containing the name of the user & the second argument is the mode (c) A character string containing file pointer & the second argument is the mode (d) None of the mentioned Answers: 1. (b), 2. (d), 3. (a), 4. (d), 5. (a) 12.8 References 1. https://www.geeksforgeeks.org/basics-file-handling-c/ 2. http://letsfindcourse.com/technical-questions/c/file-handling CU IDOL SELF LEARNING MATERIAL (SLM)
C Basics and Control Structure 303 PRACTICAL C BASICS AND CONTROL UNIT 1 STRUCTURE PROGRAMS TO UNDERSTAND THE BASIC DATA TYPE AND I/O 1. Write a program that reads two nos. from keyboard and gives their addition, subtraction, multiplication, division and modulo /* program to print sum,sub,mul,div of two numbers */ #include<stdio.h> #include<conio.h> void main() { int a,b,sum,mul,div,sub; clrscr(); printf(\"Enter First number \"); scanf(\"%d\",&a); printf(\"enter Second number \"); scanf(\"%d\",&b); sum=a+b; printf(\"\\n Addition of two numbers is %d\",sum); sub=a-b; printf(\"\\n substraction of two numbers is %d\",sub); mul=a*b; printf(\"\\n multiplication of two numbers is %d\",mul); div=a/b; printf(\"\\ndivision of two numbers is %d\",div); mod=a%b; CU IDOL SELF LEARNING MATERIAL (SLM)
304 Computer Programming printf(\"\\nModulus of two numbers is %d\",mod); getch(); } Output: 2. The distance between two cities (In KM) is input through keyboard. Write a program to convert and print this distance in metres, feet, inches and centimetres. #include<stdio.h> #include<conio.h> void main() { float km,m,cm,f,in; clrscr(); printf(\"Enter distance in kilometres: \"); scanf(\"%f\",&km); m=km*1000; cm=km*1000*100; f=km*3280.84; in=km*39370.08; printf(\"The distance in feet: %f\\n\"f); printf(\"The distance in inches: %f\\n\"in); printf(\"The distance in metres: %f\\n\"m); printf(\"The distance in Centifeet: %f\\n\"cm); getch(); } CU IDOL SELF LEARNING MATERIAL (SLM)
C Basics and Control Structure 305 Output: 3. Write a C program to perform post and preincrement, post and pre-decrement operations. /* Increment and Decrement Operators in C Example */ #include <stdio.h> int main() { int x = 10,y = 20; printf(\"----INCREMENT OPERATOR EXAMPLE---- \\n\"); printf(\"Value of x : %d \\n\", x); //Original Value printf(\"Value of x : %d \\n\", x++); // Using increment Operator printf(\"Value of x : %d \\n\", x); //Incremented value printf(\"----DECREMENT OPERATOR EXAMPLE---- \\n\"); printf(\"Value of y : %d \\n\", y); //Original Value printf(\"Value of y : %d \\n\", y--); // using decrement Operator printf(\"Value of y : %d \\n\", y); //decremented value return 0; } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
306 Computer Programming 4. Write a program which implements the working of all Bitwise operators #include <stdio.h> int main() { int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ; AND_opr = (m&n); OR_opr = (m|n); NOT_opr = (~m); XOR_opr = (m^n); printf(\"AND_opr value = %d\\n\",AND_opr ); printf(\"OR_opr value = %d\\n\",OR_opr ); printf(\"NOT_opr value = %d\\n\",NOT_opr ); printf(\"XOR_opr value = %d\\n\",XOR_opr ); printf(\"left_shift value = %d\\n\", m << 1); printf(\"right_shift value = %d\\n\", m >> 1); } Output: AND_opr value = 0 OR_opr value = 120 NOT_opr value = -41 XOR_opr value = 120 left_shift value = 80 right_shift value = 20 5. Write a program to select and print the largest of the three nos. using Nested-If- Else statement. 1. #include <stdio.h> 2. int main() { 3. double n1, n2, n3; 4. printf(\"Enter three numbers: \"); 5. scanf(\"%lf %lf %lf\", &n1, &n2, &n3); CU IDOL SELF LEARNING MATERIAL (SLM)
C Basics and Control Structure 307 6. 7. if (n1 >= n2) { 8. if (n1 >= n3) 9. printf(\"%.2lf is the largest number.\", n1); 10. else 11. printf(\"%.2lf is the largest number.\", n3); 12. } else { 13. if (n2 >= n3) 14. printf(\"%.2lf is the largest number.\", n2); 15. else 16. printf(\"%.2lf is the largest number.\", n3); 17. } 18. 19. return 0; 20. } Output: Enter three numbers: -4.5 3.9 5.6 5.60 is the largest number. 6. Write a program to perform arithmetic operations using switch case. 1. #include <stdio.h> 2. int main() { 3. char operator; 4. double first, second; 5. printf(\"Enter an operator (+, -, *,): \"); 6. scanf(\"%c\", &operator); 7. printf(\"Enter two operands: \"); 8. scanf(\"%lf %lf\", &first, &second); 9. CU IDOL SELF LEARNING MATERIAL (SLM)
308 Computer Programming 10. switch (operator) { 11. case '+': 12. printf(\"%.1lf + %.1lf = %.1lf\", first, second, first + second); 13. break; 14. case '-': 15. printf(\"%.1lf - %.1lf = %.1lf\", first, second, first - second); 16. break; 17. case '*': 18. printf(\"%.1lf * %.1lf = %.1lf\", first, second, first * second); 19. break; 20. case '/': 21. printf(\"%.1lf / %.1lf = %.1lf\", first, second, first / second); 22. break; 23. // operator doesn't match any case constant 24. default: 25. printf(\"Error! operator is not correct\"); 26. } 27. 28. return 0; 29. } Output: Enter an operator (+, -, *,): * Enter two operands: 1.5 4.5 1.5 * 4.5 = 6.8 7. Write a program to find sum of all integers greater than 100 and less than 200 and are divisible by 5. #include<stdio.h> #include<conio.h> void main() CU IDOL SELF LEARNING MATERIAL (SLM)
C Basics and Control Structure 309 { int i, sum=0; clrscr(); printf(\"\\n Numbers between 100 and 200 which is divisible by 5\"); for(i=101;i<200;i++) { if(i%5==0) { printf(\"\\n %d\",i); sum= sum + i; } } printf(\"\\n sum = %d\",sum); getch(); } Output: Numbers between 100 and 200 which is divisible by 5 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 CU IDOL SELF LEARNING MATERIAL (SLM)
310 Computer Programming 8. 180 185 190 195 sum = 2850 Write a C program to implement ex 1 x x2 x3 , 1! 2! 3! /* Program for Exponential Series */ #include<stdio.h> #include<conio.h> void main() { int i, n; float x, sum=1, t=1; clrscr(); printf(“Enter the value for x : “); scanf(“%f”, &x); printf(“\\nEnter the value for n : “); scanf(“%d”, &n); /* Loop to calculate the value of Exponential */ for(i=1;i<=n;i++) { t=t*x/i; sum=sum+t; } printf(“\\nThe Exponential Value of %f = %.4f”, x, sum); getch(); } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 311 PRACTICAL ARRAYS, STRINGS, UNIT 2 FUNCTIONS AND STRUCTURE PROGRAMS TO UNDERSTAND THE BASIC DATA TYPE AND I/O 1. Write a program to perform various matrix operations Addition, Subtraction, Multiplication, Transpose using switch-case statement 1. #include<stdio.h> 2. #define MAX 15 3. void main() 4. { 5. int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX],I,J,K,M,N,R,S,CH; 6. clrscr(); 7. printf(\"ENTER THE SIZE OF A MATRIX (M X N) : \\n\"); 8. printf(\"ENTER VALUE FOR M (LESS THAN 15) :\"); 9. scanf(\"%d\",&M); 10. printf(\"ENTER VALUE FOR N (LESS THAN 15) :\"); 11. scanf(\"%d\",&N); 12. printf(\"\\nENTER THE SIZE OF B MATRIX (R X S) : \\n\"); 13. printf(\"ENTER VALUE FOR R (LESS THAN 15) :\"); 14. scanf(\"%d\",&R); 15. printf(\"ENTER VALUE FOR S (LESS THAN 15) :\"); 16. scanf(\"%d\",&S); 17. printf(\"\\nSELECT UR CHOICE (1.ADD 2.SUB 3.MULT) : \"); 18. scanf(\"%d\",&CH); CU IDOL SELF LEARNING MATERIAL (SLM)
312 Computer Programming 19. switch(CH) 20. { 21. case 1 : 22. { 23. if(M==R && N==S) 24. { 25. printf(\"ENTER %d X %d MATRIX A VALUES\\n\",M,N); 26. for(I=0;I<M;I++) 27. { 28. for(J=0;J<N;J++) 29. { 30. scanf(\"%d\",&A[I][J]); 31. } 32. } 33. printf(\"ENTER %d X %d MATRIX B VALUES\\n\",R,S); 34. for(I=0;I<R;I++) 35. { 36. for(J=0;J<S;J++) 37. { 38. scanf(\"%d\",&B[I][J]); 39. } 40. } 41. for(I=0;I<M;I++) 42. { 43. for(J=0;J<N;J++) 44. { 45. C[I][J]=A[I][J]+B[I][J]; 46. } 47. } 48. printf(\"\\nRESULT %d X %d MATRIX C VALUES ARE :\\n\",M,N); 49. for(I=0;I<M;I++) CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 313 50. { 51. for(J=0;J<N;J++) 52. { 53. printf(\"%d\\t\",C[I][J]); 54. } 55. printf(\"\\n\"); 56. } 57. } 58. else 59. { 60. printf(\"\\nERROR : CONDITION FOR ADDITION\"); 61. printf(\" MATRICES IS NOT SATISFIED!\"); 62. } 63. break; 64. } 65. case 2 : 66. { 67. if(M==R && N==S) 68. { 69. printf(\"ENTER %d X %d MATRIX A VALUES\\n\",M,N); 70. for(I=0;I<M;I++) 71. { 72. for(J=0;J<N;J++) 73. { 74. scanf(\"%d\",&A[I][J]); 75. } 76. } 77. printf(\"ENTER %d X %d MATRIX B VALUES\\n\",R,S); 78. for(I=0;I<R;I++) 79. { 80. for(J=0;J<S;J++) CU IDOL SELF LEARNING MATERIAL (SLM)
314 Computer Programming 81. { 82. scanf(\"%d\",&B[I][J]); 83. } 84. } 85. for(I=0;I<M;I++) 86. { 87. for(J=0;J<N;J++) 88. { 89. C[I][J]=A[I][J]-B[I][J]; 90. } 91. } 92. printf(\"\\nRESULT %d X %d MATRIX C VALUES ARE :\\n\",M,N); 93. for(I=0;I<M;I++) 94. { 95. for(J=0;J<N;J++) 96. { 97. printf(\"%d\\t\",C[I][J]); 98. } 99. printf(\"\\n\"); 100. } 101. } 102. else 103. { 104. printf(\"\\nERROR : CONDITION FOR SUBTRACTION\"); 105. printf(\" MATRICES IS NOT SATISFIED!\"); 106. } 107. break; 108. } 109. case 3 : 110. { 111. if(N==R) CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 315 112. { 113. printf(\"ENTER %d X %d MATRIX A VALUES\\n\",M,N); 114. for(I=0;I<M;I++) 115. { 116. for(J=0;J<N;J++) 117. { 118. scanf(\"%d\",&A[I][J]); 119. } 120. } 121. printf(\"ENTER %d X %d MATRIX B VALUES\\n\",R,S); 122. for(I=0;I<R;I++) 123. { 124. for(J=0;J<S;J++) 125. { 126. scanf(\"%d\",&B[I][J]); 127. } 128. } 129. for(I=0;I<M;I++) 130. { 131. for(J=0;J<S;J++) 132. { 133. C[I][J]=0; 134. for(K=0;K<R;K++) 135. { 136. C[I][J]=C[I][J]+A[I][K]*B[K][J]; 137. } 138. } 139. } 140. printf(\"\\nRESULT %d X %d MATRIX C VALUES ARE :\\n\",M,S); 141. for(I=0;I<M;I++) 142. { CU IDOL SELF LEARNING MATERIAL (SLM)
316 Computer Programming 143. for(J=0;J<S;J++) 144. { 145. printf(\"%d\\t\",C[I][J]); 146. } 147. printf(\"\\n\"); 148. } 149. } 150. else 151. { 152. printf(\"\\nERROR : CONDITION FOR MULTIPLICATION\"); 153. printf(\" MATRICES IS NOT SATISFIED!\"); 154. } 155. break; 156. } 157. default: 158. { 159. printf(\"YOU ENTERED WRONG CHOICE !!!\"); 160. } 161. } 162. getch(); 163. } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 317 2. Programs based on String Handling (a) Program to accept name of the user through gets() and print string through puts() function. #include<stdio.h> int main() { char name[30]; printf(\"Enter name: \"); gets(name); //Function to read string from user. printf(\"Name: \"); puts(name); //Function to display string. return 0; } (b) Write a program in c to Calculate Length of String without Using strlen() Function #include <stdio.h> int main() { char s[] = \"Programming is fun\"; int i; for (i = 0; s[i] != '\\0'; ++i); printf(\"Length of the string: %d\", i); return 0; } Output: Length of the string: 18 (c) Write a program in c to Copy String Without Using strcpy() #include <stdio.h> int main() { char s1[100], s2[100], i; printf(\"Enter string s1: \"); fgets(s1, sizeof(s1), stdin); CU IDOL SELF LEARNING MATERIAL (SLM)
318 Computer Programming for (i = 0; s1[i] != '\\0'; ++i) { s2[i] = s1[i]; } s2[i] = '\\0'; printf(\"String s2: %s\", s2); return 0; } Output: Enter string s1: Hey fellow programmer. String s2: Hey fellow programmer. (d) Write a program in c to Remove Characters in String Except Alphabets #include <stdio.h> int main() { char line[150]; printf(\"Enter a string: \"); gets(line); for (int i = 0; line[i] != '\\0'; ++i) { while (!((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '\\0')) { for (int j = i; line[j] != '\\0'; ++j) { line[j] = line[j + 1]; } line[j] = '\\0'; } } printf(\"Output String: \"); puts(line); return 0; } CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 319 Output: Enter a string: p2'r-o@gram84iz./ Output String: programiz 3. Write a program using function to implement Pascal Triangle #include<stdio.h> int main() { int rows, coef=1, space, i, j; printf(\"Enter number of rows: \"); scanf(\"%d\", &rows); for (i=0; i<rows; i++) { for (space=1; space <= rows-i; space++) printf(\" \"); for (j=0; j<=i; j++) { if (j==0 || i==0) coef = 1; else coef=coef*(i-j+1)/j; printf(\"%4d\", coef); } printf(\"\\n\"); } return 0; } CU IDOL SELF LEARNING MATERIAL (SLM)
320 Computer Programming 4. Write a program that used user Defined Function Swap ( ) and interchange the value of two variable. #include <stdio.h> // This function swaps values pointed by xp and yp void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } int main() { int x, y; printf(\"Enter Value of x \"); scanf(\"%d\", &x); printf(\"\\nEnter Value of y \"); scanf(\"%d\", &y); swap(&x, &y); printf(\"\\nAfter Swapping: x = %d, y = %d\", x, y); return 0; } Output: Enter Value of x 12 Enter Value of y 14 After Swapping: x = 14, y = 12 5. Write a function prime that return 1 if it ‘s argument is prime and return 0 otherwise #include #include int prime(int); int main() CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 321 { int n,p; clrscr(); printf(“Enter a number : “); scanf(“%d”,&n); p=prime(n); if(p==1) printf(“%d is prime\\n”,n); else printf(“%d is not prime\\n”,n); getch(); return 0; } int prime(int n) { int i; for(i=2;i<n;i++) { if(n%i==0) return 0; } return 1; } Output: Enter a number : 18 18 is not prime Enter a number : 5 5 is prime CU IDOL SELF LEARNING MATERIAL (SLM)
322 Computer Programming 6. Define a structure type, personal, that would contain person name, date of joining and salary. Using this structure, write a program to read this information for one person from the key board and print the same on the screen. #include <stdio.h> struct personal { char person_name[100]; char join_date[100]; float salary; }; struct personal p; int main() { printf(\"Enter Name of the person :- \"); scanf(\"%s\",p.person_name); printf(\"Enter Joining Date of the person :- \"); scanf(\"%s\",p.join_date); printf(\"Enter Salary of the person :- \"); scanf(\"%f\",&p.salary); printf(\"\\nName of the person :- %s\\n\",p.person_name); printf(\"Joining Date of the person :- %s\\n\",p.join_date); printf(\"Salary of the person :- %0.2f\\n\",p.salary); } Output: Enter Name of the person :- Kiran Enter Joining Date of the person :- 6th Dec,2000 Enter Salary of the person :- 25000 Name of the person :- Kiran Joining Date of the person :- 6th Dec,2000 Salary of the person :- 25000 CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays, Strings, Functions and Structure 323 7. Define a structure called cricket that will describe the following information:player name,team name,batting average.Using cricket,declare an array player with 5 elements and write a program to read the information about all the 5 players and print a teamwise list containing names of player with their batting average. #include<stdio.h> #include<conio.h> #include<string.h> struct cricket { char nm[20],team[20]; int avg; }; #define total 5 int main() { struct cricket player[total],temp; int i,j; clrscr(); for(i=0;i<total;i++) { printf(“For player %d\\n”,i+1); printf(“Enter the name of player : “); fflush(stdin); gets(player[i].nm); printf(“Enter the team : “); fflush(stdin); gets(player[i].team); printf(“Enter the batting average : “); fflush(stdin); scanf(“%d”,&player[i].avg); } printf(“\\nTeam Name Average\\n”); CU IDOL SELF LEARNING MATERIAL (SLM)
324 Computer Programming printf(” \\n”); for(i=0;i<total;i++) { printf(“%-10s %-10s %7d\\n”,player[i].team,player[i].nm,player[i].avg); } getch(); return 0; } Output: For player 1 Enter the name of player : Radhe Enter the team : India Enter the batting average : 100 For player 2 Enter the name of player : Tiwari Enter the team : Pakistan Enter the batting average : 5 For player 3 Enter the name of player : Tendulkar Enter the team : India Enter the batting average : 45 For player 4 Enter the name of player : Dhoni Enter the team : India Enter the batting average : 48 For player 5 Enter the name of player : Yuvi Enter the team : India Enter the batting average : 39 Team Name Average India Radhe 100 Pakistan Tiwari 5 India Tendulkar 45 India Dhoni 48 India Yuvi 39 CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers and DMA 325 PRACTICAL POINTERS AND DMA UNIT 3 PROGRAMS ON POINTERS 1. Write a program using pointer and function to determine the length of string. #include <stdio.h> #include <string.h> int main() { char a[100]; int length; printf(\"Enter a string to calculate its length\\n\"); gets(a); length = strlen(a); printf(\"Length of the string = %d\\n\", length); return 0; } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
326 Computer Programming 2. Write a program using pointer to compare two strings #include <stdio.h> //Macro for maximum number of characters in a string #define MAX 100 int main() { //declare string variables char str1[MAX]={0}; char str2[MAX]={0}; int loop; //loop counter int flag=1; //declare & initialize pointer variables char *pStr1=str1; char *pStr2=str2; //read strings printf(\"Enter string 1: \"); scanf(\"%[^\\n]s\",pStr1); printf(\"Enter string 2: \"); getchar(); //read & ignore extra character scanf(\"%[^\\n]s\",pStr2); //print strings printf(\"string1: %s\\nstring2: %s\\n\",pStr1,pStr2); //comparing strings for(loop=0; (*(pStr1+loop))!='\\0'; loop++) { if(*(pStr1+loop) != *(pStr2+loop)) { flag=0; CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers and DMA 327 break; } } if(flag) printf(\"Strings are same.\\n\"); else printf(\"Strings are not same.\\n\"); return 0; } Output: 3. Write a program using pointer to concatenate two strings. #include <stdio.h> #include <string.h> int main() { char a[1000], b[1000]; printf(\"Enter the first string\\n\"); gets(a); printf(\"Enter the second string\\n\"); gets(b); strcat(a, b); printf(\"String obtained on concatenation: %s\\n\", a); return 0; } CU IDOL SELF LEARNING MATERIAL (SLM)
328 Computer Programming Output: 4. Write a program using pointer to copy one string to another string #include <stdio.h> #include <string.h> int main() { char source[1000], destination[1000]; printf(\"Input a string\\n\"); gets(source); strcpy(destination, source); printf(\"Source string: %s\\n\", source); printf(\"Destination string: %s\\n\", destination); return 0; } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers and DMA 329 5. Write a program using pointer to read an array if integer and print element in reverse order. #include <stdio.h> int main() { int n, c, d, a[100], b[100]; printf(\"Enter the number of elements in array\\n\"); scanf(\"%d\", &n); printf(\"Enter array elements\\n\"); for (c = 0; c < n ; c++) scanf(\"%d\", &a[c]); // Copying elements into array b starting from the end of array a for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c]; // Copying reversed array into the original, we are modifying the original array. for (c = 0; c < n; c++) a[c] = b[c]; printf(\"The array after reversal:\\n\"); for (c = 0; c < n; c++) printf(\"%d\\n\", a[c]); return 0; } Output: CU IDOL SELF LEARNING MATERIAL (SLM)
330 Computer Programming 6. Write a program that uses a table of integers whose size will be specified interactively at run time. #include <stdio.h> #include <stdlib.h> void main() { int *p, *table; int size; printf(\"\\nWhat is the size of table?\"); scanf(\"%d\",&size); printf(\"\\n\"); if((table = (int*)malloc(size *sizeof(int))) == 0) { printf(\"No space available \\n\"); exit(1); } printf(\"\\n Address of the first byte is %u \\n\", table); /* Reading table values*/ printf(\"\\nInput table values\\n\"); for (p=table; p<table + size; p++) scanf(\"%d\",p); /* Printing table values <span id=\"IL_AD3\" class=\"IL_AD\">in reverse</span> order*/ for (p = table + size -1; p >= table; p --) printf(\"%d is stored at address %u \\n\",*p,p); getch(); } CU IDOL SELF LEARNING MATERIAL (SLM)
Pointers and DMA 331 Output: What is the size of the table? 5 Address of the first byte is 2262 Input table values 11 12 13 14 15 15 is stored at address 2270 14 is stored at address 2268 13 is stored at address 2266 12 is stored at address 2264 11 is stored at address 2262 7. C program to input and print text using Dynamic Memory Allocation /*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; } CU IDOL SELF LEARNING MATERIAL (SLM)
332 Computer Programming Output: Enter limit of the text: 100 Enter text: I am mike from California, I am computer geek. Inputted text is: I am mike from California, I am computer geek. CU IDOL SELF LEARNING MATERIAL (SLM)
C Pre-Processor and File Management 333 PRACTICAL C PRE-PROCESSOR AND UNIT 4 FILE MANAGEMENT PROGRAMS ON BASIC FILE HANDLING OPERATIONS 1. Write a program which reads diameter and height of a cone and calculate its volume using macros. * * C Program to Find the volume and surface area of cone */ #include <stdio.h> #include <math.h> int main() { float radius, height; float surface_area, volume; printf(\"Enter value of radius and height of a cone :\\n \"); scanf(\"%f%f\", &radius, &height); surface_area = (22 / 7) * radius * (radius + sqrt(radius * radius + height * height)); volume = (1.0/3) * (22 / 7) * radius * radius * height; printf(\"Surface area of cone is: %.3f\", surface_area); printf(\"\\n Volume of cone is : %.3f\", volume); return 0; } CU IDOL SELF LEARNING MATERIAL (SLM)
334 Computer Programming 2. Write a C program to read file kiran.txt and all data character wise. #include<stdio.h> void main() { FILE *fp; char ch; clrscr(); fp=fopen(\"kiran.txt\",\"r\"); if(fp==NULL) { printf(\"file does not exists\"); } else { while(ch!=EOF) { ch=getc(fp); putch(ch); } } fclose(fp); getch(); } 3. Write a program in C program to illustate fgetc() function #include <stdio.h> int main () { // open the file FILE *fp = fopen(\"test.txt\",\"r\"); // Return if could not open file CU IDOL SELF LEARNING MATERIAL (SLM)
C Pre-Processor and File Management 335 if (fp == NULL) return 0; do { // Taking input single character at a time char c = fgetc(fp); // Checking for end of file if (feof(fp)) break ; printf(\"%c\", c); } while(1); 4. fclose(fp); return(0); } Write a C program to illustate fputc() function #include<stdio.h> int main() { int i = 0; FILE *fp = fopen(\"output.txt\",\"w\"); // Return if could not open file if (fp == NULL) return 0; char string[] = \"good bye\", received_string[20]; for (i = 0; string[i]!='\\0'; i++) // Input string into the file // single character at a time fputc(string[i], fp); fclose(fp); fp = fopen(\"output.txt\",\"r\"); CU IDOL SELF LEARNING MATERIAL (SLM)
336 Computer Programming // Reading the string from file fgets(received_string,20,fp); printf(\"%s\", received_string); fclose(fp); return 0; } Output: good bye CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344