Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

C Language Complete Guide

The document provides an overview of key concepts in the C programming language including: - The origins and evolution of C from earlier languages like ALGOL and BCPL. - Basic components of a C program including programs, compilers, variables, constants, operators, and data types. - Details on different types of constants, variables, operators like arithmetic, relational, logical, and bitwise operators. - Explanations of fundamental C concepts such as data types, variables, operators, and control flow structures over 11 pages in a detailed but accessible manner.

Uploaded by

Hunter Harsha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

C Language Complete Guide

The document provides an overview of key concepts in the C programming language including: - The origins and evolution of C from earlier languages like ALGOL and BCPL. - Basic components of a C program including programs, compilers, variables, constants, operators, and data types. - Details on different types of constants, variables, operators like arithmetic, relational, logical, and bitwise operators. - Explanations of fundamental C concepts such as data types, variables, operators, and control flow structures over 11 pages in a detailed but accessible manner.

Uploaded by

Hunter Harsha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

IT WISDOM COMPUTER EDUCATION

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.

Program: A set of instructions is called program.


Compiler: A compiler is a computer program that
transforms source code written in a programming
language into object code.

[Type text] Page 1


IT WISDOM COMPUTER EDUCATION

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 ( ) _ - + = | \ { } [ ] :
; "'<>,.?/

Constants: constant is a value which can not be


changed during execution.

Types of constants:
There are two types of constants
1. Primary constants.
2. Secondary constants.

[Type text] Page 2


IT WISDOM COMPUTER EDUCATION

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.

[Type text] Page 3


IT WISDOM COMPUTER EDUCATION

3. Commas, blanks and special symbols are not


allowed.(we can use underscore).
4. We can use any number of underscores in a
variable name.
5. Some compilers allow variable name length up to
247 characters.
Ex: c_o_m3
_n8a_me these are valid variable
names
Sum
_c_o#m@ these are not valid names
8su_m

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

[Type text] Page 4


IT WISDOM COMPUTER EDUCATION

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.

[Type text] Page 5


IT WISDOM COMPUTER EDUCATION

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

Simple Assignment operator:-


This operator is “equal to(=)” operator. The
general syntax for simple assignment operator is
V = constant value or expression;
Where V is the variable name.
Eg:- C=a+b;
A=100;

[Type text] Page 6


IT WISDOM COMPUTER EDUCATION

Shorthand Assignment operator:-


This operator add “equal to(=)” sign with all
arithmetic operators. The syntax is
V arithmetic operator = constant value or
expression;
Simple Shorthand
assignment assignment
i=i+1 i+=1
t=t*m-k t*=m-k
m=m/n m/=n
m=m-k*l m-=k*l
a=a*b a*=b

4.Logical operators : These operators are used for


multiple condition checking
OPERATOR PURPOSE
&& Logical and
|| Logical or
! Logical not

[Type text] Page 7


IT WISDOM COMPUTER EDUCATION

Truth table for logical AND


Op1 Op2 Op1&&op2
1 1 1
1 0 0
0 1 0
0 0 0

Truth table for logical OR


Op1 Op2 Op1||op2
1 1 1
1 0 1
0 1 1
0 0 0
5. Increment and Decrement Operators:-
These operators are called unary special
operators. The two operators are ++(increment
operator) and --(decrement operator). Increment
operator used for increment the value one by one.
Similarly, decrement operator is used. Further these
operators are divided into two types:

[Type text] Page 8


IT WISDOM COMPUTER EDUCATION

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

There are some more special operators available


in 'C' language which are used in pointers,
structures and unions. They are
3. Pointer operator(& and *)
4. Member selection operator(. and ->)

8. Bitwise operators : -
They are low level operators used to perform
logical calculation on bits i.e binary digits
Operator Meaning

& Bitwise AND


| Bitwise OR
>> Bitwise right
shift
<< Bitwise left shift

~ Bitwise
complement

Data types: data types are used to tell the type of


the data stored in the variable.
The data types are

[Type text] Page 11


IT WISDOM COMPUTER EDUCATION

Type Size(bits) Range


char or signed 8 -128 to 127
char
unsigned char 8 0 to 255
int ot signed 16 -32,768 to 32,767
int
unsigned int 16 0 to 65535
short int or 8 -128 to 127
signed short
int
unsigned 8 0 to 255
short int
long int or 32 -2,147,483,648 to
signed long 2,147,483,647
int
unsigned long 32 0 to 4,294,967,295
int
float 32 3.4E -38 to 3.4E
+38
double 64 1.7E -308 to 1.7E
+308
long double 80 3.4E -4932 to 1.1E
+4932

[Type text] Page 12


IT WISDOM COMPUTER EDUCATION

 Void is a special data type. It does not returns any


value.
Key words: keywords are the words whose meaning
has already been explained to the compiler. These
are also known as reserved words. 32 keywords are
there in c.
The keywords cannot be used as variable names
because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the
computer.

auto double int struct

break else long switch


case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

[Type text] Page 13


IT WISDOM COMPUTER EDUCATION

C Instructions: when we properly combine the


variables, data types and keywords instructions are
formed. A set of instructions is called a program.
Types of instructions:
1. Type Declaration Instruction- it is used to
declare the data type of variable.

Ex: int x;
Float y;
2. Input/output instruction- used to take input
from user and to send output to the user.

3. Arithmetic Instruction – used to


perform arithmetic operations.
There are three types of arithmetic
instructions

a) Integer mode arithmetic instruction :


This is an arithmetic statement in which
all operands are either integer
variables or integer constants.
1. Ex: int x=10,y=20;
a. int c;
b. C=x+y;

b)Real mode arithmetic instruction: This is


an arithmetic statement in which all

[Type text] Page 14


IT WISDOM COMPUTER EDUCATION

operands are either real variables or real


constants.

1. Ex: float a,b,c;


a. C=a+b;

c) Mixed mode arithmetic instruction: This


is an arithmetic statement in which some
of the operands are integers and some
of the operands are real.

4. Control Instruction: ‘Control Instructions’


tells us the order in which the various
instructions in a program are to be executed by
the computer.

There are four types of control


instructions in C.
(a) Sequence
Control Instruction
(b) Selection or Decision
Control Instruction
(c) Repetition or Loop
Control Instruction
(d) Case Control
Instruction

[Type text] Page 15


IT WISDOM COMPUTER EDUCATION

BASIC STRUCTURE OF ‘C’ PROGRAMMING:


Documentation Section
Preprocessor Section
Global Declaration Section
main() function
{
Declaration part;
Execution part;
}
Documentation Section: This section consist of a set
of comment lines giving the name of the program,
the another name and other details, which the
programmer would like to use later.

In c comments are written between /*-----------------*/


Ex:/*this is a program to add two numbers*/
Preprocessor Section: This section contains
preprocessor directives. The preprocessor directives
begin with # symbol. These statements includes the
header files.
Some of the header files are

