C Language Complete Guide
C Language Complete Guide
INTRODUCTION
The root of all modern languages is “ALGOL”,
introduced in the early 1960s. In 1967, “Martin
Richards” developed a language called BCPL (Basic
Combined Programming Language) primarily for
writing system software. In 1970, “Ken Thompson”
created a language using the features of BCPL and
called it simply “B”. “B” was used to create early
versions of “UNIX” operating system at Bell
Laboratories.
C’ was evolved from ALGOL, BCPL and B by
“Dennis Ritchie” at Bell Laboratories in U.S.A in
the year 1972.
C character Set:
Alphabets A,B,C…..Z
a,b,c,…….z
Digits 0,1,2,3,4,5,6,7,8,9
Special ~‘!@# %^&*
symbols ( ) _ - + = | \ { } [ ] :
; "'<>,.?/
Types of constants:
There are two types of constants
1. Primary constants.
2. Secondary constants.
Integer
constant
Numeric
constants
Real
Constants
Primary
constants
Single Chartecter
Constants
Character
constants
constants String
Constant
Arrays
Secondary Pointers
constants Structures
Unions etc
Variables:
Variable is a name given to location in the memory
where we store constants.
Ex: x=18;
X is a variable name
18 is a constant
Rules for constructing the variables:
1. The first character in the variable name must be
an alphabet or underscore.
2. We can use alphabets, digits to write the variable
name.
Operators:-
An operator is a symbol that tells the
computer to perform certain mathematical (or)
logical operations. Operators are used in
programs to manipulate data and variables. They
usually form a part of mathematical (or) logical
expressions.
‘C’ operators can be classified into a
number of categories. They are as follows:
1. Arithmetic operators.
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment & decrement operators
6. Conditional operator
7. Special operators
8. Bitwise operators
1. Arithmetic Operators:
These operators are used to
perform arithmetic calculations by evaluating
arithmetic expressions.
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
(remainder)
2. Relational Operators:
These operators are used to compare the
operands and returns 1 if comparison is true
other wise zero.
Operator purpose
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal
to
== Equal to
!= Not equal to
3. Assignment operator:
This are used to assign the values to variables.
This operator is further divided into two types:
1. Simple assignment operator
2. Shorthand assignment operator
1. Prefix operator.
2. Postfix operator
Prefix operator:-
In the prefix increment operator, first of all
value will be incremented and then incremented
value will be assigned to the variable. Similarly, in
the prefix decrement operator ,first of all will be
decrement the value and then the decremented value
will be assigned to the variable. The syntax is ++v, --
V
Postfix operator:-
In the postfix increment operator, first of all
the value will be assigned to the variable and then it
will be incremented. Similarly, the postfix decrement
operator ,first of all the value will be assigned to the
variable and then it will be decremented. The syntax
is v++, V—
6. Conditional Operator:-
Conditional operator is called ?: operator
(or) ternary operator. This operator is used for
checking the condition. The syntax is
[Type text] Page 9
IT WISDOM COMPUTER EDUCATION
exp1?exp2:exp3
where exp1 is condition expression. If exp1 is
true, exp2 will be executed, if exp1 is false, exp3 will
be executed.
7. Special Operators:-
These are used for special purpose as in 'C'
language. Some of special operators are
1. Comma Operator:- when number of statement
occur in a 'C' program having a relationship
between expressions, then we can write all the
expressions (or) statments in a single expression by
using comma operator.
Eg:- a=5;
b=10;
c=a+b;
The above three statements can be written by using
comma operator as a single statement as follows:
c = (a=5,b=10,a+b);
2. Size of operator:- It displays size covered by a
variable (or) an expression. The general syntax is n=
size of(v(or) e);
where 'n' should be of integer type, 'v' is the variable
name, 'e' is an arithmetic expression.
[Type text] Page 10
IT WISDOM COMPUTER EDUCATION
8. Bitwise operators : -
They are low level operators used to perform
logical calculation on bits i.e binary digits
Operator Meaning
~ Bitwise
complement
Ex: int x;
Float y;
2. Input/output instruction- used to take input
from user and to send output to the user.
#include<stdio.h>
#include<conio.h>
#include<math.h> etc.,
Global declaration Section: This section contains
global variables. The variables are declared before
the main ( ) function as well as user defined
functions are called global variables. These global
variables can be accessed by all the user defined
functions including main ( ) function.
Main() function: Every c program should contain
only one main() function. Program execution starts
from main() function. Main ( ) executes user defined
program statements, library functions and user
defined functions and all these statements should be
enclosed within left and right braces.
Printf(“welcome to c”);
getch();
}
printf(“remainder is %d”,c);
getch();
}
printf(“total is %d”,tot);
avg=tot/3;
printf(“average is %f”,avg);
getch();
}
/*program to calculate area of a circle*/
#include<stdio.h>
#include<conio.h>
main()
{
int r;
float pi=3.14,area;
clrscr();
printf(“enter radius”);
scanf(“%d”,&r);
area=pi*r*r;
printf(“area is %f”,area);
getch();
}
Simple if:
Syntax: if(condition)
{
Statements;
}
if the condition is true then statements are
executed otherwise not.
/*program to check given number is greater than
0*/
#include<stdio.h>
main()
{
int n;
printf(“enter a number”);
scanf(“%d”,&n);
if(n>0)
printf(“%d is greater than 0”,n);
}
If –else
Syntax:
If(condition)
{
Statement1;
}
else
{
Statement2;
}
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
return 0;
}
{
int age;
printf(“enter your age”);
scanf(“%d”,&age);
if(age>=18)
printf(“eligible to vote”);
else
printf(“not eligible to vote”);
}
/*program to check whether the given number is
divisible by both 3 and 6*/
#include<stdio.h>
main()
{
int n;
printf(“enter a number”);
scanf(“%d”,&n);
if(n%3==0&&n%6==0)
printf(“%d is divisible by both 3 and 6”,n);
else
Printf(“%d is not divisible by boh the
numbers”,n);
}
If –else-if ladder:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
else
statement;
getch();
}
scanf("%d%d%d",&m1,&m2,&m3);
tot = m1+m2+m3;
avg = (float)tot/3;
printf("\n Number : %d",sno);
printf("\n Marks : %d %d %d",m1,m2,m3);
printf("\n Total : %d",tot);
printf("\n Average : %f",avg);
printf("\n Result : ");
if(avg>75)
printf("Distinction");
else if(avg>60)
printf("I Class");
else if(avg>50)
printf("II Class");
else if(avg>35)
printf("III Class");
else
printf("Fail");
getch( );
}
main()
{
char gender, ms ;
int age ;
printf ( "Enter age, sex, marital status " ) ;
scanf ( "%d %c %c", &age, &gender, &ms
);
if ( ms == 'M' )
printf ( "Driver is insured" ) ;
else
{
if (gender == 'M' )
{
if ( age > 30 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is not
insured" ) ;
}
else
{
if ( age > 25 )
printf ( "Driver is insured" ) ;
else
printf ( "Driver is
not insured" ) ;
}
}
}
NESTED IF-ELSE:
Syntax:
if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
{
if(condition3)
statement3;
else
statement4;
}
(Or)
if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
{
statement3;
}
(Or)
if(condition1)
{
statement1;
}
else
{
if(condition2)
statement2;
else
statement3;
}
switch(condition)
{
case 1: statement;
break;
case 2:statement;
break;
case 3:statement;
break;
case n: statement;
break;
default: statement;
break;
}
Switch case rules:
break;
case 'E':
case ‘e’: printf( "it is a vowel\n" );
break;
case 'I' :
case ‘i’ : printf( "it is a vowel\n" );
break;
case 'O' :
case ‘o’ :
printf( "it is a vowel\n" );
break;
case 'U' :
case ‘u’ :
printf( "it is a vowel\n" );
break;
default : printf( "it is a consonant \n" );
break;
}
getch();
}
# include <stdio.h>
int main()
{
char op;
float n1,n2;
printf("Enter operator either + or - or * or
divide : ");
scanf("%c",&op);
printf("Enter two operands: ");
scanf("%f%f",&n1,&n2);
switch(op)
{
case '+':
printf("%.1f + %.1f = %.1f",n1, n2,
n1+n2);
break;
case '-':
printf("%.1f - %.1f = %.1f",n1, n2, n1-
n2);
break;
case '*':
printf("%.1f * %.1f = %.1f",n1, n2,
n1*n2);
break;
case '/':
printf("%.1f / %.1f = %.1f",n1, n2,
n1/n2);
break;
default:
printf("Error! operator is not
correct");
break;
}
return 0;
#include<stdio.h>
int main(){
int num,i=0,j,digit;
char * word[1000];
while(num)
{
switch(digit)
{
case 0: word[i++] = "zero";
break;
case 1: word[i++] = "one";
break;
case 2: word[i++] = "two";
break;
case 3: word[i++] = "three";
break;
case 4: word[i++] = "four";
break;
case 5: word[i++] = "five";
break;
case 6: word[i++] = "six";
break;
case 7: word[i++] = "seven";
break;
case 8: word[i++] = "eight";
break;
case 9: word[i++] = "nine";
break;
}
}
for(j=i-1;j>=0;j--)
{
printf("%s ",word[j]);
}
return 0;
output:
case 5: printf(“thursday”);
break;
case 6: printf(“friday”);
break;
case 7: printf(“saturday”);
break;
default: printf(“invalid choice”);
break;
}
getch();
}
While loop
Syntax:
while (condition)
{
Statements;
}
The statements of while loop are executed
repeatedly as long as the condition remains true.
If the condition becomes false, the
control passes to the first statement that
follows the body of the while loop.
main( )
{
int i;
clrscr( );
printf("\n Numbers from 1 to 10:\n\n");
i=1;
while(i<=10)
{
printf("%d\n",i);
i++;
}
getch( );
}
/* Accept a number and find sum of digits in it */
main( )
{
int num,rem,sum=o;
clrscr();
printf("\n Enter a number : ");
scanf("%d",&num);
while(num>0)
{
rem = num%10;
sum = sum+rem;
num= num/10;
}
printf("\n Sum of digits is %d",sum);
getch( );
}
/*program to check whether given number is
Armstrong number or not*/
#include <stdio.h>
int main()
{
int num, sum = 0, temp, rem;
printf("Enter an integer\n");
scanf("%d",&num);
temp = num;
while( temp != 0 )
{
rem = temp%10;
sum = sum + rem*rem*rem;
temp = temp/10;
}
if ( num == sum )
printf("Entered number is an armstrong
number.\n");
else
printf("Entered number is not an armstrong
number.\n");
return 0;
}
int main()
{
int n, rev = 0,rem;
while (n != 0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf("Reverse of entered number is = %d\n",
rev);
return 0;
}
int main()
{
int n, rev = 0, t;
t = n;
while( t != 0 )
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if ( n == rev )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n",
n);
return 0;
}
DO-WHILE LOOP:
Syntax :
do
{
Statements;
}
while(condition);
WHILE LOOP DO-WHILE LOOP
First condition is First statements are
checked, then statements executed, then condition
are executed. is checked.
If the condition is true Even though the
then only statements are condition is false .the
executed otherwise not. statements are executed
at least once.
#include<stdio.h>
main( )
{
int i=1;
clrscr( );
do
{
printf(“%5d “,i);
i++;
}
while(i<=5);
getch( );
}
{
fact=fact*num;
num--;
}
while (number>0);
printf("Factorial=%d",fact);
return 0;
}
FOR LOOP:
The for allows us to specify three
things about a loop in a single line:
Initializing loop counter
Testing the condition
Increment/decrementation of loop
counter
We can also have nested for loops.
Syntax:
for ( initialise counter ; test counter ;
increment counter )
{
Statements;
}
All the following statements of for loop are
similar
1. main( )
{
int i ;
for ( i = 1 ; i <= 10 ; i = i + 1 )
printf ( "%d\n", i ) ;
}
2. main( )
{
int i ;
for ( i = 1 ; i <= 10 ; )
{
printf ( "%d\n", i ) ;
i=i+1;
}
}
3. main( )
{
int i = 1 ;
for ( ; i <= 10 ; i = i + 1 )
printf ( "%d\n", i ) ;
}
4. main( )
{
int i = 1 ;
for ( ; i <= 10 ; )
{
printf ( "%d\n", i ) ;
i=i+1;
}
}
#include <stdio.h>
int main()
{
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
return 0;
}
int main()
{
int i, n, fact = 1;
return 0;
}
#include <stdio.h>
int main()
{
int n,i;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factors of %d are: ", n);
for(i=1;i<=n;++i)
{
if(n%i==0)
printf("%d ",i);
}
return 0;
}
int main()
{
int n, first = 0, second = 1, next, i;
second = next;
}
printf("%d\n",next);
}
return 0;
}
int main()
{
int n, c, k;
printf("\n");
}
return 0;
}
#include <stdio.h>
int main()
{
int n, i, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
for(i=1;i<=n;i++) /* for loop terminates if
count>n */
{
sum+=i; /* sum=sum+i */
}
printf("Sum = %d",sum);
return 0;
}
getch( );
}
break : To transfer control out of the block
forcibly.
Program 1:
/* Example on break */
main( )
{
int i;
clrscr( );
i=1;
while(i<=10)
{
if(i= =5)
break;
printf("\n i = %d",i);
i++;
}
printf("\n The loop breaked at i = %d",i);
getch( );
}
Continue:
The control transfers to condition part by skipping
all the statements after "continue"
Program 1:
/* Example on continue */
main( )
{
clrscr( );
for(i=1;i<10;i++)
{
if(i%2==0)
continue;
printf("%3d",i);
}
getch( );
}
POINTERS
Pointer is a variable which stores address of
another variable.
We must declare the pointer variable before
using it like normal variable declaration.
Syntax: data type *pointer variable name Ex:
int *x.
The data type of the pointer variable depends on
the normal variable type whose address is stored
in the pointer variable.
Float *x means not that the pointer variable
stores floating value. It means it stores the
address of float type variable.
To print the address we have to use %u format
specifier in printf() statement.
Example program:
#include<stdio.h>
void main()
{
int x=10;
int *y;
y=&x;
clrscr();
printf(“value of x = %d”,x);
printf(“value of x = %d”,*y);
printf(“value of x= %d”,*(&x));
printf(“value of y =%u”,y);
printf(“address of x =%u”,y);
printf(“address of x=%u”,&x);
getch();
}
STORAGE CLASSES
To fully define a variable we need to mention
it’s storage class along with it’s data type.
FUNCTIONS
A function is a sub program, which is used to
perform a specific task.
When a program is lengthy, it is better to divide
the program into smaller units called functions.
Functions are of two types:
C FUNCTION
S.NO SYNTAX
ASPECTS
return_type function_name (
1 function definition arguments list )
{ Body of function; }
function_name ( arguments
2 function call
list );
function return_type function_name (
3
declaration argument list );
#include<stdio.h>
#include<conio.h>
main()
{
sum();
}
sum()
{
int a,b,c;
printf(“enter two values”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum is %d”,c);
}
{
float pi=3.14;
int r,a;
a=pi*r*r;
printf(“area of circle=%f”,a);
}
scanf(“%d”,&r);
a=area(r);
printf(“area is %f”,a);
}
area(int x)
{
float pi=3.14;
float area;
area=pi*x*x;
return(area);
}
float y ;
y=x*x;
return ( y ) ;
}
int f;
for(f=1;x>0;x--)
f = f * x;
return f;
}
} /* End of
main() */
CALL BY VALUE:
In Call by Value, the value of actual parameter
is passed to formal parameter.
CALL BY REFERENCE:
In Call by Reference, the address of actual
parameter is passed to formal.
This implies that the formal and actual
parameters refers to the same memory location.
If the value of formal parameter is changed, it
affects the corresponding actual parameter.
This happens when we pass arrays, pointers as
parameters.
return ( 1 ) ;
else
if = x * rec ( x - 1 ) ;
return ( f ) ;
}
long DtoB(int);
int main()
{
long bNo;
int dNo;
bNo = DtoB(dNo);
printf("Binary value is: %ld",bNo);
return 0;
}
if(dNo != 0)
{
rem = dNo % 2;
bNo = bNo + rem * factor;
factor = factor * 10;
DtoB(dNo / 2);
}
return bNo;
}
output:
Enter any decimal number: 10
Binary value is: 1010
scanf("%d",&num);
x=findsum(num);
printf("Sum of the digits of %d is: %d",num,x);
return 0;
}
int r,s=0;
int findsum(int n)
{
if(n)
{
r=n%10;
s=s+r;
findsum(n/10);
}
else
return s;
}
ARRAYS
Array is a collection of similar type of elements.
Array elements are stored in contiguous memory
locations.
Array is represented by a variable called
subscripted variable. The variable is always
represented by its subscript which is the index
number of the element. Every element in an array
is identified by the index. The index starts from 0 .
Hence the index of first element is 0 and last
element is size - 1.
Types Of Arrays:-
There are three types of arrays. They are
Single dimensional array
Double dimensional array
Multi dimensional array
Declaration
Before using an array its type and size must be
declared. An array is declared in the following way.
Syntax:
data type variable_name[size_of_array];
Example:
int age[5];
float b[5];
char c[30];
int age[5]={2,4,34,3,4};
int age[]={2,4,34,3,4};
#include<stdio.h>
#include<conio.h>
int main()
{
int a[20],n,i,max=0; // declared the array a
with size 20
clrscr();
for(i=0;i<n;i++)
{
printf("\n Enter element [%d] : ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if(max<a[i])
max=a[i];
}
getch();
return 0;
}
/* Accept 5 elements into an array and display
values from last cell to first */
main( )
{
int a[5], i;
clrscr( );
printf("\n Enter 5 elements :\n\n ");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("\n The elements from last to first :\n\n");
for(i=4;i>=0;i--)
printf("%5d",a[i]);
getch( );
}
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter element %d : ",i+1);
scanf("%d",&a[i]);
}
for(even=odd=i=0;i<n;i++)
if(a[i]%2 == 0)
even += a[i];
else
odd += a[i];
printf("\n Even sum : %d",even);
printf("\n\n Odd sum : %d",odd);
getch( );
}
scanf("%d",&a[i]);
printf("\n Enter 5 elements of array b :\n\n ");
for(i=0;i<5;i++)
scanf("%d",&b[i]);
for(i=0;i<5;i++)
c[i] = a[i] + b[i];
printf("\n The elements of array c :\n\n");
for(i=0;i<5;i++)
printf("%5d",c[i]);
getch( );
}
/* Accept 5 numbers into an array and copy all
these elements into another array in reverse order
*/
main( )
{
int a[5],b[5],i;
clrscr( );
printf("\n Enter 5 elements :\n\n ");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
b[4-i] = a[i];
printf("\n The elements of a :\n\n");
for(i=0;i<5;i++)
printf("%5d",a[i]);
printf("\n\n The elements of b :\n\n");
for(i=0;i<5;i++)
printf("%5d",b[i]);
getch( );
[Type text] Page 94
IT WISDOM COMPUTER EDUCATION
}
Passing Array Elements to a Function
Array elements can be passed to a function
by calling the function by value, or by
reference. In the call by value we pass values
of array elements to the function, whereas in
the call by reference we pass addresses of
array elements to the function.
/*example of call by
value */
#include<stdio.h>
main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
display ( marks[i] ) ;
}
display ( int m )
{
printf ( "%d ", m ) ;
}
output.
55 65 75 56 78 78
90
j++ ;
}
}
int a[5][3];
'a' is a double dimensional array.
acceptable,
whereas,
would never
work.
sum += a[i][j];
printf("%5d",a[i][j]);
}
printf("%5d",sum);
printf("\n\n");
}
getch( );
}
Array of Pointers
The way there can be an array of ints or an
array of floats, similarly there can be an array of
pointers.
main()
{
int *arr[4] ; /* array of integer pointers */
int i = 5, j = 7, k = 9, l = 11, m ;
arr[0] = &i ;
arr[1] = &j ;
arr[2] = &k ;
arr[3] = &l ;
for ( m = 0 ; m <= 3 ; m++ )
printf ( "%d ", * ( arr[m] ) ) ;
}
Output: 5 7 9 11
STRINGS
String is a group of characters. Array of
integers is called an array ,where as array of
characters is known as string.
A string constant is always terminated by null
character(‘\0’). It tells where the string ends.
DECLARATION:
Ex: char name[10];
INITIALIZATION:
char name[]="WISDOM";
OR,
char name[7]="WISDOM";
OR,
char name[]={‘W’,’I’,’S’,’D’,’O’,’M’,'\0'};
OR;
char name[7]={‘W’,’I’,’S’,’D’,’O’,’M’,'\0'};
Each character occupies one byte.
during declaration ‘\0’ is not necessary.
C inserts the null character automatically.
W I S D O M ‘\0’
1801 1802 1803 1804 1805 1806
1807
Output:
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); .
printf("Name: ");
puts(name);
return 0;
}
Output:
Enter name: it wisdom
name : it wisdom
#inclue<stdio.h>
main()
{
char name[]=”itwisdom”;
int i=0;
Output:
itwisdom
#include<stdio.h>
main()
{
char name[]=”itwisdom”;
char *ptr;
ptr=name;
while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
ptr++;
}
#include <stdio.h>
void show(char ch[]);
int main()
{
char name[50];
printf("Enter string: ");
gets(name);
show(name);
return 0;
}
void show(char ch[])
{
printf("String Output: ");
puts(ch);
}
char name[]=”geetha”;
int len;
len=strlen(name);
printf(“length of the name= %d”,len);
getch();
}
Strcmp:
This is a function which compares two strings to
find out whether they are same or different. If the
two strings are identical, strcmp( ) returns a value
zero. If they’re not, it returns the numeric
difference between the ASCII values of the first
non-matching pairs of characters.
main( )
{
#include<stdio.h>
int main()
{
int i=0,j=0,k=0;
char str1[20],str2[20],temp[20];
puts("Enter first string");
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before swaping the strings are\n");
puts(str1);
puts(str2);
while(str1[i]!='\0')
{
temp[j++]=str1[i++];
}
temp[j]='\0';
i=0,j=0;
while(str2[i]!='\0')
{
str1[j++]=str2[i++];
}
str1[j]='\0';
i=0,j=0;
while(temp[i]!='\0')
{
str2[j++]=temp[i++];
}
str2[j]='\0';
printf("After swaping the strings are\n");
puts(str1);
puts(str2);
return 0;
}
#include<stdio.h>
int main()
{
char str[100];
int i=0;
return 0;
}
STRUCTURES
output
Enter names, prices and no. of pages of 2
books
C 100.00 354
C++ 256.50 682
}
printf("\nSum of distances=%d\'-
%.1f\"",sum.feet,sum.inch);
return 0;
}
Output
Enter information for 1st distance
Enter feet: 12
Enter inch: 3.45
Enter information for 1st distance
Enter feet: 12
Enter inch: 9.2
Sum of distances=25'-0.6"
Array of structures:
We can use array of structures like array of
integers.
};
struct book b[10];
for(i=0;i<10;i++)
{
printf ( "\nEnter names, prices & no. of
pages book %d\n" ,i+1) ;
scanf ( "%c %f %d", &b[i].name,
&b[i].price, &b[i].pages ) ;
}
printf ( "\nbooks details are:" ) ;
for(i=0;i<10;i++)
{
printf ( "\n%c %f %d", b[i].name,
b[i].price, b[i].pages ) ;
}
linkfloat( )
{
float a = 0, *b ;
b = &a ; /* cause emulator to be linked */
a = *b ; /* suppress the warning - variable
not used */
}
getch();
}
main( )
{
struct employee
{
char name[10] ;
int age ;
float salary ;
};
struct employee e1 = { "Sanjay", 30,
5500.50 } ;
struct employee e2, e3 ;
/* piece-meal copying */
strcpy ( e2.name, e1.name ) ;
e2.age = e1.age ;
e2.salary = e1.salary ;
/* copying all elements at one go */
e3 = e2 ;
printf ( "\n%s %d %f", e1.name, e1.age,
e1.salary ) ;
printf ( "\n%s %d %f", e2.name, e2.age,
e2.salary ) ;
printf ( "\n%s %d %f", e3.name, e3.age,
e3.salary ) ;
}
Nested structures:
main( )
{
struct address
{
int phone ;
char city[25] ;
int pin ;
};
struct emp
{
char name[25] ;
struct address a ;
};
struct emp e = { "jeru", 531046,
"nagpur", 10 };
printf ( "\nname = %s phone = %d",
e.name, e.a.phone ) ;
printf ( "\ncity = %s pin = %d", e.a.city,
e.a.pin ) ;
}
struct Res
{
int rno;
char sname[10];
struct Marks
{
char subname[30];
int submarks;
}m;
}r;
int main(void)
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&r.rno);
printf("\n\t Enter Student name : ");
scanf("%s",r.sname);
printf("\n\t Enter Subject name : ");
scanf("%s",r.m.subname);
printf("\n\t Enter Marks : ");
scanf("%d",&r.m.submarks);
printf("\n\n\t Roll Number : %d",r.rno);
printf("\n\n\t Student name : %s",r.sname);
printf("\nSubject name : %s",r.m.subname);
struct book
{
char name[25] ;
char author[25] ;
int callno ;
[Type text] Page 124
IT WISDOM COMPUTER EDUCATION
};
main( )
{
struct book b1 = { " C", "ITWISDOM",
101 } ;
display ( b1 ) ;
}
display ( struct book b )
{
printf ( "\n%s %s %d", b.name,
b.author, b.callno ) ;
}
Note: as pass
when we namethese
and cname are,base
variables declared as arrays
address of
arrays is passed to the called function.
The way we can have a pointer pointing to
an int, or a pointer pointing to a char,
similarly we can have a pointer pointing to a
struct. Such pointers are known as
‘structure pointers’.
an operator ->, called an arrow operator is
used to refer to the structure elements.
main( )
{
struct book
{
char
name[25] ;
char
author[25]
; int pgs ;
};
struct book b1 = { "C programming",
"ITWISDOM", 500 } ;
Uses of structures:
1. Clearing screen
2. Drawing any graphics shape on the screen
3. Receiving a key from the keyboard
4. Changing the size of the cursor
5. Hiding a file from the directory
6. Displaying the directory of a disk
7. Checking the memory size
8. Sending the output to printer
9. Interacting with the mouse
UNIONS
FILES
File is a place on disk where a group of related
data is stored.
File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file.
Types of files:
1. Text files
2. Binary files
Syntax
FILE *fp;
fp = fopen(“file name”, ”mode”);
fclose():-closes the already opened file.
Syntax
int fclose(file pointer)
fprintf( ):- prints the data on the specified file.
Syntax
int fprintf(FILE *fp, const char *format
[,arguments]);
fscanf():-reads the data from specified file.
Syntax
int fscanf(FILE *fp, const char *format,
arguments);
fwrite(): Writes to a stream
size_t
fwrite(address of the variable,size of the
variable,no.of copies, file pointer);
Writes n items of size bytes each. Returns the
number of items (not bytes) actually written.
#include<stdio.h>
int main()
{
FILE *fptr;
fptr=fopen(“c:\\add.txt”,”w”);
if(ptr==NULL)
{
printf(“error!”);
exit(1);
}
printf(“enter n:”);
scanf(“%d”,&n);
fprintf(fptr,”%d”,n);
return 0;
}
#include<stdio.h>
int main()
{
FILE *fptr;
if((fptr=fopen(“c:\\add.txt”,”r”))==NULL)
{
printf(“error!”);
exit(1);
}
fscanf(fptr,”%d”,&n);
printf(“value of n=%d”,n);
fclose(fptr);
return 0;
}
scanf("%s",&sna);
printf("enter student number");
scanf("%d",&sno);
printf("enter marks in 3 subjects ");
scanf("%d%d%d",&m1,&m2,&m3);
fprintf(p,"%20s%5d%3d%3d%3d",sna,sno,m1,m
2,m3);
printf("any more y/n");
ch=getch( );
}
while(ch=='y');
fclose(p);
}
/* program to read student data from student.txt
file */
#include <stdio.h>
main( )
{
char sna[20];
int sno,m1,m2,m3;
char ch;
FILE *p;
float tot,avg;
p=fopen("student.txt","r");
if(p= =NULL)
{
printf("Accessing not possible");
exit(0);
}
clrscr( );
while(!feof(p))
{
fscanf(p,"%20s%5d%3d%3d%3d",&sna,&sno,&
m1,&m2,&m3);
printf("student name :%s\n",sna);
printf("student number :%d\n",sno);
printf("marks in 3 sub :%d %d
%d\n",m1,m2,m3);
tot=m1+m2+m3;
avg=tot/3;
printf("student total marks :%f\n",tot);
printf("student avg marks :%5.2f\n",avg);
}
fclose(p);
}
/* Write a program to accept a file name and list
outnumber of characters, words and lines present
in it */
#include "stdio.h"
main()
{
char name[12],ch;
FILE *p;
int nc=0,nw=0,nl=0;
printf("enter file name to list");
scanf("%s",&name);
p=fopen(name,"r");
if(p==NULL)
[Type text] Page 141
IT WISDOM COMPUTER EDUCATION
{
printf("File Not Found :- %s",name);
exit(0);
}
while(!feof(p))
{
ch=fgetc(p);
nc++;
if(ch==' ')
nw++;
if(ch=='\n')
{
nw++;
nl++;
}
}
fclose(p);
clrscr();
printf("no of lines %d\n",nl);
Binary Files
Depending upon the way file is opened for
processing, a file is classified into text file and
binary file.
fwrite(address_data,size_data,numbers_data,po
inter_to_file);
Function fread() also take 4 arguments similar
to fwrite() function as above.
PREPROCESSORS
Preprocessor is a program that processes the
source code before passing it to the compiler.
Preprocessor provides many preprocessor
directives starts with # symbol. We can write these
directives anywhere in the program.
The preprocessor directives are
(a) Macro
expansion
Macro expansion:
Ex:
#define VALUE 10
main()
int i;
for(i=0;i<=VALUE;i++)
{
printf(“%d\n”,i);
}
getch();
}
NOTE:
EX2:.
#define PI
3.1415 main( )
{
float r = 6.25 ;
float area ;
area = PI * r * r ;
printf ( "\nArea of circle = %f", area ) ;
}
if(a>0ANDa<10)
X;
}
#define SQUARE(X) ( x * x )
main( )
{
int n1 = 6, n2 = 2, s ;
s= SQUARE ( n1 ) ;
printf ( "\nsuare of %d = %d",n1, s ) ;
s = SQUARE ( n2 ) ;
printf ( "\nsquare of %d = %d",n2, s ) ;
}
File inclusion:
It is used to include one file into another. there are
two ways to include these files. They are
Conditional Compilation :
Miscellaneous Directives
#undef directive
#pragma Directive
Output:
First function
Main function
Second function