2017 Edition
2014 Edition
|
C Language For Beginners By Srikanth Pragada is a book
meant for absolute beginners of programming. It teaches how to write programs
using C Language.
How to compile and run C programs?
Watch the following video to understand how to use CodeBlocks IDE.
This video explains how to download, install and use CodeBlocks IDE to compile and run C programs.
How to use CodeBlocks IDE for C Programming
How To Buy This Book?
Hard copy (printed version) of this book is available for sale at Srikanth Technologies.
The price of this book is 250 INR.
Kindle Edition (digital version) of this book in available in
Amazon.
Answers For Exercises
1. Introduction To C
- Compiler or interpreter
- They use more operators, which make program very compact.
- Functions. Because C is function oriented language.
2. First C Program
- /* */
- \t
- main
- A
- Display your name and address in two different lines.
// Program to print name and address in two different lines
#include <stdio.h>
void main()
{
printf("Srikanth Pragada");
printf("\n304, Srikanth Technologies, Eswar Paradise, Dwarkanagar, Vizag-16");
}
- Display your name on the first line and address on the second line. Separate each part of the address using tab.
#include <stdio.h>
void main()
{
printf("Srikanth Pragada");
printf("\n304\tSrikanth Technologies\tEswar Paradise\tDwarkanagar\tVizag-16");
}
3. Language Elements
- %u
- 8 bytes (may vary based on compiler)
- _ (underscore)
- Character
-
- Valid
- Valid
- Invalid - main is a keyword
- Valid
- Invalid – identifier must not start with a digit
- Valid
- Accept two integers and display octal equivalent of first and hex equivalent of second.
#include <stdio.h>
void main()
{
int n1,n2;
// Accept two numbers
printf("Enter two numbers :");
scanf("%d%d",&n1,&n2);
printf("Octal of %d = %o Hex of %d = %x",n1,n1,n2,n2);
}
- Accept amount and discount percentage and display net amount.
#include <stdio.h>
void main()
{
float amt, disper,net;
// accept amount and discount percentage
printf("Enter amount and discount percentage : ");
scanf("%f%f", &amt,&disper);
net = amt - ( amt * disper / 100 );
printf("Net amount : %f ", net);
}
- Take two numbers and display them in the reverse order of accepted order.
#include <stdio.h>
void main()
{
int n1,n2;
// accept two numbers
printf("Enter two numbers ");
scanf("%d%d", &n1, &n2);
// print numbers in the reverse order
printf("Numbers in reverse order : %d %d ", n2, n1);
}
4. Operators
-
&&
-
10 and store the result back in A
-
a = b is assigning value of b to a, a == b is comparing the value of a with b for equality
-
pre-fix notation
-
An operator that takes only one operand, such as ++ and --.
- Take two integers and display sum, difference, product, quotient, and remainder.
#include <stdio.h>
void main()
{
int n1,n2;
// accept two numbers
printf("Enter two numbers :");
scanf("%d%d", &n1, &n2);
// print sum, difference, product and quotient and remainder
printf("\nSum = %d ", n1 + n2);
printf("\nDifference = %d ", n1 - n2);
printf("\nProduct = %d ", n1 * n2);
printf("\nQuotient = %d ", n1 / n2);
printf("\nRemainder = %d ", n1 % n2);
}
- Take a number and display its square.
#include <stdio.h>
void main()
{
int n;
// accept a number
printf("Enter a number ");
scanf("%d",&n);
printf("\nSquare of %d = %d ", n , n * n );
}
- Take principal amount, rate of interest, number of years and display simple interest.
#include <stdio.h>
void main()
{
float pamt, rate, interest;
int ny;
printf("Enter principal amount : ");
scanf("%f",&pamt);
printf("Enter interest rate : ");
scanf("%f",&rate);
printf("Enter number of years : ");
scanf("%d",&ny);
interest = pamt * rate * ny / 100;
printf("Total Simple Interest = %f", interest );
}
- Take values for 'a' and 'b' and then display the result for a2 + b2
#include <stdio.h>
void main()
{
int a,b;
printf("Enter value for a and b : ");
scanf("%d%d",&a,&b);
printf(" Result of = %d " , a * a + b * b);
}
5. Control Structures
- Accept a number and display whether it is an even number or odd number. Write two programs - one with normal if statement and another with conditional expression.
#include <stdio.h>
void main()
{
int n;
printf("Enter a number : ");
scanf("%d",&n);
if ( n % 2 == 0 )
printf("%d is even number",n);
else
printf("%d is odd number",n);
}
/* using conditional expression */
#include <stdio.h>
void main()
{
int n;
printf("Enter a number : ");
scanf("%d",&n);
printf("%d is %s ", n, n % 2 == 0 ? "Even" : "Odd");
}
- Accept marks in subject and subject code (1 to 4) and display whether student passed or failed.
Pass mark is based on subject code as follows. 1 - 40, 2 - 50 , 3 - 45 , 4 - 55.
#include <stdio.h>
void main()
{
int marks,pm,subject;
printf("Enter subject code [1-4]: ");
scanf("%d",&subject);
printf("Enter marks : ");
scanf("%d",&marks);
switch(subject)
{
case 1: pm = 40; break;
case 2: pm = 50; break;
case 3: pm = 45; break;
case 4: pm = 55; break;
}
if (marks >= pm)
printf(" Passed");
else
printf(" Failed");
}
- Accept two numbers and display the relationship between these two numbers. The output should display one of the messages: "Both numbers are equal", "First number is bigger" or "Second number is bigger".
#include <stdio.h>
void main()
{
int n1,n2;
printf("Enter two numbers : ");
scanf("%d%d",&n1,&n2);
if (n1 == n2)
printf("Both the numbers are equal");
else
if (n1 > n2)
printf("First number is bigger");
else
printf("Second number is bigger");
}
- Accept three numbers from user and display the biggest of three numbers.
#include <stdio.h>
void main()
{
int n1,n2,n3,big;
printf("Enter three numbers : ");
scanf("%d%d%d",&n1,&n2,&n3);
big = n1 > n2 ? n1 : n2;
big = n3 > big ? n3: big;
printf(" The biggest of %d %d %d is %d ", n1,n2,n3,big);
}
6. Looping Structures
- do..while
- break
- initialization, condition and updation
- Display numbers from 100 to 1.
#include <stdio.h>
void main()
{
int i;
for (i = 100 ; i > 0 ; i--)
printf("%d\n", i);
}
- Accept a number and display sum of numbers from 1 to that number.
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1 ; i <= n ; i ++)
sum += i;
printf("Sum of 1 to %d = %d ", n,sum);
}
- Display all even numbers in the range 100 to 200.
#include <stdio.h>
void main()
{
int i;
for (i = 100 ; i <= 200 ; i += 2)
printf("%d\n",i);
}
- Take numbers from user until user enters 0 and display sum and average of accepted numbers.
#include <stdio.h>
void main()
{
int i=0,n;
float sum=0;
while (1) /* always true loop */
{
printf("Enter a number [0 to stop] : ");
scanf("%d", &n);
if (n == 0)
break; /* terminate loop */
sum += n;
i++;
}
printf("Sum = %f Average = %f ",sum, sum / i);
}
- Take 10 numbers and display the biggest and smallest of the given numbers.
#include <stdio.h>
void main()
{
int i,n,big,small;
big = -32768; /* set big to smallest possible number */
small = 32767; /* set small to biggest possible number */
for (i=1; i <= 10 ; i++)
{
printf("Enter a number : ");
scanf("%d", &n);
if(n > big )
big = n;
if ( n < small )
small = n;
}
printf(" The smallest = %d and biggest = %d ", small, big);
}
- Display table for 7 up to 20.
Sample output:
7 * 1 = 7
7 * 2 = 14
...
7 * 20 = 140
#include <stdio.h>
void main()
{
int i;
for ( i = 1; i <= 20 ; i++)
printf("7 * %2d = %4d\n", i, 7 * i);
}
- Display numbers in the following format.
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
#include <stdio.h>
void main()
{
int i,j;
for(i=1; i <= 5 ; i++)
{
printf("\n");
for (j = 1 ; j <= 5 ; j ++)
printf("%5d", j);
}
}
7. Character Handling
- 50
- iscntrl()
- Standard input device
- Echo
- The character will be read from the file on the disk.
- printf(). For example: printf("%d", 'A');
- Accept 10 characters and display number of uppercase letter, lowercase letters and digits.
#include <ctype.h>
#include <stdio.h>
void main()
{
char ch;
int i,nu,nd,nl;
nu = nd = nl = 0;
for (i = 1 ; i <= 10 ; i ++)
{
ch = getchar();
if (isupper(ch))
nu ++;
else
if (islower(ch))
nl ++;
else
if (isdigit(ch))
nd ++;
}
printf("Upper = %d, Lower = %d, Digits = %d",nu,nl,nd);
}
- Accept a character and convert that character to uppercase if it is in lowercase or convert it to lowercase if it is in uppercase.
#include <ctype.h>
#include <stdio.h>
void main()
{
char ch;
printf("Enter a character : ");
ch = getchar();
if (isupper(ch))
putchar( tolower(ch));
else
if (islower(ch))
putchar(toupper(ch));
}
- Accept characters till the user inputs '*' and convert characters to lowercase.
#include <ctype.h>
#include <stdio.h>
void main()
{
char ch;
printf("Enter characters : ");
while (1)
{
ch = getch();
if (ch == '*')
break;
putch(tolower(ch));
}
}
8. Arrays
- Accept 20 numbers into array and display the sum and average along with numbers.
#include <stdio.h>
void main()
{
int ar[20];
int i, sum = 0;
for(i = 0 ; i < 20 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
sum += ar[i];
}
printf("Entered Numbers \n");
for (i = 0 ; i < 20 ; i++)
{
printf("%d\n", ar[i]);
}
printf("Sum = %d Average = %d ", sum, sum / 20);
}
- Take an array of 10 integers and accept values into it. Sort the array in descending order.
#include <stdio.h>
void main()
{
int ar[10];
int i, j, temp;
for (i = 0 ; i < 10 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
}
/* sort array in descending order */
for ( i = 0 ; i < 9 ; i++)
{
for ( j = i+1; j < 10 ; j ++)
{
if ( ar[i] < ar[j])
{
/* interchange */
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
}
} /* end of j loop */
} /* end of i loop */
/* display sorted array */
printf("Entered Numbers \n");
for (i = 0 ; i < 10 ; i++)
{
printf("%d\n", ar[i]);
}
}
- Accept 20 numbers into an array and display how many numbers are below the average of the array.
#include <stdio.h>
void main()
{
int ar[20];
int i,avg,sum=0,count = 0;
for (i = 0 ; i < 20 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
sum += ar[i];
}
avg = sum / 10;
/* Count values that are below average of the array */
for (i = 0 ; i < 20 ; i++)
{
if (ar[i] < avg )
count ++;
}
printf("\nNo. of values below average : %d",count);
}
- Create an array of 10 elements and fill 9 elements of the array. Accept a number and position and insert the number at the given position in the array.
#include <stdio.h>
void main()
{
int ar[10];
int i,num, pos;
for (i = 0 ; i < 9 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
}
/* take number and position */
printf("Enter position and number : " );
scanf("%d%d", &pos, &num);
/* push all numbers from position to right */
for (i = 9 ; i > pos ; i-- )
ar[i] = ar [i - 1];
/* insert new value at position */
ar[pos] = num;
/* Display array after insertion */
for(i = 0 ; i < 10 ; i++)
{
printf("%d \n", ar[i]);
}
}
- Create an array of 10 elements and fill it. Interchange first 5 elements with last 5 elements.
#include <stdio.h>
void main()
{
int ar[10];
int i,temp;
for(i = 0 ; i < 10 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
}
/* interchange first 5 elements with last 5 elements */
for(i = 0 ; i < 5 ; i++)
{
temp = ar [i];
ar[i] = ar [9-i];
ar[9-i] = temp;
}
/* Display array after interchange */
for (i = 0 ; i < 10 ; i++)
{
printf("%d \n", ar[i]);
}
}
9. Multidimensional Array
- Take an array of 5 * 5 ( 5 rows and 5 columns ) and accept values into it. Display the array in the form of a matrix.
#include <stdio.h>
void main()
{
int ar[5][5];
int i,j;
for (i = 0 ; i < 5 ; i++)
{
for( j = 0 ; j < 5 ; j ++)
{
printf("Enter number for [%d][%d] element : ",i,j);
scanf("%d", &ar[i][j]);
}
}
/* display array as a matrix */
for (i = 0 ; i < 5 ; i++)
{
/* move to next line before each row */
printf("\n");
for( j = 0 ; j < 5 ; j ++)
{
printf("%5d",ar[i][j]);
}
}
}
- Take an array of 4 * 4. Place 1 in diagonal cells and 0 in remaining and display the array in matrix format.
#include <stdio.h>
void main()
{
int ar[4][4];
int i,j;
for (i = 0 ; i < 4 ; i++)
{
for( j = 0 ; j < 4 ; j ++)
{
if ( i == j )
ar[i][j] = 1;
else
ar[i][j] = 0;
}
}
/* display array as a matrix */
for (i = 0 ; i < 4 ; i++)
{
/* move to next line before each row */
printf("\n");
for( j = 0 ; j < 4 ; j ++)
{
printf("%5d",ar[i][j]);
}
}
}
- Accept numbers into an array of 5 * 5. Accept a number. Display all the elements of the array that are greater than the accepted number.
#include <stdio.h>
void main()
{
int ar[5][5];
int i,j,num;
for (i = 0 ; i < 5 ; i++)
{
for( j = 0 ; j < 5 ; j ++)
{
printf("Enter number for [%d][%d] element : ",i,j);
scanf("%d", &ar[i][j]);
}
}
printf("Enter a number : ");
scanf("%d", &num);
/* display all elements that are greater than the given number */
for (i = 0 ; i < 5 ; i++)
{
for( j = 0 ; j < 5 ; j ++)
{
if ( ar[i][j] > num )
printf("%d \n",ar[i][j]);
}
}
}
- Store random numbers into an array of 6 * 6 and interchange first 3 rows with last three rows.
#include <stdlib.h>
void main()
{
int ar[6][6];
int i,j,temp;
srand(time(0)); // Initialize seed
for (i = 0 ; i < 6 ; i++)
{
/* move to next line before each row */
printf("\n");
for(j = 0 ; j < 6 ; j ++)
{
ar[i][j] = rand() % 100;
printf("%5d",ar[i][j]);
}
}
/* interchange */
for (i = 0 ; i < 3 ; i++)
{
for(j = 0 ; j < 6 ; j ++)
{
temp = ar[i][j];
ar[i][j] = ar[5-i][j];
ar[5-i][j] = temp;
}
}
printf("\n\n");
for (i = 0 ; i < 6 ; i++)
{
/* move to next line before each row */
printf("\n");
for( j = 0 ; j < 6 ; j ++)
{
printf("%5d",ar[i][j]);
}
} /* end of i loop */
} /* end of main */
10. String Handling
- stricmp()
- 2 bytes one for A and other one for null character.
- Because scanf() takes whitespace character as end of input for a field.
- Return value will be greater than 0 as first string is bigger than second string.
- printf("%s",name) will display the value of name and puts(name) will display name followed by new line.
- Accept a string and display each character in the string in opposite case.
#include <stdio.h>
void main()
{
char st[20];
int i;
/* accept a string */
printf("Enter a string : ");
gets(st);
/* display it in opposite case */
for ( i = 0 ; st[i] != '\0'; i++)
if (islower(st[i]))
putch(toupper(st[i]));
else
putch(tolower(st[i]));
}
- Accept a string and display only uppercase letters in the string.
#include <stdio.h>
void main()
{
char st[20];
int i;
/* accept a string */
printf("Enter a string : ");
gets(st);
for ( i = 0 ; st[i] != '\0'; i++)
if (isupper(st[i]))
putch(st[i]);
}
- Accept a string and a character. Display how many times that character occurs in string.
#include <stdio.h>
void main()
{
char st[20];
int i, count = 0;
char ch;
/* accept a string */
printf("Enter a string : ");
gets(st);
/* accept character */
printf("Enter a character : ");
ch = getchar();
/* count */
for ( i = 0 ; st[i] != '\0'; i++)
if ( st[i] == ch)
count ++;
printf("Count : %d", count);
}
- Take a sentence and display the number of words in it. You can assume that words are separated by only one space. Try to do this without this assumption also.
#include <stdio.h>
void main()
{
char st[100];
int i,count =0;
/* accept a string */
printf("Enter a string : ");
gets(st);
/* count words */
for ( i = 0 ; st[i] != '\0'; i++)
if (st[i] == ' ' )
count ++;
printf(" No. of words : %d", count + 1);
}
Count no. of words without assuming there is only one space between words.
#include <stdio.h>
void main()
{
char st[100];
int ch, i, inword = 0, wordcount = 0;
printf("Enter string :");
gets(st);
for(i=0; st[i] != '\0'; i++)
{
if(st[i] != 32) // Non-space
{
if(!inword) // if it is first char in word then count it a word
{
wordcount++;
inword = 1;
}
}
else
{
inword = 0;
}
}
printf("No. of words = %d",wordcount);
}
- Take a string, source character and target character. Replace every occurrence of source character with target character.
#include <stdio.h>
void main()
{
char st[20];
int i;
char sch,tch;
/* accept a string */
printf("Enter a string : ");
gets(st);
/* accept source and target characters */
printf("\nEnter source character : ");
sch = getche();
printf("\nEnter target character : ");
tch = getche();
/* replace source with target */
for (i = 0 ; st[i] != '\0'; i++)
if (st[i] == sch)
st[i] = tch;
printf("\nString after conversion : %s", st);
}
- Accept 10 strings and display the biggest of 10 strings.
#include <stdio.h>
void main()
{
char st[10][20];
int i, hpos=0;
/* take strings */
for (i = 0 ; i < 10 ; i ++)
{
printf("Enter a string :");
gets( st[i]);
if(strcmp(st[i],st[hpos]) > 0 )
hpos = i;
}
printf("%s is the biggest string", st[hpos]);
}
11. User-defined Functions
- only one
- return
- int
- Function declaration is optional
- Function declaration should be given first and then function definition.
- Recursion
- User-defined function can have any name whereas main is predefined name. Function main() is the first
function to be automatically called whereas user-defined function is to be explicitly called.
- Write a function that takes a number as parameter and returns the next odd number.
int nextodd(int num)
{
if (num % 2 == 0)
return num + 1;
else
return num + 2;
}
- Write a function to take a string as parameter and display only non-blank characters of the given string.
void nonblank(char st[100])
{
int i;
for (i = 0 ; st[i] != '\0'; i ++)
if (st[i] != 32)
putch(st[i]);
}
- Write a function to take a number and return 1 if it is a prime number, otherwise 0.
int isprime(int num)
{
int i;
for (i = 2; i <= num/2 ; i ++)
if (num % i == 0 ) /* not a prime number */
return 0;
/* if control comes here, it means prime number */
return 1;
}
- Write a function to take a string and return the number of digits the string contains.
int nodigits(char st[100])
{
int count = 0, i;
for (i = 0 ; st[i] != '\0'; i ++)
if (isdigit (st[i]) )
count ++;
return count;
}
- Write a function to take a number and return factorial of the given number. Use recursion.
#include <stdio.h>
void main()
{
printf("Fact : %d ", fact(4));
}
int fact(int n)
{
if ( n > 1 )
return (n * fact( n-1));
else
return 1;
}
12. Storage Classes
- static
- scope
- extern
- static
- By declaring another variable in a block with the same name as the one to be hidden.
fun()
{
int i;
if ( )
{
int i; /* outer i is hidden here */
}
}
- Yes
13. Pointers
- &
- *
- Generally 4 bytes. But it depends on system.
- A pointer
- Declare two int variables, take values into them and display the values and addresses of those variables.
#include <stdio.h>
void main()
{
int n1,n2;
printf("Enter two values : ");
scanf("%d%d", &n1,&n2);
printf("Values %d %d ", n1,n2);
printf("\nAddresses %p %p", &n1,&n2);
}
- Write a function that takes 2 numbers and sets both of them to the smallest of two. Use pass by reference.
void settosmall(int * n1, int * n2)
{
if (*n1 < *n2)
*n2 = *n1;
else
*n1 = *n2;
}
- Write a function to take three numbers and return minimum and maximum values. Use pass by reference.
#include <stdio.h>
void smallbig(int n1,int n2, int n3,int * big, int * small)
{
/* get biggest */
*big = n2 > n1 ? n2 : n1;
*big = n3 > *big ? n3 : *big;
/* get samllest */
*samll = n2 < n1 ? n2 : n1;
*samll = n3 < *samll ? n3 : *small;
}
void main()
{
int n1, n2, n3, small, big;
smallbig(n1,n2,n3, &big, &small);
}
- Write a function to take an array and return smallest and largest values of the array. Use pass by reference.
void smallbig(int * ar,int * big, int * small)
{
int i;
*big = *small = ar[0];
for( i = 1 ; i < 10 ; i ++)
{
if ( ar[i] > *big )
*big = ar[i];
if ( ar[i] < *small)
*small = ar[i];
}
}
- Write a function to take an array of 10 integers and set all of them to 0. Use pass by reference
void settozeroes(int * ar)
{
int i;
for(i = 0; i < 10 ; i ++)
{
ar[i] = 0;
}
}
14. Pointer vs. Array
- Write a function that takes an array and number of elements as parameters and sorts the array in the ascending order.
#include <stdio.h>
void sortarray( int * ar, int nel)
{
int i,j,temp;
/* sort array in descending order */
for (i = 0 ; i < nel - 1 ; i++)
{
for (j = i+1; j < nel ; j ++)
{
if ( ar[j] > ar[i])
{
/* interchange */
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
}
} /* end of j loop */
} /* end of i loop */
}
void main()
{
int ar[10];
int i, j, temp;
for (i = 0 ; i < 10 ; i++)
{
printf("Enter number for [%d] element : ",i);
scanf("%d", &ar[i]);
}
sortarray(ar,10);
/* display sorted array */
for ( i = 0 ; i < 10 ; i++)
{
printf("%d\n", ar[i]);
}
}
- Take month number from user and display the name of the month. Use an array of strings, which contains the names of all months.
#include <stdio.h>
void main()
{
int mn;
char * months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
printf("Enter month number :");
scanf("%d",&mn);
printf(" Month name : %s", months[ mn - 1]);
}
- Write a function that takes an array of 10 integers and a search number, and returns the address in the array where search number is found. If number is not found then it should return NULL.
#include <stdio.h>
int * search(int a[10], int sn)
{
int i;
for (i = 0 ; i < 10 ; i++)
{
if(a[i] == sn)
return &a[i];
}
return NULL;
}
void main()
{
int ar[10],*p;
// fill array
p = search(ar,10); // look for 10
if(p == NULL)
printf("Not Found");
else
printf("Found at %d", p - ar); // Pointer Arithmetic
}
15. Structures
- Take details of 10 students ( student number, name, total marks) and display details in ascending order of total marks.
#include <stdio.h>
struct student
{
int no;
char name[30];
int tm;
};
void main()
{
struct student s[10], temp;
int i,j;
for ( i = 0 ; i < 10 ; i ++)
{
printf("Enter student number : ");
scanf("%d", & s[i].no);
fflush(stdin);
printf("Enter student name : ");
gets( s[i].name);
printf("Enter total marks : ");
scanf("%d",& s[i].tm);
}
/* sort the array */
for ( i = 0 ; i < 9 ; i ++)
for ( j = i + 1 ; j < 10 ; j ++)
if ( s[i].tm > s[j].tm)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
/* display sorted details */
for ( i = 0 ; i < 10 ; i ++)
{
printf("\n %5d %-20s %5d", s[i].no, s[i].name, s[i].tm);
}
} /* end of main*/
- Write a program to take 10 times ( HH:MM:SS) and display the smallest time. Allow user to enter time in HH:MM:SS format.
Hint: Use %d:%d:%d with scanf().
#include <stdio.h>
struct time
{
int h,m,s;
};
/* returns > 0 if t1 > t2
< 0 if t1 < t2
0 if t1 == t2
*/
int compare(struct time t1, struct time t2)
{
return (t1.h * 60 * 60 + t1.m * 60 + t1.s) - (t2.h * 60 * 60 + t2.m * 60 + t2.s);
}
void main()
{
struct time t[10], st;
int i;
/* accept 10 times */
for ( i = 0 ; i < 10 ; i ++)
{
printf("Enter time in hh:mm:ss format :");
scanf("%d:%d:%d", & t[i].h, &t[i].m, &t[i].s);
}
/* get the smallest time */
st = t[0];
for ( i = 1; i < 10 ; i ++)
{
if ( compare( t[i], st ) < 0 ) /* if time is less than smallest time */
st = t [i];
}
printf("Smallest Time : %d:%d:%d", st.h, st.m, st.s);
}
- Write a function to take a parameter of struct time and return the next second of the given time. Return value is also a struct time.
struct time
{
int h,m,s;
};
struct time nextsecond(struct time t)
{
t.s ++; /* increment seconds */
if ( t.s > 59 )
{
t.s = 0;
t.m ++;
if ( t.m > 59 )
{
t.m = 0;
t.h ++;
if ( t.h > 23 )
t.h = 0;
}
}
return t;
}
- (*p).x is to treat p as a pointer and then access structure pointed by p. Then it will access member x of that structure.
*p.x is to take member x of structure variable p first, as .(member operator) has higher precedence over *, and
then treat that member (x) as a pointer.
- In Structure declaration only members of the structure are declared. No space is allocated
to member.
In Structure variable declaration, we declare a variable of the structure and that variable is allocated
memory.
16. Union, typedef and enumeration
- All members in a structure are allocated memory whereas only the largest member of a union
is allocated memory.
- The value is assigned to the item instead of the default value. If nothing is specified
enum starts assigning from zero onwards.
- typedef char * STRING;
17. Pre-processor commands
- In case of angle brakets (<>) C searches for the file only in standard include directory.
In case of double quotes C searches for header file in the current directory first and if it
is not found then searches for the file in the standard include directory.
- A macro will improve performance because it will not have the overheads of calling a function.
- Create a macro called odd to take a number and return 1 if it is odd and 0 if even.
#define odd(n) n % 2 == 1
- Create a macro that takes a number as parameter and returns next even number after the parameter.
#define nexteven(n) n % 2 == 0 ? n + 2 : n + 1
18. File handling
- fgets()
- NULL pointer
- r+
- char *
- stdio.h
- Accept a filename and display only uppercase characters of the file.
#include <stdio.h>
#include <ctype.h>
void main()
{
char fn[30];
int ch;
FILE * fp;
printf("Enter filename :");
gets(fn);
fp = fopen(fn,"r");
if ( fp == NULL)
{
printf("File not found.");
exit(1);
}
while (1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
if ( isupper(ch))
putchar(ch);
}
fclose(fp);
} /* end of main */
- Accept source filename and target filename and copy the contents of source file to target file.
#include <stdio.h>
void main()
{
char sfn[30],tfn[30];
int ch;
FILE * sfp, * tfp;
printf("Enter source filename :");
gets(sfn);
printf("Enter target filename :");
gets(tfn);
sfp = fopen(sfn,"r");
if (sfp == NULL)
{
printf("Source file not found.");
exit(1);
}
tfp = fopen(tfn,"w");
if (tfp == NULL)
{
printf("Target file not found.");
exit(1);
}
while (1)
{
ch = fgetc(sfp);
if(ch == EOF)
break;
fputc(ch, tfp);
}
fclose(sfp);
fclose(tfp);
} /* end of main */
- Accept filename and display the number of lines.
#include <stdio.h>
void main()
{
char fn[30];
int ch;
FILE * fp;
int lines=0;
printf("Enter filename :");
gets(fn);
fp = fopen(fn,"r");
if ( fp == NULL)
{
printf("File not found.");
exit(1);
}
while (1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
if (ch == '\n')
lines ++;
}
fclose(fp);
printf("No. of lines : %d", lines);
} /* end of main */
- Accept lines from keyboard till END is given and write all lines into file called LINES.TXT.
#include <stdio.h>
void main()
{
char line[100];
FILE * fp;
fp = fopen("lines.txt","w");
if ( fp == NULL)
{
printf("LINES.TXT could not be created.");
exit(1);
}
while (1)
{
printf("Enter a line and END to stop :");
gets(line);
if ( strcmp(line,"END") == 0 )
break;
fputs(line,fp);
}
fclose(fp); /* close the file */
} /* end of main */
- Accept a file and display its content by displaying one space where multiple spaces are present in the file.
#include <stdio.h>
#include <ctype.h>
void main()
{
char fn[30];
int ch, inspace = 0;
FILE * fp;
printf("Enter filename :");
gets(fn);
fp = fopen(fn,"r");
if (fp == NULL)
{
printf("File not found.");
exit(1);
}
while (1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
if(ch == 32) //space
{
if(!inspace) // if it is first space then print otherwise ignore
{
inspace = 1;
putch(ch);
}
}
else
{
inspace = 0;
putch(ch);
}
}
fclose(fp);
} /* end of main */
19. Binary files and random access
- Accept details of a collection of students and write details into STUDENT.DAT.
#include <stdio.h>
struct student
{
int sno;
char name[30];
int tf, fp;
};
void main()
{
struct student s;
FILE * fp;
fp = fopen("student.dat","wb"); /* open in write and binary mode */
while(1)
{
fflush(stdin);
printf("Enter student number [0 to stop]: ");
scanf("%d", & s.sno);
if ( s.sno == 0 )
break;
fflush(stdin);
printf("Enter student name : ");
gets(s.name);
printf("Enter total fee : ");
scanf("%d", & s.tf);
printf("Enter fee paid : ");
scanf("%d", & s.fp);
/* write record to file */
fwrite(&s,sizeof(s),1,fp);
}
fclose(fp);
}
- Display the details of all students who have not paid complete amount by using the data in STUDENT.DAT.
#include <stdio.h>
struct student
{
int sno;
char name[30];
int tf, fp;
};
void main()
{
struct student s;
FILE * fp;
int count;
fp = fopen("student.dat","rb"); /* open in read and binary mode */
/* read record */
count = fread(&s,sizeof(s),1,fp);
while( count != 0 )
{
if (s.tf > s.fp )
printf("%d\t%s\t%d\t%d\n", s.sno, s.name, s.tf, s.fp);
count = fread(&s,sizeof(s),1,fp);
}
fclose(fp);
}
- Accept record number and display that record from STUDENT.DAT.
#include <stdio.h>
struct student
{
int sno;
char name[30];
int tf, fp;
};
void main()
{
struct student s;
FILE * fp;
int recno;
fp = fopen("student.dat","rb"); /* open in read and binary mode */
/* read record number */
printf("Enter record number. Record number starts with 0 : ");
scanf("%d",&recno);
/* move to the record with the given record number */
fseek(fp, sizeof(s) * recno , 0);
/* read the record */
fread(&s,sizeof(s),1,fp);
printf("%d %s %d %d", s.sno, s.name, s.tf, s.fp);
fclose(fp);
}
- Accept record number, amount paid and increment fp (fee paid) in that record by amount paid.
Hint: Open file in r+ (read and write) mode. Read record, change the data in memory, and write record back to file. But make sure you move record pointer back before you write modified record.
#include <stdio.h>
struct student
{
int sno;
char name[30];
int tf, fp;
};
void main()
{
struct student s;
FILE * fp;
int recno, amt;
fp = fopen("student.dat","r+b"); /* open in update and binary mode */
/* read record number */
printf("Enter record number. Record number starts with 0 : ");
scanf("%d",&recno);
printf("Enter Amount paid : ");
scanf("%d",&amt);
/* move to the record with the given record number */
fseek ( fp, sizeof(s) * recno , 0);
/* read the record */
fread(&s,sizeof(s),1,fp);
/* update structure in memory */
s.fp += amt;
/* move back to the previous record */
fseek (fp, sizeof(s) * -1l, 1);
/* write new record back to file */
fwrite(&s,sizeof(s),1,fp);
printf("Updation is complete");
fclose(fp);
}
20. Command line arguments
- Take source file and target file on command line and place source file contents into target file after converting contents to lowercase.
#include <stdio.h>
void main(int argc, char * argv[] )
{
int ch;
FILE * sfp, * tfp;
if (argc < 3 )
{
/* display syntax of the program. Assuming file name is LOWER.C */
printf("LOWER source target");
exit(1);
}
sfp = fopen(argv[1],"r");
if ( sfp == NULL)
{
printf("Source file not found.");
exit(2);
}
tfp = fopen(argv[2],"w");
if ( tfp == NULL)
{
printf("Target file not found.");
exit(3);
}
while (1)
{
ch = fgetc(sfp);
if(ch == EOF)
break;
fputc( tolower(ch), tfp);
}
fclose(sfp);
fclose(tfp);
}
- Take filename and a string on the command line and display all lines of the file that contain the given string along with line numbers.
#include <stdio.h>
void main()
{
FILE * fp;
char line[100], word[30] , fn[30], *cp;
int ln=1;
/* take input from user */
printf("Enter filename : ");
gets(fn);
printf("Enter string to search for : ");
gets(word);
/* open file */
fp = fopen(fn,"r");
ln = 1;
while(1)
{
cp = fgets(line,100,fp);
if (cp == NULL)
break;
if (strstr(line,word) != NULL )
printf("%4d:%s", ln, line);
ln++;
}
fclose(fp);
}
- Take a target file and source file(s) and place the contents of all source file(s) in target file.
Example: c:\cprog>concat t.txt a.txt b.txt
Places contents of a.txt and b.txt one after another into t.txt.
#include <stdio.h>
void main(int argc, char * argv[] )
{
int ch;
FILE * sfp, * tfp;
int i;
if ( argc < 3 )
{
/* display syntax of the program. Assuming file name is COPYALL.C */
printf("COPYALL target source ...");
exit(1);
}
/* open target file */
tfp = fopen(argv[1],"w");
if ( tfp == NULL)
{
printf("Target file open error.");
exit(2);
}
for (i = 2; i < argc ;i ++)
{
/* open source file */
sfp = fopen( argv[i], "r");
if ( sfp == NULL)
{
printf("Error while opening file %s ", argv[i]);
exit(3);
}
while (1)
{
ch = fgetc(sfp);
if(ch == EOF)
break;
fputc( ch, tfp);
}
/* close current source file */
fclose(sfp);
} /* end of for loop */
fclose(tfp); /* close target file */
}
21. Dynamic memory allocation
- void *
- free()
- No. of blocks, Size of block
- Because the default return type is void *, which is a pointer that points to no specific data type.
22. Linked list
- Write a program to take the content of a file into a linked list and display the content in the reverse order.
Hint: Create a list that works like a stack and not a queue.
#include <stdio.h>
/* create a structure for node */
typedef struct node
{
char line[100];
struct node * prev;
} NODE;
void main()
{
NODE * root= NULL ,*current;
char fn[10],line[100];
FILE * fp;
printf("Enter filename :");
gets(fn);
fp = fopen(fn,"r");
while (!feof(fp))
{
fgets(line,100,fp);
current = (NODE *) malloc(sizeof(NODE));
if (current == NULL)
{
printf("Memory allocation error. ");
exit(1);
}
/* copy data into node */
strcpy( current -> line, line);
current -> prev = root;
root = current;
} /* end of while */
fclose(fp);
/* display the content of the file */
current = root;
while(current != NULL)
{
printf(current-> line);
current = current -> prev;
} /* end of while */
} /* end of main */
- Write a program to create a linked list to take all lines from the given file. While
creating the list ensure the nodes in the list are in the ascending order. Then display the sorted list.
/* take the content of the file and sort it */
#include <alloc.h>
#include <stdio.h>
struct node
{
char line[100];
struct node * next;
} * root;
struct node * findpos(char *);
void main()
{
struct node * cur, * prev;
char fn[30],line[100];
FILE * fp;
printf("Enter filename : ");
gets(fn);
fp = fopen(fn,"rt");
if ( fp == NULL)
{
printf("File not found. ");
exit(1);
}
/* add a dummy node at the beginning */
cur = (struct node * ) malloc(sizeof(struct node ));
cur -> next = NULL;
cur->line[0] = '\0'; /* value is empty string */
root = cur;
while ( fgets(line,100,fp) != NULL )
{
cur = ( struct node *) malloc( sizeof(struct node));
strcpy( cur-> line, line);
prev = findpos(line);
cur-> next = prev-> next;
prev -> next = cur;
}
fclose(fp);
/* display the list */
cur = root;
while ( cur != NULL)
{
printf("%s", cur->line);
cur = cur -> next;
}
}
struct node * findpos( char * line)
{
struct node * cur, * prev;
prev = root;
cur = root -> next;
while ( cur != NULL )
{
if ( strcmp(cur-> line, line) > 0 )
break;
prev = cur;
cur = cur -> next;
}
return prev;
}
- Create a function called search that takes the root node and the name to search for.
It must return the address of the node if the name is found in the list otherwise NULL pointer.
#include <alloc.h>
/* create a structure for node */
typedef struct node
{
char line[100];
struct node * next;
} NODE;
NODE * search(NODE * root, char name[20])
{
NODE * current;
current = root;
while ( current != NULL)
{
if (strcmp( current-> line, name) == 0)
return current;
current = current -> next;
}
return NULL; /* value not found */
} /* end of function */
|