[Type text] Page 16


IT WISDOM COMPUTER EDUCATION

#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.

/*program to print a statement*/


#include<stdio.h>
#include<conio.h>
main()
{
Clrscr();

[Type text] Page 17


IT WISDOM COMPUTER EDUCATION

Printf(“welcome to c”);
getch();
}

/*program to accept two values and add them*/


#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
printf(“enter two values”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum of %d and %d is %d”,a,b,c);
getch();
}

[Type text] Page 18


IT WISDOM COMPUTER EDUCATION

/*program to calculate simple interest*/


#include<stdio.h>
#include<conio.h>
main()
{
int t;
float r,p,si;
clrscr();
printf(“enter price,time and rate of interest\n”);
scanf(“%f%d%f”,&p,&t,&r);
si=p*t*r/100;
printf(“simple interest is %f”,si);
getch();
}

[Type text] Page 19


IT WISDOM COMPUTER EDUCATION

/*program to perform arithmetic operations on


two numbers*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
printf(“enter two values”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum of %d and %d is %d”,a,b,c);
c=a-b;
printf(“difference of %d and %d is %d”,a,b,c);
c=a*b;
printf(“product of %d and %d is %d”,a,b,c);
c=a/b;
printf(“quotient is %d”,c);
c=a%b;

[Type text] Page 20


IT WISDOM COMPUTER EDUCATION

printf(“remainder is %d”,c);
getch();
}

/*program to accept student number, name marks


in 3 subjects and calculate total and average*/
#include<stdio.h>
#include<conio.h>
main()
{
int rno,m1,m2,m3,tot;
float avg;
clrscr();
printf(“enter student number,name,marks in 3
subjects”);
scanf(“%d%s%d%d%d”,&rno,&name,&m1,&m
2,&m3);
printf(“student number is %d\n”,rno);
printf(“name is %s”,name);
tot=m1+m2+m3;

[Type text] Page 21


IT WISDOM COMPUTER EDUCATION

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();
}

[Type text] Page 22


IT WISDOM COMPUTER EDUCATION

DECISION MAKING STRUCTURES


Decision making statements are used to make
decision about which statement has to be executed
next.
There are 4 types of decision making statements
1. if
2. if-else
3. switch and
4. conditional operator

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*/

[Type text] Page 23


IT WISDOM COMPUTER EDUCATION

#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;
}

[Type text] Page 24


IT WISDOM COMPUTER EDUCATION

If condition is true statement 1 is executed. If


the condition is false statement 2 is executed.

/* program to check given number is even or odd*/


#include<stdio.h>
main()
{
int n;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
if(n%2==0)
printf(“%d is even number”,n);
else
printf(“%d is odd number”,n);
getch();
}

[Type text] Page 25


IT WISDOM COMPUTER EDUCATION

/*program to check given character is vowel or


consonant*/
#include <stdio.h>

int main()
{
char ch;

printf("Enter a character\n");
scanf("%c", &ch);

if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch


== 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' ||
ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", ch);

return 0;
}

/* program to accept the age and check whether


the person is eligible to vote or not*/
#include<stdio.h>
main()

[Type text] Page 26


IT WISDOM COMPUTER EDUCATION

{
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);

[Type text] Page 27


IT WISDOM COMPUTER EDUCATION

else
Printf(“%d is not divisible by boh the
numbers”,n);
}

/* program to check given year is leap year or


not*/
#include<stdio.h>
main()
{
int yr;
if(yr%4==0)
printf(“%d is leap year”,yr);
else
printf(“%d is not leap year”,yr);
}

[Type text] Page 28


IT WISDOM COMPUTER EDUCATION

/* program to check biggest of two numbers*/


#include<stdio.h>
main()
{
int a,b;
printf(“enter two values”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“%d is biggest number”,a);
else
printf(“%d is biggest number”,b);
}

If –else-if ladder:
if(condition)
statement;
else if(condition)
statement;
else if(condition)

[Type text] Page 29


IT WISDOM COMPUTER EDUCATION

statement;
else
statement;

/* program to check whether given number is equal


to zero , positive or negative*/
#include<stdio.h>
main()
{
int n;
clrscr();
printf(“enter a number”);
scanf(“%d”,& n);
if(n==0)
printf(“number is zero”);
else if(n>0)
printf(“positive number”);
else
printf(“negative number”);

[Type text] Page 30


IT WISDOM COMPUTER EDUCATION

getch();
}

/* Accept student number, marks in 3 sub.


Calculate average and display result.
AVERAGE RESULT
>75 - Distinction
>60 - I Class
>50 - II Class
>35 - III Class
Otherwise - Fail */
main( )
{
int sno,m1,m2,m3,tot;
float avg;
clrscr( );
printf("\n Enter student number : ");
scanf("%d",&sno);
printf("\n Enter marks in 3 subjects : ");

[Type text] Page 31


IT WISDOM COMPUTER EDUCATION

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( );
}

[Type text] Page 32


IT WISDOM COMPUTER EDUCATION

/*A company insures its drivers in the


following cases:
− If the driver is
married.
− If the driver is unmarried, male &
above 30 years of age.
− If the driver is unmarried, female &
above 25 years of age.*/

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" ) ;

[Type text] Page 33


IT WISDOM COMPUTER EDUCATION

}
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;

[Type text] Page 34


IT WISDOM COMPUTER EDUCATION

}
else
{
if(condition3)
statement3;
else
statement4;
}

(Or)
if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
{

[Type text] Page 35


IT WISDOM COMPUTER EDUCATION

statement3;
}
(Or)
if(condition1)
{
statement1;
}
else
{
if(condition2)
statement2;
else
statement3;
}

[Type text] Page 36


IT WISDOM COMPUTER EDUCATION

