Home
Blog
Training
Course Schedule
Courses Offered
Corporate Training
Video Courses
Resources
Projects
Programs
Video Tutorials
My Favourites
Exam
Books
Books Read
Books Written
Testimonials
Feedback
FAQs
About
Answers to Exercises in Udemy Course - C Language for Beginners
These are the answers for exercises given in my Udemy course titled - C Language For Beginners.
Lesson 1 - Getting Started With Programming using C Language
Lesson 2 - Language Elements
Lesson 4 - Control Statements
Lesson 6 - Loops
Lesson 8 - Arrays
Lesson 10 - Chars and Strings
Lesson 12 - User-defined Functions
Lesson 15 - Pointers
Lesson 16 - Structures
Lesson 17 -Text File Handling
Lesson 18 - Binary File Handling
Lesson 19 - Miscellaneous Topics - Part 1
Lesson 20 - Miscellaneous Topics - Part 2
Additional Resources
Here are some additional videos that will help you to learn more.
How to use CodeBlocks IDE for C Programming
Understanding Pointers in C
Pass By Reference in C
Pointers vs. Arrays in C
Using Storage Classes in C Language
My book
C Language For Beginners
is available at Amazon in Kindle Edition.
For my offline and online courses, please visit
srikanthtechnologies.com
Lesson 1 - Getting Started With Programmming using C Language
Accept centimeters and display equivalent inches and millimeters
// Program to display inches and millimeters by accepting centimeters #include
void main() { float cm,inches,mm; printf("Enter number of centimeters :"); scanf("%f",&cm); inches = cm / 2.5; mm = cm * 10; // %.2f is to display only two decimal places printf("For %.2f Centimeter, Inches are %.2f and Millimeters are %.2f \n",cm,inches,mm); }
Accept price and quantity and display amount
// Program to take quantity and price and display amount #include
void main() { float price,qty,amount; printf("Enter price :"); scanf("%f",&price); printf("Enter quantity :"); scanf("%f",&qty); amount=price * qty; printf("Amount = %f \n",amount); }
Accept a number and display cube of the given number
// Cube for given number #include
void main() { int num,cube; printf("Enter a number :"); scanf("%d",&num); cube=num * num * num; printf("Cube for %d is %d \n",num, cube); }
Lesson 2 - Language Elements
Accept basic salary and calculate net salary by adding 40% HRA, 20% DA, and subtracting 5% PF
// Program to calculate net salary #include
void main() { float salary,hra,da,pf,netsalary; printf("Enter salary :"); scanf("%f",&salary); hra = salary * 0.4; da = salary * 0.2; pf = salary * 0.05; netsalary=salary + hra + da - pf; // Display net salary without any decimal portion printf("Net salary = %.0f\n",netsalary); }
Accept two numbers and interchange them with and without using third variable.
// Program to interchange values of two variables without using 3rd variable #include
void main() { int a,b, temp; printf("Enter two numbers :"); scanf("%d%d",&a,&b); // By using third variable temp = a; a = b; b = temp; printf("value of a = %d and value of b = %d \n",a,b); // Without using thrid variable a = a + b; b = a - b; a = a - b; printf("value of a = %d and value of b = %d \n",a,b); }
Lesson 4 - Control Statements
Accept month number and year and display exact number of days in the given month.
// Program to display number of days in the given month and year #include
main() { int month,year, nodays; printf("Enter Month [1-12] :"); scanf("%d",&month); printf("Enter 4 digit year :"); scanf("%d",&year); switch(month) { case 2 : if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) nodays = 29; else nodays = 28; break; case 4: case 6: case 9: case 11: nodays = 30; break; default: nodays = 31; } printf("We have %d days in month %d of year %d\n", nodays,month,year); }
Accept quantity and price from user and display net amount to be paid. Apply 20 % discount if quantity is more than 5 or 10% if quantity is more than 2. Apply additional 10% discount if total amount crosses 1000.
// Program to calculate net amount #include
main() { float qty, price, amount; printf("Enter Price :"); scanf("%f",&price); printf("Enter Quantity :"); scanf("%f",&qty); amount = qty * price; if (qty > 5) amount = amount * 0.80; // 20% discount else if (qty > 2) amount = amount * 0.90; // 10% discount // calculate additional discount if ( amount > 1000) amount *= 0.90; printf("Net Amount :%.2f\n",amount); // display amount with decimal places }
Accept marks from user and display grade based on the following table :
Marks
Grade
>80
A
>70
B
>60
C
<=60
D
// Program to print grade based on marks #include
main() { int marks; printf("Enter Marks :"); scanf("%d",&marks); if (marks > 80) printf("A"); else if (marks > 70) printf("B"); else if (marks > 60) printf("C"); else printf("D"); }
Accept three numbers and display the biggest of three numbers.
// Program to find out biggest of three numbers #include
main() { int a,b,c,big; printf("Enter three numbers :"); scanf("%d%d%d",&a,&b,&c); // enter three numbers with space separating them if(a>b) { if(a>c) big = a; else big = c; } else { if(b>c) big = b; else big = c; } printf("Biggest number is %d\n", big); }
Accept marks in two subjects and display grade as follows:
Fail if marks in any subject are less than 50
Grade A if marks in each subject are more than 80
Grade B if marks in any one subject are more than 80
Grade C if total marks are more than 150
Otherwise Grade D
// Program to calculate grades based on given marks #include
void main() { int marks1, marks2; printf("Enter marks for two subjects :"); scanf("%d%d",&marks1, &marks2); if ( marks1 < 50 || marks2 < 50) printf("Failed\n"); else if( marks1 > 80 && marks2 > 80 ) printf("Grade A \n"); else if ( marks1 > 80 || marks2 > 80) printf("Grade B \n"); else if ( marks1 + marks2 > 150) printf("Grade C \n"); else printf("Grade D \n"); }
Lesson 6 - Looping Structures
Accept 10 numbers and display the biggest number
// Program to display biggest of 10 numbers #include
void main() { int i=1,num,big; big=0; for(i=1; i <= 10; i ++) { printf("Enter a number :"); scanf("%d",&num); if(num > big) big = num; } printf("\nBiggest = %d \n",big); }
Accept a number and display whether it is a prime number
// Program to display prime number or not #include
main() { int n,i,prime = 1; printf("Enter a number :"); scanf("%d",&n); for(i=2; i <= n/2; i++) { if(n % i == 0) { prime = 0; // false break; } } if(prime) // if prime is non-zero printf("%d is prime number\n",n); else printf("%d is not a prime number!\n",n); }
Accept base and power and display the result
// Program to accept base and power and display the result (base raised to power) #include
void main( ) { int base,power, result=1 , i; printf("Enter Base :"); scanf("%d",&base); printf("Enter Power :"); scanf("%d",&power); for(i=1;i<=power;i++) { result *= base; } printf("%d raised to %d = %d\n", base,power,result); }
Display table for number 9 from 10 to 20
Sample Output : 9 * 10 = 90 9 * 11 = 99 … 9 * 20 = 180
// Program to display table for 9 from 10 to 20 #include
void main() { int r,i; for(i=10; i<=20 ;i++) { printf("%2d * %2d = %4d\n", 9, i, 9 * i); } }
Display first 10 numbers in Fibonacci series
// First 10 numbers in fibonacci series #include
void main() { int prev=0,current=1,next, i; printf("%d\n%d\n", prev,current); for(i=3; i <= 10; i ++) { next = prev + current; prev = current; current = next; printf("%d\n",next); } }
Accept two numbers and display GCD (Greatest Common Divisor)
// Program to display GCD of 2 numbers #include
void main() { int a,b,small,i; printf("Enter Two Numbers : "); scanf("%d %d",&a,&b); small = a < b ? a : b; // start with smallest of two numbers for(i=small; i>=1; i --) { if( a % i == 0 && b % i == 0) break; } printf("GCD of %d and %d is %d\n", a, b, i); }
Print sum of digits for numbers between 1000 and 9999
// Sum of digits for numbers between 1000 and 9999 */ #include
void main() { int n,i,r,sum; for(i=1000; i <= 9999; i++) { n=i; sum=0; while(n!=0) { r= n % 10; sum += r; n = n / 10; } printf("%d %d\n",i,sum); } }
Lesson 8 - Arrays
Take an array of 10 elements, fill it with random numbers and then reverse array without using any second array.
// Program to fill array with random numbers and reveres array without using another array #include
void main() { int a[10]; int n,i,j,temp; srand(time(0)); printf("\nOriginal Array\n"); for(i=0;i<10;i++) { a[i]=rand()%100; printf("%d\t", a[i]); } // reverse array for(i=9,j=0;j < i ;i--,j++) { temp=a[j]; a[j]=a[i]; a[i]=temp; } printf("\nArray after reversing it\n"); for(i=0;i<10;i++) printf("%d\t",a[i]); }
Delete the element at the given position from an array of 10 elements and fill the last element with 0.
// Program to delete the element at the given position from an array of 10 elements and fill the last element with 0 #include
void main() { int a[10],i,pos; srand(time(0)); // Initialize seed // Fill array with random numbers for(i=0;i<10;i++) { a[i] = rand() % 100; printf("%d\t", a[i]); } printf("\nEnter position of element to delete :"); scanf("%d",&pos); for(i=pos;i < 9; i++) { a[i]=a[i+1]; } a[9]=0; // Set last element to 0 printf("\nArray after deletion\n"); for(i=0;i<10;i++) printf("%2d\t",a[i]); }
Read numbers from keyboard and copy them into an array of 5 elements. Make sure only positive numbers are copied into array and negative numbers are ignored.
// Program to read numbers from keyboard and place only positive numbers into array #include
main() { int i=0,count=0,n; int a[5]; while(i<5) { printf("Enter a number : "); scanf("%d",&n); if(n > 0) { a[i]=n; i++; } } for(i=0;i<5;i++) printf("%d\n",a[i]); }
Print all even numbers of an array of 10 elements first and then odd numbers.
//Program to print even numbers first then odd numbers of an Array #include
void main() { int i,j=0,n; int a[10]; srand(time(0)); // Fill array with random numbers for(i=0;i < 10;i++) a[i] = rand() % 100; // Print even numbers printf("\nEven Numbers\n"); for(i=0;i<10;i++) { if( a[i] % 2 == 0) printf("%d\n",a[i]); } // Print odd numbers printf("\nOdd Numbers\n"); for(i=0;i<10;i++) { if( a[i] % 2 != 0) printf("%d\n",a[i]); } }
Lesson 10 - Chars and Strings
Accept a string and count number of words
// Program to count number of words in string #include
#include
main() { int count=0,i,inword; char st[50]; printf("Enter a string :"); gets(st); inword = 0; for(i=0; st[i] != '\0'; i++) { if(st[i] == 32) inword = 0; // not in word else if(!inword) // if not in word then increment count { inword = 1; count++; } } printf("Word count = %d\n",count); }
Accept 10 characters without echoing and print their inverse case
// Program to accept 10 characters without echoing and print their inverse case #include
#include
main() { int i; char ch; printf("Enter 10 characters\n"); for(i=0;i<10;i++) { ch = getch(); if (isupper(ch)) putch(tolower(ch)); else putch(toupper(ch)); } }
Accept password (without echoing characters) and check whether it has a digit, alphabet and special character – or @
// Program to accept password (without echoing characters) and check whether it has a digit, alphabet and special character – or @ #include
#include
main() { int i,alpha=0,digit=0,special=0; char pwd; printf("Enter password [enter to stop] :"); do { pwd = getch(); // take one char without echo if(isalpha(pwd)) alpha++; else if(isdigit(pwd)) digit++; else if(pwd =='-' || pwd == '@') special++; } while(pwd!=10); // until new line is entered if(alpha > 0 && digit > 0 && special > 0 ) printf("\nPassword is valid!\n"); else printf("\nPassword is invalid!\n"); }
Accept 10 strings and print the largest string
// Accept 10 strings and print the largest string #include
#include
main() { int i; char st[20], largest[20]; // initialize largest to empty string largest[0]= '\0'; for(i=0;i<10;i++) { printf("Enter a string : "); gets(st); if(strcmp(st,largest) > 0 ) strcpy(largest,st); } printf("Largest String = %s\n",largest); }
Print each word in a string in reverse order
// Program to print each word in a string in reverse order #include
#include
void main() { int i,j; char st[100],word[20]; printf("Enter a string :"); gets(st); for(i=0, j=0; ;i++) { if(st[i] == 32 || st[i] == '\0') // print { if ( j > 0) // if word has any char { for(--j; j >=0; j --) { putch(word[j]); } printf("\n"); j = 0; } if(st[i] == '\0') // stop if end of string reached break; } else word[j++] = st[i]; } }
Accept two strings and check whether they have same set of characters
// Program to check whether two strings have same set of chars #include
main() { char st1[50], st2[50]; int i,j, found; printf("Enter first string : "); gets(st1); printf("Enter second string : "); gets(st2); // Check whether every char in first string is present in second string for(i=0; st1[i] ; i ++) { found = 0; for(j = 0; st2[j]; j ++) { if (st1[i] == st2[j]) { found = 1; break; } } if (!found) { printf("Strings do not have same set of chars"); exit(0); // terminate program } } // Check whether every char in second string is present in first string for(i = 0; st2[i] ; i ++) { found = 0; for(j = 0; st1[j]; j ++) { if (st2[i] == st1[j]) { found = 1; break; } } if (!found) { printf("Strings do not have same set of chars"); exit(0); // terminate program } } printf("\nBoth strings have same set of chars\n"); }
Lesson 12- User-defined Functions
Create a function that takes a number and returns 1 if number is prime, otherwise 0.
// Create a function to check whether a number is prime #include
int prime(int num); main () { int n,a; printf("Enter a number :"); scanf("%d",&n); if(prime(n)) printf("%d is prime\n",n); else printf("%d is not prime\n",n); } int prime(int n) { int i; for(i=2;i<=n/2;i++) { if(n%i==0) return 0; // Number is not prime } return 1; // No factor found, so prime number }
Create a function that takes an array of 10 integers and returns sum of the array.
// Program to take an array of 10 numbers and to return sum of array #include
main() { int a[]={12,23,44,55,33,343,13,34,335,22}; // initialize array printf("Sum = %d\n", sum_array(a) ); } int sum_array(int a[10]) { int i,sum=0,n; for(i=0;i<10;i++) sum+=a[i]; return sum; }
Create a function that takes a string and a character and returns number of times the character is found in the string
// Create a function that returns how many times given char is present in the given string #include
int count_char(char s[20],char c); main() { int count; count = count_char("How are you",'o'); printf("Count = %d\n",count); } int count_char(char s[20],char c) { int count=0,i; for(i=0; s[i] != '\0'; i++) { if(s[i]== c) count++; } return count; }
Create a function that takes an array of 10 integers and returns highest number in the array
// Program to take an array of 10 numbers and to return highest number in array #include
main() { int a[] = {33,11,32,32,12,43,83,31,12,34}; int biggest; biggest=highest_number(a); printf("Highest number in the array is %d", biggest); } int highest_number(int a[10]) { int i,biggest; biggest=a[0]; for(i=0;i<10;i++) { if(a[i]>biggest) biggest=a[i]; } return biggest; }
Create a function that takes two integers and returns GCD of the numbers
// Program to find GCD of 2 numbers using a function #include
void main() { int a,b,g; printf("Enter two numbers : "); scanf("%d%d",&a,&b); g=gcd(a,b); printf("GCD of %d and %d is %d\n",a,b,g); } int gcd(int a,int b) { int i, big; big = a < b ? a : b; for(i=big; i >=1 ; i--) { if(a % i ==0 && b % i == 0) return i; } }
Create a function that takes an array of 10 integers and position of the element to be deleted, and delete the element from array. Fill last element of the array with 0.
// Program to delete the element at the given position from an array of 10 elements and fill the last element with 0 #include
void main() { int a[10],i,pos; srand(time(0)); // Initialize seed // Fill array with random numbers for(i=0;i<10;i++) { a[i] = rand() % 100; printf("%d\t", a[i]); } printf("\nEnter position of element to delete :"); scanf("%d",&pos); delete_item(a,pos); printf("\nArray after deletion\n"); for(i=0;i<10;i++) printf("%2d\t",a[i]); } void delete_item(int a[],int pos) { int i; for(i=pos; i < 9; i++) { a[i]=a[i+1]; } a[9]=0; // Set last element to 0 }
Lesson 15 - Pointers
Create a function to take two numbers (int) and set both of them to the highest of two.
// Create a function to set both the parameters to biggest of the two void set_big(int * p1, int * p2) { if (*p1 > *p2) *p2 = * p1; else *p1 = * p2; } main() { int a=30, b=20; set_big(&a,&b); printf("%d %d", a, b); }
Create a function that takes an array of integers and sets all elements to zeros. Make function flexible so that it can work with an array of any size.
// Program to create a function that fills the given array with zeros #include
#include
main() { int a[10],b[20]; zero_fill(a,10); zero_fill(b,20); // print arrays printf("\nFirst Array\n"); print(a,10); printf("\nSecond Array\n"); print(b,20); } void print(int a[], int size) { int i; for(i=0; i < size; i ++) printf("%5d", a[i]); } void zero_fill(int a[], int size) { int i; for(i=0; i < size ;i++) { a[i] = 0; } }
Create a function that returns the number of uppercase and lowercase letters in the given string. Hint: Use pass by reference to return two values from a function.
/* Program to create a function that returns the number of uppercase and lowercase letters in the given string*/ #include
#include
main() { int upper,lower; char st[30]; printf("\nEnter a string : "); gets(st); count_upper_lower(st,&upper,&lower); printf("\nNumber of upper case letters : %d",upper); printf("\nNumber of lower case letters : %d",lower); } int count_upper_lower(char * st,int * upper, int * lower) { int i; *upper = *lower = 0; for(i=0; st[i]!='\0';i++) { if(isupper(st[i])) (*upper)++; else if(islower(st[i])) (*lower)++; } }
Write a program to find out how many times a substring is found in main string. Accept main string and sub string from keyboard.
/* Program to count how many times substring is present in main string */ #include
#include
main() { int count=0; char st[100], sub[20], *p; printf("\nEnter main string : "); gets(st); printf("\nEnter substring : "); gets(sub); p = st; // make p point to main string while(1) { p = strstr(p,sub); if(p == NULL) break; count ++; p++; // start next search after where previous occurrence was found } printf("\nSubstring [%s] was found [%d] time(s) in [%s]\n",sub,count,st); }
Create a function to take two arrays of same size and copy second array to first array in reverse order.
// Program to create a function to take two arrays of same size and copy second array to first array in reverse order #include
void arrayreverse(int *source, int * target); main() { int i; int a[10],b[10]; // fill first array with random numbers srand(time(0)); // init random seed printf("\nElements in first array\n"); for(i=0;i<10;i++) { a[i] = rand() % 100; printf("%5d",a[i]); } reverse_array(a,b); printf("\nElements in second array\n"); for(i=0;i<10;i++) printf("%5d",b[i]); } void reverse_array(int *source ,int * target) { int i,j; for(i=0,j=9;i<10;i++,j--) { target[j]= source[i]; } }
Lesson 16 - Structures
Create a structure to represent a product with id, name, price and quantity on hand. Read details from user and print all details along with net price, which includes a tax of 18%
// Program to create a structure to represent a product with id, name, price and quantity on hand. // Read details from user and print all details along with net price, which includes a tax of 18% #include
struct product { int id; char name[30]; int quantity; float price; }; void main() { struct product p; float netprice; printf("Enter product id :"); scanf("%d",&p.id); fflush(stdin); // we need to clear keyboard buffer to get rid of \n entered in previous scanf() printf("Enter product name :"); gets(p.name); printf(("Enter product quantity :")); scanf("%d",&p.quantity); printf("Enter product price :"); scanf("%f",&p.price); netprice= p.price*1.18; printf("Id : %d\n",p.id); printf("Name : %s\n",p.name); printf("Quantity : %d\n",p.quantity); printf("Price : %.2f\n",p.price); printf("NetPrice : %.2f\n",netprice); }
Create a function that takes two parameters of type struct product and return true if they match exactly, otherwise false.
// Create a function that takes two parameters of type struct product and return true (1)if they match exactly, // otherwise false(0) #include
struct product { int id; char name[30]; int qty; float price; }; int compare(struct product s,struct product p); main() { struct product p1 = {1,"iPhone X",10,80000}; struct product p2 = {1,"iPhone X",10,80000}; if ( compare(p1,p2)) // returns 1 (true) when two variables have same data printf("Equal\n"); else printf("Not Equal\n"); } int compare(struct product p1,struct product p2) { if(p1.id == p2.id && strcmp(p1.name,p2.name) ==0 && p1.qty == p2.qty && p1.price == p2.price) return 1; else return 0; }
Create a structure that stores time – hours, minutes, and seconds. Create an array of 5 elements of type struct time, read values from keyboard into array and then display them in HH:MM:SS format.
/*Program to Create a structure that stores time – hours, minutes, and seconds and an array of 5 elements of type struct time, read values from keyboard into array and then display them in HH:MM:SS format.*/ #include
struct time { int hours; int minutes; int seconds; }; void main() { struct time a[5]; int i,j; for(i=0;i<5;i++) { printf("Enter time [hh:mm:ss] : "); scanf("%d:%d:%d",&a[i].hours, &a[i].minutes, &a[i].seconds); } for(i=0;i<5;i++) { printf("%02d:%02d:%02d\n",a[i].hours,a[i].minutes,a[i].seconds); } }
Create a function that takes a parameter of type struct time and return time after adding 1 second.
// Program to create a function that takes a parameter of type struct time and return another struct time after adding 1 second #include
struct time { int hours; int minutes; int seconds; }; struct time add_second(struct time t); void main() { struct time t1 = {10,20,30}, t2; t2 = add_second(t1); printf("%02d:%02d:%02d",t2.hours,t2.minutes,t2.seconds); } struct time add_second(struct time t) { t.seconds ++; if (t.seconds > 59) { t.seconds = 0; t.minutes++; if ( t.minutes > 59) { t.minutes = 0; t.hours ++; if(t.hours > 23) t.hours = 0; } } return t; }
Lesson 17 - Text File Handling
Accept a filename and display all non-blank lines of the file.
// Display all non-blank lines from the given file #include
main() { char line[100], filename[50]; FILE * fp; printf("Enter filename : "); gets(filename); fp = fopen(filename, "rt"); if (fp == NULL) { printf("\nError : Could not open %s file. Quitting.", filename); exit(1); // Exit program with error code } while(1) { if (fgets(line,100,fp) == NULL) // if EOF break; // Length of line must be greater than 1 to be non-blank. // Line always contains new line (\n), so length is always a minimum of 1 if (strlen(line) > 1) printf("%s",line); } fclose(fp); }
Accept a filename and convert its contents to uppercase.
// Convert contents of file to uppercase #include
main() { char line[100], filename[50]; FILE * fp, * tfp; printf("Enter filename : "); gets(filename); fp = fopen(filename, "rt"); if (fp == NULL) { printf("\nError : Could not open %s file. Quitting.", filename); exit(1); // Exit program with error code } tfp = fopen("tempfile.txt", "wt"); if (tfp == NULL) { printf("\nError : Could not create target file - tempfile.txt. Quitting."); exit(1); // Exit program with error code } while(1) { if (fgets(line,100,fp) == NULL) // if EOF break; fputs(strupr(line),tfp); // Convert to upper and write to target } fclose(fp); fclose(tfp); // Delete source file remove(filename); rename("tempfile.txt",filename); }
Accept a filename and display number of chars, words and lines in the file.
// Program to count no. of chars, words and lines in the given file #include
main() { FILE * fp; char filename[50]; int ch,chars,words,lines, inword; printf("Enter filename : "); gets(filename); fp = fopen(filename, "rt"); if (fp == NULL) { printf("\nError : Could not open %s file. Quitting.", filename); exit(1); // Exit program with error code } chars = words = lines = 0; inword = 0; while(1) { ch = fgetc(fp); if (ch == -1) break; chars ++; if(ch == '\n') { lines ++; inword = 0; // not in word as we are at the beginning of next line } else if (!isspace(ch)) // not a space { if(!inword) // not in words, so first char in new word, increment word count { inword = 1; words++; } } else // space inword = 0; } fclose(fp); printf("\nChars = %d, Words = %d, Lines = %d", chars, words, lines); }
Assume a file marks.txt, which contains marks of students one per line. Display marks that are >= average marks.
// Program to take a file which contains marks of students one per line and display marks that are >= average marks #include
main() { FILE * fp; char line[5]; int total, count, avg, marks; fp = fopen("marks.txt", "rt"); if (fp == NULL) { printf("\nError : Could not open MARKS.TXT. Quitting."); exit(1); // Exit program with error code } count = 0; while(1) { if (fgets(line,5,fp) == NULL) break; total += atoi(line); count ++; } avg = total / count; fclose(fp); // Reopen file. A better way is to use fseek() fp = fopen("marks.txt", "rt"); printf("\nMarks that are greater than average marks - %d\n",avg); while(1) { if (fgets(line,5,fp) == NULL) break; marks = atoi(line); if ( marks > avg) printf("%d\n",marks); } }
Accept a filename and encrypt (add a number to ASCII code of each character) file and write encrypted content into another file with same primary filename, but .enc extension.
// Program to encrypt file and write into another file with .enc extension #include
void main() { FILE * fp, * tfp; char filename[50], targetfilename [50]; int ch; printf("Enter filename : "); gets(filename); fp = fopen(filename, "rt"); if (fp == NULL) { printf("\nError : Could not open file %s. Quitting.", filename); exit(1); // Exit program with error code } // create target file strcpy(targetfilename,filename); strcat(targetfilename,".enc"); tfp = fopen(targetfilename, "wb"); // open in binary mode, more in next lesson if (tfp == NULL) { printf("\nError : Could not create file %s. Quitting.", targetfilename); exit(1); // Exit program with error code } while(1) { ch = fgetc(fp); if(ch == EOF) break; fputc(ch + 1, tfp); // add 1 to ASCII code of char to make it illegible } fclose(fp); fclose(tfp); }
Lesson 18 - Binary File Handling
Create a file called marks.dat and write marks of students based on admission number. Marks of admno 1 will be written in first 4 bytes of file and then marks of admno 2 and so on. Accept marks from user in the order of admission number. Stop taking input when user enters -1.
// Program to write marks into marks.dat #include
#define FILENAME "marks.dat" void main() { FILE * fp; int marks; fp = fopen(FILENAME,"wb"); if ( fp == NULL) { printf("Sorry! File could not be opened!\n"); return; } while(1) { printf("Enter marks [-1 to stop] : "); scanf("%d",&marks); if (marks == -1) break; fwrite(&marks,sizeof(int),1,fp); } fclose(fp); }
Open marks.dat and display marks of student based on the given admission number. Hint: Use fseek() to position file pointer at the required position, based on admission number, before reading marks.
// Program to display marks for the given admno #include
#define FILENAME "allmarks.dat" void main() { FILE * fp; int marks, admno, count; fp = fopen(FILENAME,"rb"); if ( fp == NULL) { printf("Sorry! File could not be opened!\n"); return; } while(1) { printf("Enter admno [0 to stop] : "); scanf("%d",&admno); if (admno == 0) break; //Go to required position based on admno fseek(fp,(admno - 1) * sizeof(int), SEEK_SET); count = fread(&marks,sizeof(int),1,fp); if (count == 1) printf("\nMarks = %d\n",marks); else printf("\nSorry! Couldn't read marks!\n"); } fclose(fp); }
Accept two binary files and merge them into target file. Accept names of source files and target file from user.
// Merge two files and copy into another #include
FILE * open(char *, char *); // Prototype for function void main() { char sfn1[50], sfn2[50], tfn[50]; FILE * sfp1, * sfp2, * tfp; char buffer[100]; int count; printf("Enter first source filename : "); gets(sfn1); sfp1 = open(sfn1,"rb"); printf("Enter second source filename : "); gets(sfn2); sfp2 = open(sfn2,"rb"); printf("Enter target filename : "); gets(tfn); tfp = open(tfn,"wb"); // copy first source file to target while(1) { count = fread(buffer,1,100,sfp1); // read a block of 100 bytes if (count == 0) // stop if we reached end of file break; // write buffer to target file fwrite(buffer,1,count,tfp); // write whatever bytes read from source to target } fclose(sfp1); // copy second source file to target while(1) { count = fread(buffer,1,100,sfp2); if (count == 0) break; // write buffer to target file fwrite(buffer,1,count,tfp); } fclose(sfp2); fclose(tfp); } FILE * open(char * filename, char * mode) { FILE * fp; fp = fopen(filename, mode); if (fp == NULL) { printf("\nError : Could not open %s file. Quitting.", filename); exit(1); // Exit program with error code } return fp; }
Lesson 19 - Miscellaneous Topics - Part 1
Create a macro that takes an int and returns true if it is even number
// Create a macro that takes an int and returns true if it is even number #define iseven(n) n % 2 == 0 void main() { int n = 11; printf("%s", iseven(n) ? "Even" : "Odd"); }
Create a macro that takes a year and returns true if it is a leap year
// Create a macro to test leap year #define leapyear(y) y % 4 == 0 && y % 4 != 100 || y % 400 == 0 void main() { int year; // print leap years from 2000 to 2020 for( year = 2000; year <= 2020; year ++) { if (leapyear(year)) printf("%d\n", year); } }
Create enumeration that represents days of a week and use it in a switch statement to calculate wage. Wage depends on day of the week as follows: Mon – 1000, Tue – 1000, Wed – 1000, Thu – 1200, Fri – 1200, Sat – 1500, Sun – 1500
// Wage calculation based on day of week enum week { MON, TUE, WED, THU, FRI,SAT,SUN }; void main() { enum week dayofweek; int wage; printf("Enter day of week [0-6] : "); scanf("%d",&dayofweek); switch(dayofweek) { case MON: case TUE: case WED: wage = 1000; break; case THU: case FRI: wage = 1200; break; case SAT: default : wage = 1500; } printf("Wage = %d\n",wage); }
Lesson 20 - Miscellaneous Topics - Part 2
Accept a filename on command line and display how many alphabets, digits and special characters the file has.
// Count Alphabets, digits and other chars in a file #include
main(int argc, char * argv[]) { FILE * fp; int ch, alphas, digits, others; if(argc == 1) // No parameters passed { printf("\nMissing filename!\n"); printf("\nUsage : count
\n"); return; } fp = fopen(argv[1],"r"); if ( fp == NULL) { printf("Sorry! File not found. Quitting."); return; } alphas = digits = others = 0; while(1) { ch = fgetc(fp); if (ch == EOF) break; if(isalpha(ch)) alphas++; else if (isdigit(ch)) digits ++; else others++; } fclose(fp); printf("No. of Alphabets : %d\n",alphas); printf("No. of Digits : %d\n",digits); printf("No. of Other chars: %d\n",others); }
Create a recursive function that takes number and prints digits in reverse order
// Program to print digits of a number in reverse order using recursion #include
void print_reverse(int num) { if (num == 0) return; printf("%d", num % 10); // print rightmost digit print_reverse(num/10); // remove rightmost digit and make recursive call } void main() { print_reverse(1234); }
Display sum of all numbers given as command line arguments
// Program to display sum of numbers given on command line #include
void main(int argc, char * argv[]) { int sum = 0,i; for(i=1; i < argc; i ++) { sum += atoi( argv[i]); } printf("Sum = %d",sum); }
Accept number of students in a class and then take marks for all students. Display all marks in sorted order.
// Take marks and print them in sorted order using dynamic memory allocation #include
#include
#include
void main() { int * marks, count, i,j, temp; printf("Enter no. of students :"); scanf("%d",&count); srand(time(0)); // Allocate a block to accommodate marks marks = (int *) malloc(sizeof(int) * count); if (marks == NULL) { printf("Sorry! Memory allocation error. Quitting."); return; } // Take input from user for(i=0; i < count ; i ++) { // printf("Enter marks for student with roll no %d :", i + 1); // scanf("%d", marks + i); marks[i] = rand() % 100; } // Sort marks for(i=0; i < count -1 ; i ++) { for(j=i+1; j < count; j ++) { if ( marks[i] > marks[j]) { temp = marks[i]; marks[i] = marks[j]; marks[j] = temp; } } } // Print sorted marks for(i=0; i < count ; i ++) { printf("%5d\n",marks[i]); } }