/*program to check whether the person is


eligible to vote or not using nested if-else*/
#include<stdio.h>
main()
{
int age;
printf(“enter the age”);
scanf(“%d”,&age);
if(age==0)
printf(“invalid age”);
else
{
if(age>=18)
printf(“eligible to vote”);
else
printf(“not eligible to vote”);
}

[Type text] Page 37


IT WISDOM COMPUTER EDUCATION

/*program to find out greatest of three numbers*/


main( )
{
int a,b,c,big;
clrscr( );
printf("\n Enter 3 numbers : ");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
if(a>c)
big = a;
else
big = c;
else
if(b>c)
big = b;
else
big = c;
printf("\n Biggest number : %d",big);
getch( );

[Type text] Page 38


IT WISDOM COMPUTER EDUCATION

/*program to check whether given number is equal


to zero ,positive or negative */
#include<stdio.h>
main()
{
int n;
printf(“enter a number”);
scanf(“%d”,&n);
if(n==0)
printf(“number is zero”);
else
{
if(n>0)
printf(“%d is a positive number “,n);
else
printf(“%d is a negative number”,n);
}
getch();
}

[Type text] Page 39


IT WISDOM COMPUTER EDUCATION

CASE CONTROL STATEMENT:


Switch statement: Switch case checks the value of
expression/variable against the list of case values
and when the match is found , the block of
statement associated with that case is executed.

switch(condition)
{
case 1: statement;
break;
case 2:statement;
break;
case 3:statement;
break;
case n: statement;
break;
default: statement;
break;
}
Switch case rules:

[Type text] Page 40


IT WISDOM COMPUTER EDUCATION

1. Case label must be unique and ends with a


colon(:)
2. Case label might be integer or character
constants but it should not be floating point
number.
3. Default label is optional and can be placed
anywhere in switch.
4. Break statement takes control out of the switch
5. Two or more cases may share one break
statement
6. Relational Operators are not allowed in Switch
Statement.
7. Break statement after default case is optional.

//program to check whether the given alphabet is an


vowel or not
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter an alphabet");
scanf("%c",&ch);
switch( ch )
{
case 'A':
case ‘a’: printf( "it is a vowel\n" );

[Type text] Page 41


IT WISDOM COMPUTER EDUCATION

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();
}

/*program to create a simple calculator for


addition, subtraction, multiplication and
division using switch case statement . */

# include <stdio.h>
int main()
{
char op;

[Type text] Page 42


IT WISDOM COMPUTER EDUCATION

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;

[Type text] Page 43


IT WISDOM COMPUTER EDUCATION

/*C code to covert each digits of a number in


English word*/

#include<stdio.h>

int main(){

int num,i=0,j,digit;
char * word[1000];

printf("Enter any integer: ");


scanf("%d",&num);

while(num)
{

digit = num %10;


num = num /10;

switch(digit)
{
case 0: word[i++] = "zero";
break;
case 1: word[i++] = "one";
break;
case 2: word[i++] = "two";

[Type text] Page 44


IT WISDOM COMPUTER EDUCATION

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:

[Type text] Page 45


IT WISDOM COMPUTER EDUCATION

Enter any integer: 23451208


two three four five one two zero eight

/*program to print the selected day using switch*/


#include<stdio.h>
main()
int m;
printf(“enter your choice between 1 and 7”);
scanf(“%d”,&m);
switch(m)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“monday”);
break;
case 3: printf(“tuesday”);
break;
case 4: printf(“wednesday”);
break;

[Type text] Page 46


IT WISDOM COMPUTER EDUCATION

case 5: printf(“thursday”);
break;
case 6: printf(“friday”);
break;
case 7: printf(“saturday”);
break;
default: printf(“invalid choice”);
break;
}
getch();
}

[Type text] Page 47


IT WISDOM COMPUTER EDUCATION

LOOP CONTROL STRUCTURE


Loop control structures are used to execute a set of
instructions repeatedly. This involves repeating
some portion of the program either a specified
number of times or until a particular condition is
being satisfied.
There are three types of loops in c
1. While loop
2. Do-while loop
3. For loop

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.

/*program to print 1 to 10 natural numbers*/

[Type text] Page 48


IT WISDOM COMPUTER EDUCATION

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 : ");

[Type text] Page 49


IT WISDOM COMPUTER EDUCATION

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;

[Type text] Page 50


IT WISDOM COMPUTER EDUCATION

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;
}

/* program to reverse a number*/


#include <stdio.h>

int main()
{
int n, rev = 0,rem;

printf("Enter a number to reverse\n");


scanf("%d", &n);

while (n != 0)
{

[Type text] Page 51


IT WISDOM COMPUTER EDUCATION

rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf("Reverse of entered number is = %d\n",
rev);

return 0;
}

/*program to check whether given number is


palindrome or not*/
#include <stdio.h>

int main()
{
int n, rev = 0, t;

printf("Enter a number to check if it is a


palindrome or not\n");
scanf("%d",&n);

t = n;

while( t != 0 )
{
rem=n%10;
rev=rev*10+rem;

[Type text] Page 52


IT WISDOM COMPUTER EDUCATION

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;
}

/*program to print multiplication tables*/


#include <stdio.h>
int main()
{
int num, i = 1;
printf("\n Enter any Number:");
scanf("%d", &num);
printf("Multiplication table of %d: \n", num);
while (i <= 10)
{
printf("\n %d x %d = %d", num, i, num * i);
i++;
}
return 0;
}

[Type text] Page 53


IT WISDOM COMPUTER EDUCATION

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( );

[Type text] Page 54


IT WISDOM COMPUTER EDUCATION

do
{
printf(“%5d “,i);
i++;
}
while(i<=5);
getch( );
}

/*C program to find factorial of a given


number*/
#include <stdio.h>
int main()
{
int num,fact=1;
printf("Enter a number.\n");
scanf("%d",&num);
do

{
fact=fact*num;
num--;
}

[Type text] Page 55


IT WISDOM COMPUTER EDUCATION

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 ; )
{

[Type text] Page 56


IT WISDOM COMPUTER EDUCATION

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;
}
}

/* C program to display character from A to Z


using loops. */

#include <stdio.h>
int main()
{
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
return 0;
}

[Type text] Page 57


IT WISDOM COMPUTER EDUCATION

/*program to find out factorial of given


number*/
#include <stdio.h>

int main()
{
int i, n, fact = 1;

printf("Enter a number to calculate it's


factorial\n");
scanf("%d", &n);

for (i = 1; i <= n; i++)


fact = fact * i;

printf("Factorial of %d = %d\n", n, fact);

return 0;
}

/* C to find and display all the factors of a


number entered by an user */

#include <stdio.h>
int main()
{
int n,i;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factors of %d are: ", n);

[Type text] Page 58


IT WISDOM COMPUTER EDUCATION

for(i=1;i<=n;++i)
{
if(n%i==0)
printf("%d ",i);
}
return 0;
}

/* Program to print Fibonacci series */


#include<stdio.h>

int main()
{
int n, first = 0, second = 1, next, i;

printf("Enter the number of terms\n");


scanf("%d",&n);

printf("First %d terms of Fibonacci series are :-


\n",n);

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


{
if ( i <= 1 )
next = i;
else
{
next = first + second;
first = second;

[Type text] Page 59


IT WISDOM COMPUTER EDUCATION

second = next;
}
printf("%d\n",next);
}

return 0;
}

/*program to print the given pattern*/


*
**
***
****
*****
#include <stdio.h>

int main()
{
int n, c, k;

printf("Enter number of rows\n");


scanf("%d",&n);

for ( c = 1 ; c <= n ; c++ )


{
for( k = 1 ; k <= c ; k++ )
printf("*");

[Type text] Page 60


IT WISDOM COMPUTER EDUCATION

printf("\n");
}

return 0;
}

/*program to print sum of natural numbers*/

#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;
}

[Type text] Page 61


IT WISDOM COMPUTER EDUCATION

Unconditional control statements or jumping


statements
They are used to transfer the control without
checking conditions.
goto statement :
This is used to transfer the control from
current point of program execution to the ‘label’
specified.
Syntax :
goto <label>;
Program 1:
/* Example on goto statement */
main( )
{
clrscr( );
printf("Good Morning ");
goto sam;
printf("Every body ");
sam:
printf("Students of ITWISDOM");

[Type text] Page 62


IT WISDOM COMPUTER EDUCATION

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);

[Type text] Page 63


IT WISDOM COMPUTER EDUCATION

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( );
}

[Type text] Page 64


IT WISDOM COMPUTER EDUCATION

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;

[Type text] Page 65


IT WISDOM COMPUTER EDUCATION

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();
}

 “&“ is called address of operator.


 “*” is called value at address operator.
Note:
1. we can add a number to the pointer.
2. we can subtract a number from pointer.
3. we can not multiply a constant and pointers.
4. we can not divide a ponter with a constant.
5. we can subtract one pointer from another
pointer. when we want to subtract two pointers
,they must point to the values of same array.
6. But we can not add two pointers.

[Type text] Page 66


IT WISDOM COMPUTER EDUCATION

STORAGE CLASSES
 To fully define a variable we need to mention
it’s storage class along with it’s data type.

There are two kinds of locations in computer to


store the values. They are
a) Memory and
b) CPU Registers.
 Depending on the variable storage class these
locations are selected.
 If we did not mention any storage class the
compiler will automatically assigns the location
depending on the context in which the variable
is used.
Storage class of a variable tells that,
 Where the variable would store i.e either in
memory or in CPU Registers.
 What will be the initial value of the variable(if
we did not specify the initial value).
 What is the scope of the variable.
 What is the life of the variable.

There are 4 types of storage classes


1. Automatic storage class
2. Register storage class
3. Static storage class
4. External storage class

[Type text] Page 67


IT WISDOM COMPUTER EDUCATION

Storage keywor Storag Default scope Life


class d e initial
type value
Automat auto Memor Garbag Local Till
ic y e value control
remain
s within
the
block
Register register CPU Garbag Local Till
registe e value control
r remain
s within
the
block
Static static Memor Zero Local Persists
y betwee
n
differe
nt
functio
n calls
External extern Memor Zero Glob As long
y al as
progra
m
exists.

[Type text] Page 68


IT WISDOM COMPUTER EDUCATION

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:

1. Library functions : These are built in functions


available in header files.
Ex : strcmp, strcat, sqrt.
2. User defined functions: Functions defined by
programmer

C function declaration, function call and function


definition:
There are 3 aspects in each C function. They are,
 Function declaration or prototype -
This informs compiler about the function name,
function parameters and return value’s data
type.
 Function call – This calls the actual function
 Function definition – This contains all the
statements to be executed.

[Type text] Page 69


IT WISDOM COMPUTER EDUCATION

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 );

 We can send parameters(arguments) to functions

 Arguments of calling are called "actual


parameters" and the arguments used in the called
function are called "formal parameters".

 The values of actual parameters are received by


the formal parameters (receiving parameters)

 The number of actual parameters should be equal


to the number of formal parameters and their
corresponding data types should match.

[Type text] Page 70


IT WISDOM COMPUTER EDUCATION

/*program to add two numbers using functions*/

#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);
}

Calling function and called functions:


main( )
{
printf ( "\n I am in main function" ) ;
c( ) ;
java( ) ;
oracle( )
;
}
c( )
{
[Type text] Page 71
IT WISDOM COMPUTER EDUCATION

printf ( "\n I am learning c language" ) ;


}
oracle( )
{
printf ( "\n I am learning oracle" ) ;
}
java( )
{
printf ( "\n I am learning java" ) ;
c();
}

 Every c program must contain main() function


because execution of a program starts from
main() function
 If a program contains more than one main()
function the compiler will get confused from
where the program execution has to be started.
 A function gets called when the function name is
followed by a semicolon.

 A function is defined when function name is


followed by a pair of braces in which one or
more statements may be present
 Any function can be called from any other
function. Even main( ) can be called from other
functions.
 A function can be called any number of times.

 The order in which the functions are


defined in a program and the order in
which they get called need not
necessarily be same.

[Type text] Page 72


IT WISDOM COMPUTER EDUCATION

 A function can call itself. Such a process is


called ‘recursion’.
 A function can be called from other function,
but a function cannot be defined in another
function.

Depending on the usage of the arguments and return


type functions are of four type.
1. Function without arguments and without return
type
2. Function without arguments and with return
type.
3. Function with arguments without return type.
4. Function with arguments and with return type.

Function without arguments and without return


type.
#include<stdio.h>
#include<conio.h>
main()
{
area();
}
area()

[Type text] Page 73


IT WISDOM COMPUTER EDUCATION

{
float pi=3.14;
int r,a;
a=pi*r*r;
printf(“area of circle=%f”,a);
}

Function without arguments and with return type.


#include<stdio.h>
#include<conio.h>
main()
{
float x
x=area();
printf(“area is %f”,x);
}
area()
{
float pi=3.14;
int r,a;
a=pi*r*r;
return(a);
}

[Type text] Page 74


IT WISDOM COMPUTER EDUCATION

Function with arguments without return type.


#include<stdio.h>
#include<conio.h>
main()
{
int r;
printf(“enter radius”);
scanf(“%d”,&r);
area(r);
}
area(int x)
{
float pi=3.14;
float a;
a=pi*x*x;
printf(“area is %f”,a);
}

Function with arguments and with return type.


#include<stdio.h>
#include<conio.h>
main()
{
int r,a;
printf(“enter radius”);

[Type text] Page 75


IT WISDOM COMPUTER EDUCATION

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);
}

/*program to find out square of a number*/


#include<stdio.h>
main( )
{
float square ( float ) ;
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
}
float square ( float x )
{
[Type text] Page 76
IT WISDOM COMPUTER EDUCATION

float y ;
y=x*x;
return ( y ) ;
}

/* Finding factorial using function */


#include<stdio.h>
main( )
{
int a,res;
int fact(int );
clrscr( );
printf("\n Enter a number : ");
scanf("%d",&a);
res = fact(a);
printf("\n Factorial of %d = %d",a,res);
getch( );
}
/* The function fact */
int fact(int x)
{

[Type text] Page 77


IT WISDOM COMPUTER EDUCATION

int f;
for(f=1;x>0;x--)
f = f * x;
return f;
}

/*program to find largest of two numbers using


functions*/
#include<stdio.h>
#include<conio.h>
void main()
{
float a , b , max;
clrscr();
float large(float x , float y); /*
Function declaration */

printf(" Enter the value of two numbers\n");


scanf("%f%f" , &a , &b);

printf("a = %f and b = %f\n" , a, b);


max = large(a,b);
printf(" The largest number is = %f\n" , max);

[Type text] Page 78


IT WISDOM COMPUTER EDUCATION

} /* End of
main() */

float large(float x , float y)


{
if(x>y)
{
return(x);
}
else /* ( y>x ) */
{
return(y);
}
}

/* Example on global variables */


int a,b,c;
main( )
{
void sum( );
clrscr( );
printf("\n Enter 2 numbers : ");
scanf("%d%d",&a,&b);
sum( );
[Type text] Page 79
IT WISDOM COMPUTER EDUCATION

printf("\n Sum is %d",c);


getch( );
}
/* The function sum */
void sum( )
{
c = a + b;
}
/* program to find square of a number using
functions*/
main(
)
{
float square ( float ) ;
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
}
float square ( float x )
{
float y ;
y=x*x;
return ( y ) ;
}

[Type text] Page 80


IT WISDOM COMPUTER EDUCATION

METHODS FOR PASSING THE VALUES


There are two ways of sending values between the
functions.
1. By passing values(call by value)
2. By passing address(call by reference)

CALL BY VALUE:
 In Call by Value, the value of actual parameter
is passed to formal parameter.

 If the value of formal parameter is changed, it


will not affect the corresponding values of actual
parameter. Because the formal and actual
parameters maintain separate memory locations
to hold data.

[Type text] Page 81


IT WISDOM COMPUTER EDUCATION

/*program to swap two numbers using call by value


method*/
main( )
{
int a = 10, b = 20 ;
swapv ( a, b ) ;
printf ( "\na = %d b = %d", a, b ) ;
}
swapv ( int x, int y )
{
int t ;
t=x;
x=y;
y=t;
printf ( "\nx = %d y = %d", x, y ) ;
}

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.

[Type text] Page 82


IT WISDOM COMPUTER EDUCATION

/* PROGRAM TO SWAP TWO NUMBERS USING


CALL BY REFERENCE METHOD*/
main( )
{
int a = 10, b = 20 ;
swapr ( &a, &b ) ;
printf ( "\na = %d b = %d", a, b ) ;
}
swapr( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}

RECURSION: The process of calling a function by


itself is called recursion.
main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
[Type text] Page 83
IT WISDOM COMPUTER EDUCATION

return ( 1 ) ;
else
if = x * rec ( x - 1 ) ;
return ( f ) ;
}

/*C code to convert decimal number to binary


number by recursion*/
#include<stdio.h>

long DtoB(int);

int main()
{

long bNo;
int dNo;

printf("Enter any decimal number: ");


scanf("%d",&dNo);

bNo = DtoB(dNo);
printf("Binary value is: %ld",bNo);

return 0;
}

long DtoB(int dNo)


{

[Type text] Page 84


IT WISDOM COMPUTER EDUCATION

static long bNo,rem,factor = 1;

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

/*Sum of digits in c using recursion*/


#include<stdio.h>
int main()
{
int num,x;
clrscr();
printf("\nEnter a number: ");

[Type text] Page 85


IT WISDOM COMPUTER EDUCATION

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;
}

[Type text] Page 86


IT WISDOM COMPUTER EDUCATION

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

Single dimensional array:


An array with only single subscripted value is
called a single dimensional array.
int a[5];
'a' is a single dimensional array.

[Type text] Page 87


IT WISDOM COMPUTER EDUCATION

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];

Initialization of one-dimensional array:


Arrays can be initialized at declaration time
in this source code as:

int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays


during initialization.

int age[]={2,4,34,3,4};

[Type text] Page 88


IT WISDOM COMPUTER EDUCATION

/*program to enter student details using array*/


main( )
{
int avg, sum = 0 ;
int i ;
int marks[10] ; /* array declaration */
for ( i = 0 ; i <= 9 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* enter
data in array */
}
for ( i = 0 ; i <= 9 ; i++ )
sum = sum + marks[i] ; /* read data from
an array*/
avg = sum / 10 ;
printf ( "\nAverage marks = %d", avg ) ;
}
/*program to findout greatest element of array
elements*/

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

int main()
{
int a[20],n,i,max=0; // declared the array a
with size 20
clrscr();

[Type text] Page 89


IT WISDOM COMPUTER EDUCATION

printf("\n Enter the number of elements for


1-D array : ");
scanf("%d",&n);

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];
}

printf("\n Greatest element from above array


inserted is : %d",max);

getch();

return 0;
}
/* Accept 5 elements into an array and display
values from last cell to first */
main( )

[Type text] Page 90


IT WISDOM COMPUTER EDUCATION

{
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( );
}

/* Accept some numbers into an array and find sum


of even and odd numbers */
main( )
{
int a[15], n, even, odd, i;
clrscr( );
printf("\n Enter size of array : ");

[Type text] Page 91


IT WISDOM COMPUTER EDUCATION

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( );
}

[Type text] Page 92


IT WISDOM COMPUTER EDUCATION

/* program for Adding 2 arrays */


main( )
{
int a[5],b[5],c[5],i;
clrscr( );
printf("\n Enter 5 elements of array a :\n\n ");
for(i=0;i<5;i++)

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( );

[Type text] Page 93


IT WISDOM COMPUTER EDUCATION

}
/* 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

[Type text] Page 95


IT WISDOM COMPUTER EDUCATION

/* example of call by reference */


main( )
{
int i ;
int marks[ ] = { 10, 20, 30, 40, 50, 60, 70 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ;
}
disp ( int *n )
{
printf ( "%d ", *n ) ;
}
output
10 20 30 40 50 60 70

Passing an Entire Array to a


Function

We can pass an entire array to a


function rather than its individual
elements.
/* example of passing an
entire array to a function */
main(
)
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
dislpay ( &num[0], 6 ) ;
}

[Type text] Page 96


IT WISDOM COMPUTER EDUCATION

display ( int *j, int n )


{
int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "\nelement = %d", *j ) ;

j++ ;
}
}

Two dimensional array: An array with two


subscripted values is called a double
dimensional array.
A 2D array is a collection of many 1D arrays.

int a[5][3];
'a' is a double dimensional array.

In the above example 'a' is an array of 5 single


dimensional arrays each of size 3.

[Type text] Page 97


IT WISDOM COMPUTER EDUCATION

int stud[4][2] ={ 1234, 56 },


{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
or even this
would work...
int stud[4][2] = { 1234, 56, 1212, 33,
1434, 80, 1312, 78 } ;
It is important to remember that while
initializing a 2-D array it is necessary
to mention the second (column)
dimension, whereas the first dimension
(row) is optional.
Thus the
declarations,
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45,
56, 45 } ;
are perfectly

acceptable,

whereas,

int arr[2][ ] = { 12, 34, 23,


45, 56, 45 } ;
int arr[ ][ ] = { 12,
34, 23, 45, 56, 45 } ;

[Type text] Page 98


IT WISDOM COMPUTER EDUCATION

would never
work.

/* Example to print student number and name


using 2D Array */
main( )
{
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0],
&stud[i][1] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

/* Accept elements into 3x3 2D array and display


the same */
main( )
{
int a[3][3],i,j;
clrscr( );

[Type text] Page 99


IT WISDOM COMPUTER EDUCATION

printf("\n Enter elements of A :\n");


for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("\n Enter element (%d,%d) : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
printf("\n\n Elements of A :\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%5d",a[i][j]);
printf("\n\n");
}
getch( );
}

[Type text] Page 100


IT WISDOM COMPUTER EDUCATION

/* Accept a 3x3 matrix and display the matrix along


with row sum */
main( )
{
int a[3][3],i,j,sum;
clrscr( );
printf("\n Enter elements of A :\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("\n Enter element (%d,%d) : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
printf("\n\n The elements of A along with row
sum :\n\n");
for(i=0;i<3;i++)
{
for(sum=j=0;j<3;j++)
{
[Type text] Page 101
IT WISDOM COMPUTER EDUCATION

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

[Type text] Page 102


IT WISDOM COMPUTER EDUCATION

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.

[Type text] Page 103


IT WISDOM COMPUTER EDUCATION

W I S D O M ‘\0’
1801 1802 1803 1804 1805 1806
1807

/*program to accept a name and to print the


name*/
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}

Output:

Enter name: it wisdom


Your name is it

Here, program will ignore wisdom


because, scanf() function takes only string
before the white space.

[Type text] Page 104


IT WISDOM COMPUTER EDUCATION

To solve this problem gets() function is used.

#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

/*C program to read line of text manually.*/

#inclue<stdio.h>
main()
{
char name[]=”itwisdom”;
int i=0;

[Type text] Page 105


IT WISDOM COMPUTER EDUCATION

while(i<=5) /*while(name[i]!=0) is also same*/


{
printf(“%c”,name[i]);
i++;
}
}

Output:
itwisdom

we can also print the string using pointers

#include<stdio.h>
main()
{
char name[]=”itwisdom”;
char *ptr;
ptr=name;
while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
ptr++;
}

[Type text] Page 106


IT WISDOM COMPUTER EDUCATION

Passing Strings to Functions

String can be passed to function in similar


manner as arrays as, string is also an array.

#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);
}

[Type text] Page 107


IT WISDOM COMPUTER EDUCATION

String Handling Functions


There are numerous functions defined
in "string.h" header file.
FUNCTION DESCRIPTION
strlen() Calculates the
length of the string.
strcpy() Copies one string to
another.
strlwr() Converts upper case
to lowercase.
strupr() Converts lower case
to uppercase.
strcat() Combines two
strings.
strcmp() Compares two
strings.
strrev() Reverses the string.

/*program to calculate string length*/


#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{

[Type text] Page 108


IT WISDOM COMPUTER EDUCATION

char name[]=”geetha”;
int len;
len=strlen(name);
printf(“length of the name= %d”,len);
getch();
}

/*program to copy and reverse the string*/


#include<stdio.h>
#include<string.h>
main()
{
char name1[]=”geetha”;
char name2[10];
strcpy(name2,name1);
printf(“name is %s “,name2);
printf(“reverse of the name is
%s”,strrev(name2));
getch();
}
[Type text] Page 109
IT WISDOM COMPUTER EDUCATION

/*program to combine two strings*/


#include<stdio.h>
#include<conio.h>
main()
{
char name1[]=”IT”;
char name2[]=”WISDOM”;
strcat(name1,name2);
printf(“first name is %s”,name1);
printf(“name after concatenation %s”,name2);
}

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( )
{

[Type text] Page 110


IT WISDOM COMPUTER EDUCATION

char string1[ ] = "january" ;


char string2[ ] = "February" ;
int i, j, k ;
i = strcmp ( string1, "january" );
j = strcmp ( string1, string2 );
k = strcmp ( string1, "june");
printf ( "\n%d %d %d", i, j, k ) ;
}

/*Swapping of strings using c programming


language*/

#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");

[Type text] Page 111


IT WISDOM COMPUTER EDUCATION

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");

[Type text] Page 112


IT WISDOM COMPUTER EDUCATION

puts(str1);
puts(str2);
return 0;
}

/*Program to convert string into ASCII values in c


programming language*/

#include<stdio.h>

int main()
{

char str[100];
int i=0;

printf("Enter any string: ");


scanf("%s",str);

printf("ASCII values of each characters of given


string: ");
while(str[i])
printf("%d ",str[i++]);

return 0;
}

[Type text] Page 113


IT WISDOM COMPUTER EDUCATION

STRUCTURES

Structure is a collection of different data type


elements.
Syntax:
struct structurename
{
Datatype variable1;
Datatype variable2;
:
:
Datatype variable n;
};

Declaring structure variables:

 We can declare any number of structure


variables.
 We can initialize the structure variables at the
time of declaration.

[Type text] Page 114


IT WISDOM COMPUTER EDUCATION

Ex: struct book


{
char name;
float price;
int pages;
};
Struct book b1={“ Let Us C”,350,500};
Struct book b2={“ C++”,400,600};

Accessing structure elements:


Dot operator (.)is used to access structure elements.

[Type text] Page 115


IT WISDOM COMPUTER EDUCATION

/*program to store information of student using


structure*/
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("Enter information of
students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}

[Type text] Page 116


IT WISDOM COMPUTER EDUCATION

/*program to store details of books*/


#include<stdio.h>
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2 ;

printf ( "\nEnter names, prices & no. of


pages of 2 books\n" ) ;
scanf ( "%c %f %d", &b1.name,
&b1.price, &b1.pages ) ;
scanf ( "%c %f %d", &b2.name,
&b2.price, &b2.pages ) ;

printf ( "\nbooks details are:" ) ;


printf ( "\n%c %f %d", b1.name, b1.price,
b1.pages ) ;
printf ( "\n%c %f %d", b2.name, b2.price,
b2.pages ) ;
}

output
Enter names, prices and no. of pages of 2
books
C 100.00 354
C++ 256.50 682

[Type text] Page 117


IT WISDOM COMPUTER EDUCATION

/*program to add two distance using structure*/


#include <stdio.h>
struct Distance
{
int feet;
float inch;
}d1,d2,sum;
int main()
{
printf("Enter information for 1st
distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet);
printf("Enter inch: ");
scanf("%f",&d1.inch);
printf("\nEnter information for 2nd
distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet);
printf("Enter inch: ");
scanf("%f",&d2.inch);
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;

/* If inch is greater than 12, changing it to


feet. */
if (sum.inch>12.0)
{
sum.inch=sum.inch-12.0;
++sum.feet;

[Type text] Page 118


IT WISDOM COMPUTER EDUCATION

}
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.

/*program to enter details of 10 books*/


#include<stdio.h>
main( )
{
struct book
{
char name ;
float price ;
int pages ;

[Type text] Page 119


IT WISDOM COMPUTER EDUCATION

};
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();
}

If we don’t define linkfloat( )


function you are bound to get the
error "Floating Point Formats Not
Linked" with majority of C Compilers.
When parsing our source file, if the
compiler encounters a reference to the
address of a float, it sets a flag to
have the linker link in the floating-
point emulator. A floating point

[Type text] Page 120


IT WISDOM COMPUTER EDUCATION

emulator is used to manipulate floating


point numbers linkfloat( ) forces
linking of the floating-point emulator
into an application. There is no need to
call this function, just define it
anywhere in your program.

 The values of a structure variable can be


assigned to another structure variable of the
same type using the assignment operator.

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,

[Type text] Page 121


IT WISDOM COMPUTER EDUCATION

e2.salary ) ;
printf ( "\n%s %d %f", e3.name, e3.age,
e3.salary ) ;
}

Nested structures:

One structure can be nested within another


structure

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 ) ;
}

[Type text] Page 122


IT WISDOM COMPUTER EDUCATION
/*program to print student marks using nested
structures*/
#include <stdio.h>
#include <conio.h>

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);

[Type text] Page 123


IT WISDOM COMPUTER EDUCATION

printf("\n\n\t Marks : %d",r.m.submarks);


getch();
return 0;
}
Passing structure to the function
 A structure variable can also be passed
to a function.
individual We may
structure either pass
elements orgo.
the
entire structure variable at one
 We can
.They pass
are a structure
call by value in two
and callways
by
reference.
/* Passing individual structure elements */
main( )
{
struct employee
{
char
name[25] ;
char
cname25] ;
int eid ;
};
struct employee e1 = { "geetha",
"ITWISDOM", 10 } ;
display ( e1.name, e1.cname, e1.eid ) ;
}
display ( char *s, char *t, int n )
{
printf ( "\n%s %s %d", s, t, n ) ;
}
/*passing entire structure*/

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 } ;

[Type text] Page 125


IT WISDOM COMPUTER EDUCATION

struct book *ptr ;


ptr = &b1 ;
printf ( "\n%s %s %d", b1.name,
b1.author, b1.pgs ) ;
printf ( "\n%s %s %d", ptr->name, ptr-
>author, ptr->pgs ) ;
}
/*program to calculate difference of two time
periods*/
#include <stdio.h>
struct TIME
{
int sec;
int min;
int hrs;
};
void Difference(struct TIME t1, struct TIME t2,
struct TIME *diff);
int main()
{
struct TIME t1,t2,diff;
printf("Enter start time: \n");
printf("Enter hours, minutes and seconds
respectively: ");
scanf("%d%d%d",&t1.hrs,&t1.min,&t1.sec);
printf("Enter stop time: \n");
printf("Enter hours, minutes and seconds
respectively: ");
scanf("%d%d%d",&t2.hrs,&t2.min,&t2.sec);
Difference(t1,t2,&diff);

[Type text] Page 126


IT WISDOM COMPUTER EDUCATION

printf("\nTIME DIFFERENCE: %d:%d:%d -


",t1.hrs,t1.min,t1.sec);
printf("%d:%d:%d ",t2.hrs,t2.min,t2.sec);
printf("=
%d:%d:%d\n",diff.hrs,diff.min,diff.sec);
return 0;
}
void Difference(struct TIME t1, struct TIME t2,
struct TIME *differ)
{
if(t2.sec>t1.sec)
{
--t1.min;
t1.sec+=60;
}
differ->sec=t1.sec-t2.sec;
if(t2.min>t1.min)
{
--t1.hrs;
t1.min+=60;
}
differ->min=t1.min-t2.min;
differ->hrs=t1.hrs-t2.hrs;
}
Output
Enter start time:
Enter hours, minutes and seconds respectively:
12

[Type text] Page 127


U.S.A in the year 1972.
C’ wasinevolved
U.S.A the yearfrom ALGOL, BCPL and B by “Dennis Ritchie” at Bell Laboratories in
1972.
U.S.A in the year 1972.
Program: A set of instructions is called program.
Program: A set ofIT WISDOM
instructions COMPUTER
is called program. EDUCATION
Program:
Compiler:A Aset of instructions
compiler is called
is a computer program.
program that transforms source code written in
Program:
Compiler: A
A set of instructions
compiler is a is called
computer
a programming language into object code. program.
program that transforms source code written in
34
Compiler: A compiler is a computer
a programming language into object code. program that transforms source code written in
Compiler: A compiler
a programming languageisinto
a computer program that transforms source code written in
object code.
a programming language into object code.
55
.C character Set:
Enter stop
.C character Set: time:
.Ccharacter Set: Alphabets A,B,C…..Z
.Ccharacter Set: Alphabets A,B,C…..Z
a,b,c,…….z
Enter hours, minutes and seconds respectively:8
Alphabets
Digits A,B,C…..Z
a,b,c,…….z
0,1,2,3,4,5,6,7,8,9
Alphabets
Digits
Special symbols A,B,C…..Z
a,b,c,…….z
~‘!@# %^&*()_-+=|\{
0,1,2,3,4,5,6,7,8,9
Digits a,b,c,…….z
} [‘ ]! :@; #" ' %
0,1,2,3,4,5,6,7,8,9
12 Special symbols
Digits
Special symbols
~
~ ‘
< >^ ,&. ?* /( ) _ - + = | \ {
0,1,2,3,4,5,6,7,8,9
} [ ] : ; " ' < >^ ,&. ?* /( ) _ - + = | \ {
! @ # %
Special symbols } [‘ ]! :@; #" ' %
~ < >^ ,&. ?* /( ) _ - + = | \ {
15 } [not
Constants: constant is a value which can ] : be
; "changed
' < > , . ?during
/ execution.
Constants: constant is a value which can not be changed during execution.
Constants: constant is a value which can not be changed during execution.
Constants: constant is a value which can not be changed during execution.
Types of constants:
Types of constants:
TIME DIFFERENCE: 12:34:55 - 8:12:15 =
Types of constants:
There are two types of constants
Types
4:22:40of constants:
There are two types of constants
There are two types
1. Primary of constants
constants.
There
1. are two
2. Primary types
Secondary of constants
constants.
constants.
1.
2. Primary
Secondaryconstants.
constants.
1. Primary
2. Secondary constants.
constants.
2. Secondary constants.

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

[Type text] Page 128


IT WISDOM COMPUTER EDUCATION

UNIONS

Unions are quite similar to the structures in C.


Union is also a derived type as structure. Union
can be defined in same manner as structures just
the keyword used in defining union
in union where keyword used in defining
structure was struct.
union car
{
char name[50];
int price;
};
 Union variables can be created in similar
manner as structure variable.

 There is difference in memory allocation


between union and structur

[Type text] Page 129


IT WISDOM COMPUTER EDUCATION

 The amount of memory required to store a


structure variables is the sum of memory size
of all members.
 But, the memory required to store a union
variable is the memory required for largest
element of an union.

 All members of structure can be accessed at


any time. But, only one member of union can
be accessed at a time in case of union and
other members will contain garbage value.

[Type text] Page 130


IT WISDOM COMPUTER EDUCATION

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

Working with file


While working with file, you need to declare a
pointer of type file. This declaration is needed
for communication between file and program.
FILE *ptr;
File handling functions
fopen():-creates a new file or opens an existing file
from the disk.

[Type text] Page 131


IT WISDOM COMPUTER EDUCATION

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.

[Type text] Page 132


IT WISDOM COMPUTER EDUCATION

fread(): Reads data from a stream


size_t fread(void *ptr, size_t size, size_t n, FILE
*fp);
Reads n items of size bytes each. Returns the
number of items (not bytes) actually read.
feof(end of file character):-this function checks
whether a file pointer has been reached the end of
the file character or not. It returns a –1 when the
file comes to an end otherwise it returns a 0(zero).
int feof(FILE *fp)
fgetc() : Gets character from a stream
Syntax
int fgetc(FILE *fp);
fputc() : Outputs a character to a stream
int fputc(int c, FILE *fp);
Rewind(): repositions a file pointer to the beginning
of a stream.
Syntax
void rewind(FILE *fp);

[Type text] Page 133


IT WISDOM COMPUTER EDUCATION

Filemode Meaning of During


Mode Inexistence of file
r Open for If the file does
reading not exist, fopen()
returns NULL.
w Open for If the file exists,
writing. its contents are
overwritten. If
the file does not
exist, it will be
created.
a Open for If the file does
append. i.e, not exists, it will
Data is be created.
added to end
of file.
r+ Open for If the file does
both reading not exist, fopen()
and writing. returns NULL.
w+ Open for If the file exists,
both reading its contents are
and writing overwritten. If
the file does not
exist, it will be
created.
a+ Open for If the file does
both reading not exists, it will
and writing be created.

[Type text] Page 134


IT WISDOM COMPUTER EDUCATION

/*example program for writing to a file*/

#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;
}

[Type text] Page 135


IT WISDOM COMPUTER EDUCATION

/*program to read from a file*/

#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;
}

[Type text] Page 136


IT WISDOM COMPUTER EDUCATION

/* program to enter a string into the file*/


#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
fptr=fopen("program.txt","w");
f(fptr==NULL)
{
printf("Error!");
exit(1);
} printf("Enter a sentence:\n");
gets(c);
fprintf(fptr,"%s",c);
fclose(fptr);
return 0;
}

[Type text] Page 137


IT WISDOM COMPUTER EDUCATION

/*program to store student name, number and


marks in three subjects
in student.txt file*/
#include <stdio.h>
main( )
{
char sna[20];
int sno,m1,m2,m3;
char ch;
FILE *p;
p=fopen("student.txt","w");
if(p= =NULL)
{
printf("unable to write");
exit(0);
}
do
{
printf("enter student name");

[Type text] Page 138


IT WISDOM COMPUTER EDUCATION

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];

[Type text] Page 139


IT WISDOM COMPUTER EDUCATION

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);

[Type text] Page 140


IT WISDOM COMPUTER EDUCATION

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);

[Type text] Page 142


IT WISDOM COMPUTER EDUCATION

printf("no of words %d\n",nw);


printf("no of char %d\n",nc);
getch();
}

Binary Files
Depending upon the way file is opened for
processing, a file is classified into text file and
binary file.

If a large amount of numerical data it to be


stored, text mode will be insufficient. In such case
binary file is used.

Working of binary files is similar to text files with


few differences in opening modes, reading from
file and writing to file.

Opening modes of binary files


Opening modes of binary files
are rb, rb+, wb, wb+,ab and ab+. The only
difference between opening modes of text and
binary files is that, b is appended to indicate that,
it is binary file.

[Type text] Page 143


IT WISDOM COMPUTER EDUCATION

Reading and writing of a binary file.


Functions fread() and fwrite() are used for
reading from and writing to a file on the disk
respectively in case of binary files.

Function fwrite() takes four arguments, address


of data to be written in disk, size of data to be
written in disk, number of such type of data and
pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,po
inter_to_file);
Function fread() also take 4 arguments similar
to fwrite() function as above.

[Type text] Page 144


IT WISDOM COMPUTER EDUCATION

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

(b) File inclusion

(c) Conditional Compilation


(d) Miscellaneous directives

Macro expansion:

Ex:
#define VALUE 10

main()

[Type text] Page 145


IT WISDOM COMPUTER EDUCATION

int i;

for(i=0;i<=VALUE;i++)
{
printf(“%d\n”,i);
}
getch();
}

The statement #define VALUE 10 is called ‘macro


definittion’ or ‘macro’.
During preprocessing, the preprocessor replaces
every occurrence of VALUE in the program with
10.

VALUE is called macro template.

10 is called macro excpansion.

NOTE:

1. macro template and its macro expansion


are separated by blanks or tabs.
2. A space between # and define is optional.
3. macro definition is never to be
terminated by a semicolon.

[Type text] Page 146


IT WISDOM COMPUTER EDUCATION

EX2:.

#define PI
3.1415 main( )
{
float r = 6.25 ;
float area ;
area = PI * r * r ;
printf ( "\nArea of circle = %f", area ) ;
}

We can also use operators as macro expansions.

#define AND &&


#define X printf(“number is between 0 and 10”);
main()
{
int a=5;

if(a>0ANDa<10)
X;
}

Macros with arguments:

macros can have arguments like function.

#define SQUARE(X) ( x * x )
main( )
{
int n1 = 6, n2 = 2, s ;

[Type text] Page 147


IT WISDOM COMPUTER EDUCATION

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

#include "filename" : This command would


look for the file in the current directory
as well as the specified list of directories
as mentioned in the include search path.
#include <filename>: This command would
look for the file in the specified list of
directories only.

Conditional Compilation :

#ifdef and #endif directives


Syntax:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif

[Type text] Page 148


IT WISDOM COMPUTER EDUCATION

If macroname has been #defined, the block of


code will be processed as usual otherwise not.

Miscellaneous Directives

#undef directive

The #undef directive undefines a constant or


preprocessor macro defined previously
using #define.
#undef token
For example:
#define E 2.71828
int e_squared = E * E;
#undef E

#pragma Directive

#pragma startup and #pragma exit:


These directives allow us to specify
functions that are called upon
program startup (before main( )) or

[Type text] Page 149


IT WISDOM COMPUTER EDUCATION

program exit (just before the


program terminates). Their usage is
as follows:
void one( ) ;
void two( ) ;
#pragma startup one
#pragma exit two
main( )
{
printf ( "\n main function" ) ;
}
void one ( )
{
printf ( "\nfirst function" ) ;
}
void two( )
{
printf ( "\n second function" ) ;
}

Output:
First function
Main function
Second function

[Type text] Page 150

You might also like