C Notes
C Notes
C Notes
1.1 Algorithm
Oval Terminal
Input/
Parallelogram
output
Document Printout
Rectangle Process
Diamond Decision
Circle Connector
Arrow Flow
Double sided Predefined
Rectangle Process
data
Limitations of flowcharts
1. Flowcharts are difficult to modify. Re-drawing of flowchart
may be necessary
2. Translation of flowchart into computer program is always not
easy
Advantages of flowcharts
1. Logic of program is clearly represented
2. It is easy to follow logically the flow chart
Start
Read N
Count = 0
Sum = 0
Avg = 0
Sum = Sum +
a
Count =
Count+1
Count<
=n
?
True
False
1.3 Introduction
C is a programming language developed at AT & T Bell
Laboratories of USA in 1972. It was designed and written by “Dennis
Ritchie”. C is a powerful general purpose and most popular computer
programming language. C is highly portable i.e., software written for
one computer can be run on another computer. C language is well
suited for structured programming. An important feature of „C‟ is its
ability to extend itself. A C program is basically a collection of
functions.
Historical Development of C
Developed
Year Language Remarks
by
special
International Too general,
ALGOL
characters/symbols. The Committee too abstract
character set is given
below.
Alphabets A, B, C,
…………Z 1960
Hard to learn,
Cambridge
1963 CPL difficult to
University
implement
Martin Could deal
Richards at with only
1967 BCPL
Cambridge specific
University problems
Could deal
Ken Thomson with only
1970 B at AT & T specific
problems
Lost
Dennis Ritchie generality of
1972 C
at AT & T BCPL and B
restored
1.5 C Tokens
A token is an atomic unit (smallest indivisible units) in a
program.
The most basic elements in a C program recognized by the
compiler are a single character or a group of characters called C
tokens.
The compiler cannot breakdown the token any further. For
example, the words main, „{„ (brace), „(„ (parenthesis) are all tokens of
C program.
C language has 6 types of tokens.
1. Keywords
Examples: float, int, double, while, for
2. Identifiers
Examples: main, amount
3. Constants
Examples: 12.4, 7894
4. Strings
Examples: “CSM”, “Thursday”
5. Special Symbols
Examples: [,], {, }, (, )
6. Operators
Examples: +, *, /
Steps in learning C language are …
1. Character Set – Alphabets, Digits and Special Symbols
2. Datatypes, Constants, Variables and Keywords
3. Instructions
4. Functions, Program
In C, the alphabet is a set of characters. The words correspond
to constants,
variables, keywords, etc. These are classified into different
datatypes. Further, these are combined with operators to form
expressions, of various types. These are in turn combined to form
instructions. Combining a group of instructions into functions makes a
program.
1.6 The C character set
The C character set includes the upper case letters A to Z, the
lower case a to z, the decimal digits 0 to 9 and certain
a, b, c, ……………z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special characters/Symbols ~ , . ; : ? „ “ ! ( ) [ ] { } / \ < > = +
-$#@&*%^
Escape sequence
Some non-printing characters and some other characters such as
double quote (“), single quote („), question mark (?) and backslash (\),
require an escape sequence. A list of commonly used backslash
character constants is given below.
Escape Sequence Meaning ASCII value Escape Sequence Meaning ASCII value
\a Bell 7 \r Carriage return 13
\b Back Space 8 \” Double Quote 34
\t Tab 9 \‟ Single Quote 39
\n New line 10 \? Question Mark 63
\v Vertical tab 11 \\ Back Slash 92
\f Form feed 12 \0 Null 0
Variables
A variable can be considered as a name given to the location in
memory. The term variable is used to denote any value that is
referred to a name instead of explicit value. A variable is able to hold
different values during execution of a program, where as a constant is
restricted to just one value.
For example, in the equation 2x + 3y = 10; since x and y can
change, they are variables, whereas 2,3 and 10 cannot change,
hence they are constants. The total equation is known as
expression.
Rules for constructing variable names
(a) The name of a variable is composed of one to several
characters, the first of which must be a letter
(b) No special characters other than letters, digits, and
underscore can be used in
variable name. Some compilers permit underscore as the first
character.
(c) Commas or Blanks are not allowed with in a variable name.
(d) Upper case and Lower case letters are significant. That is
the variable income is
not same as INCOME.
(e) The variable name should not be a C key word. Also it
should not have the same
name as a function that is written either by user or already exist
in the C library.
The following are valid variable names:
Alpha
income
x
fyear_9899
matrix
1.11 C Instructions
There are basically four types of instructions in C:
(a) Type Declaration Instruction
(b) Input/Output Instruction
(c) Arithmetic Instruction
(d) Control Instruction
The purpose of each these instructions is
(a) Type Declaration instruction - to declare the type of
variables used in a C
program
(b) Input/Output instruction - to perform the function of
supplying input
data to a program and obtaining
the output
results from it.
(c) Arithmetic instruction - to perform arithmetic
operations between
constants and variables.
(d) Control instruction - to control the sequence of
execution of
various statements in a C program.
Type Declaration Instruction
This instruction is used to declare the type of variables being
used in the program. Any variable used in the program must be
declared before using it in any statement. The type declaration
statement is usually written ate the beginning of the C program.
Ex: int bas;
float rs, grosssal;
char name,code;
Arithmetic Instruction
A C arithmetic instruction consists of a variable name on the left
hand side of = and variable names & constants on the right hand side
of the =. The variables and constants appearing on the right hand
side of = are connected by arithmetic operators like +, -, *, and /.
Assigning Values
The values can be assigned to variables using assignment
statements.
The general format of assignment statement is…
Variable-name = expression;
where expression may be as simple as a constant or as complex
as an expression.
The operator = is called assignment operator. The left of
assignment operator must be a variable. It should not be a function or
a constant.
Bitwise operators
C supports a set of bitwise operations. The lowest logical
element in the memory is bit. C allows the programmer to interact
directly with the hardware of a particular system through bitwise
operators and expression. These operators work only with int and
char datatypes and cannot be used with float and double type.
The following table shows the bitwise operators that are
available in C.
Operator Meaning
- One‟s Complement
| Bitwise OR
& Bitwise AND
^ Bitwise Exclusive OR (XOR)
>> Right Shift
<< Left Shift
Increment & Decrement operators
C has two very useful operators for adding and subtracting a
variable. These are the increment and decrement operators, ++
and --
These two operators are unary operators. The increment
operator ++ adds 1 to its operand, and the decrement operator --
subtracts 1 from its operand. Therefore, the following are equivalent
operations.
++i; is equivalent to i = i + 1;
--i; is equivalent to i = i – 1;
These operators are very useful in loops.
Assignment operators
In addition to usual assignment operator =, C has a set of shorthand
operators, that simplifies the coding of a certain type of assignment
statement. It is of the form
var op = exp
where var is a variable, op is a C binary arithmetic operator
and exp is an expression.
The operator += means add the expression on the right to the
variable on the left and the operator -= means subtract the expression
on the right from the variable on the left.
Compile Source
C Compiler
Program
Synta x
Errors?
Logic and
Data
1.18 scanf( ) Function: getting user input
The real power of a technical C program is its ability to interact
with the program
user. This means that the program gets input values for variables
from users.
The scanf( ) function is a built-in C function that allows a
program to get user
input from the keyboard. The structure of this function is
scanf(format string &list of arguments);
Examples
scanf(“%d”, &a );
scanf(“%d %c %f ”,&a, &b, &c );
PROG RAMS
Prog.1: To print a message on the screen.
/* Printing a message on the screen */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“This is my First Program in C ”);
getch();
}
Output
This is my First Program in C
Prog.2: To print our Institute Name.
/* Printing our institute name */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Welcome to Millennium Software Solutions”);
getch();
}
Output
Welcome to Millennium Software Solutions
Prog.3: To Display Multiple Statements.
/* Printing our Institute Address*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Millennium Software Solutions”);
printf(“\n Visakhapatnam”);
getch();
}
Output
Millennium Software Solutions
Visakhapatnam
Prog.4: To Display a value of single variable
/*Initialization of a variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a; /* Declaration */
clrscr();
a = 10; /* Initialization */
printf(“The value is:%d”,a);
getch();
}
Output
The value is:10
Prog.5: To Display values of two variables.
/*Declaration and Initialization of a variables*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
printf(“%d is a value,%d is b value”,a,b);
getch();
}
Output
10 is a value,20 is b value
Prog.6: To calculate the sum of two numbers.
/* Sum of two numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
printf(“Sum of two numbers is:%d”,a+b);
getch();
}
Output
Sum of two numbers is:30
-x-
2. CONTROL STRUCTURES
2.1 Introduction: A C statement consists of keywords, expressions
and other statements. There are two types of statements in C. These
are single statements and compound statements. A compound
statement is a series of statements enclosed with in braces ({}) while
a single statement ends with a semicolon (;).
The control flow statements of a language determine the order in
which the statements are executed.
We also need to be able to specify that a statement, or a group
of statements, is to be carried out conditionally, only if some condition
is true. Also we need to be able to carry out a statement or a group of
statements repeatedly based on certain conditions. These kinds of
situations are described in C using Conditional Control and Loop
Control structures.
A conditional structure can be implemented in C using
(a) The if statement
(b) The if-else statement
(c) The nested if-else statement
(d) The switch statement.
whereas loop control structures can be implemented in C using
(a) while loop
(b) do-while loop
(c) for statement
/* Even or Odd */
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;
clrscr( );
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n%2==0)
printf(“It is Even number”);
if(n%2!=0)
printf(“It is Odd number”);
getch( );
}
Output 1
Enter a number:4
It is Even number
Output 2
Enter a number:5
It is Odd number
Note that there is no semicolon between the condition and the
statement i.e., no semicolon following if(n%2==0).
It is important to note that, if the condition is false the
statement is skipped and control goes to the next statement
immediately after if statement.
PROG RAMS
If statement
Prog.27: To check whether the year is leap or not
/* Inputting year is Leap or not */
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf(“Enter year:”);
scanf(“%d”,&year);
if(year%4==0)
printf(“Leap year”);
if(year%4!=0)
printf(“Not leap year”);
getch();
}
Output 1
Enter year:1990
Not leap year
Output 2
Enter year:1996
Leap year
Prog.28: To find the biggest number in two variables
/* Biggest number in two variables */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values:”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“a is big”);
if(a<b)
printf(“b is big”);
getch();
}
Output 1
Enter a,b values:3 4
b is big
Output 2
Enter a,b values:4 2
a is big
Prog.29: To check the enter number is single digit or not
/* Single digit or not */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n<=9)
printf(“Single digit”);
if(n>9)
printf(“Not single digit”);
getch();
}
Output 1
Enter a number:5
Single digit
Output 2
Enter a number:12
Not single digit
Prog.30: To check the number is positive, negative or zero.
/* To check whether +ve, -ve or zero */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n>0)
printf(“+ve”);
if(n<0)
printf(“-ve”);
if(n==0)
printf(“zero”);
getch();
}
Output 1
Enter a number: -2
-ve
Output 2
Enter a number:0
zero
Output 3
Enter a number:5
+ve
Switch statement
Prog.42: To check whether the letter is vowel or consonant
/* Vowel or Consonant */
#include<stdio.h>
#include<conio.h>
void main()
{
char x;
clrscr();
printf(“Enter a char:”);
scanf(“%c”,&x);
switch(x)
{
case „a‟:
case „A‟:
case „e‟:
case „E‟:
case „i‟:
case „I‟:
case „o‟:
case „O‟:
case „u‟:
case „U‟:printf(“Vowel”);
break;
default:printf(“Consonant”);
}
getch();
}
Output 1
Enter a char:a
Vowel
Output 2
Enter a char:b
Consonant
Output 3
Enter a char:U
Vowel
Prog.43: To print words corresponding numbers below 9
/* Numbers -> words (0-9)*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number(0-9):”);
scanf(“%d”,&n);
switch(n)
{
case 0:printf(“Zero”);
break;
case 1:printf(“One”);
break;
case 2:printf(“Two”);
break;
case 3:printf(“Three”);
break;
case 4:printf(“Four”);
break;
case 5:printf(“Five”);
break;
case 6:printf(“Six”);
break;
case 7:printf(“Seven”);
break;
case 8:printf(“Eight”);
break;
case 9:printf(“Nine”);
break;
default:printf(“More than 9”);
}
getch();
}
Output 1
Enter a number(0-9):3
Three
Output 2
Enter a number(0-9):12
More than 9
Prog.44:To print Day corresponding Number
/* Number corresponding Day */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
switch(n)
{
case 1:printf(“Sunday”);
break;
case 2:printf(“Monday”);
break;
case 3:printf(“Tuesday”)
break;
case 4:printf(“Wednesday”);
break;
case 5:printf(“Thursday”);
break;
case 6:printf(“Friday”);
break;
case 7:printf(“Saturday”);
break;
default:printf(“No week day”);
}
getch();
}
Output 1
Enter a number:3
Tuesday
Output 2
Enter a number:9
No week day
Prog.45: To print color name corresponding letter
/* Letter -> color name */
#include<stdio.h>
#include<conio.h>
void main()
{
char x;
clrscr();
printf(“Enter a char:”);
scanf(“%c”,&x);
switch(x)
{
case „w‟:printf(“w->white”);
break;
case „b‟:printf(“b->black”);
break;
case „l‟:printf(“l->blue”);
break;
case „y‟:printf(“y->yellow”);
break;
case „g‟:printf(“g->green”);
break;
case „r‟:printf(“r->red”);
break;
case „o‟:printf(“o->orange”);
break;
default:printf(“No color”);
}
getch();
}
Output 1
Enter a char:l
l->blue
Output 2
Enter a char:y
y->yellow
Output 3
Enter a char:c
No color
-x-
3. LOOPS
3.1 Def: A portion of program that is executed repeatedly is called a
loop.
The C programming language contains three different program
statements for program looping. They are
1. For loop
2. While loop
3. Do-While loop
PROG RAMS
The for loop
Prog.48: To print the message 10 times.
/* Print a message 10 times */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
printf(“\nMillennium Software Solutions”);
getch();
}
Output
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Prog.49: To print 1 to 10 numbers.
/* Print 1 to 10 numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
printf(“\n%d”,i);
getch();
}
Output
1
2
3
4
5
6
7
8
9
10
Pyramids
/* *
* *
* * *
* * * *
* * * * * */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“* ”);
}
printf(“\n”);
}
getch();
}
Output
*
* *
* * *
* * * *
* * * * *
Prog.66: To print the following format
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
/* 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
/* 1
2 2
3 3 3
4 4 4 4
5 5 5 5 5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,i);
}
printf(“\n”);
}
getch();
}
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Prog.68: To print the following format
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
/* 5 5 5 5 5
4 4 4 4
3 3 3
2 2
1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,i);
}
printf(“\n”);
}
getch();
}
Output
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
/* 1 2 3 4 5
1 2 3 4
1 2 3
1 2
1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Prog.70: To print the following format
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
/* 1 1 1 1 1
2 2 2 2
3 3 3
4 4
5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,i);
}
printf(“\n”);
}
getch();
}
Output
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
Prog.71: To print the following format
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
/* 5 4 3 2 1
5 4 3 2
5 4 3
5 4
5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
/* 5
5 4
5 4 3
5 4 3 2
5 4 3 2 1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Prog.73: To print the following format
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
/* 5
4 4
3 3 3
2 2 2 2
1 1 1 1 1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,i);
}
printf(“\n”);
}
getch();
}
Output
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
While Loop
Prog.74 : To print the message 10 times.
/* Print a message 10 times */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf(“\nMillennium Software Solutions”);
i++;
}
getch();
}
Output
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Prog.75: To print 1 to 10 numbers.
/* Print 1 to 10 numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf(“\n%d”,i);
i++;
}
getch();
}
Output
1
2
3
4
5
6
7
8
9
10
Prog.76: To print 1 to 10 even numbers.
/* Print even numbers below 10 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=2;
clrscr();
while(i<=10)
{
printf(“\n%d”,i);
i + =2;
}
getch();
}
Output
2
4
6
8
10
do-while Loop:
Note: Do all above programs using do-while loop syntax .
Syn: initialization;
do
{
statements;
incre / decre;
}while(condition);
-x-
4. ARRAYS
4.1 Def: An Array is a collection of same data type. The
elements of an array are referred by a common name and are
differentiate from one another by their position with in an array. The
elements of an array can be of any data type but all elements in an
array must be of the same type.
The general form of declaring a array is
type array_name[size];
where type is a valid datatype, array_name is the name of the array
and size is the number of elements that array_name contains.
Example:
int A[100],marks[20];
float rates[50];
char name[30];
int A[100];
here int data type of elements that an array
A name of array
100 size of an array
6.6 Variables and Storage Classes: There are three basic places
in a C program where variables will be declared: inside the function, in
the definition of function parameters, or outside of all functions. These
variables are called local variables, formal parameters, and global
variables respectively.
Local Variables: The body of any function comprises of two parts:
declaration of variables and a set of executable statements. Variables
declared inside a function are called local variables. This name derives
from the fact that a variable inside a function can be used only inside
that function. An attempt on our part or access the local variable of
one function in another, will draw an error from the compiler:
Identifier undefined.
Global Variables: C program consists of three sections namely: the
preprocessor directives, the global variable section and fi nally the
functions. The variables that are declared in the global variable
section are called global variables. While a local variable can be used
only inside a function in which it is declared, a global variable can be
used anywhere in the program.
Block Variables: Yet another place to declare variables is inside any
block: these variables are called block variables and these can be used
only inside that block.
Global Vs Local Variables:
There are a number of differences between global variables and
local variables.
1. Local variables can be used only inside the function or the block
in which they are declared. On the other hand, global variables
can be used throughout the program.
2. The rules of initialization differ. All global variables, in the
absence of explicit initialization, are automatically initialized. A
global int variable begins with the value 0, a global float gets
initialized to 0.0, a global char holds the ASCII null byte, and a
global pointer points to NULL. As against this, local variables do
not get initialized to any specified value, when a value is not
provided. Thus a local variable begins with an unknown value,
which may be different each time.
3. Global variables get initialized only once, before the program
starts executing. But, local variables get initialized each time
the function or block containing their declaration is entered.
4. The initial value that you supply for a global variable must be a
constant, whereas a local variable can contain variables in its
initializer.
5. A local variable loses its value, the moment the function/block
containing it is exited. Global variables retain their values
throughout their execution.
Storage classes:
The storage class of a variable dictates how, when and where
storage will be allocated for the variable. The different storage classes
available are:
1. Auto 2. Register 3. Extern 4. Static
1. Auto: Automatic variables are declared inside a function in
which they are to be utilized. They are created when the function
is called and destroyed automatically when the function is
exited, hence the name automatic. Automatic variables are
therefore private (or local) to the function in which they are
declared. Because of this property, automatic variables are also
refereed to as local or internal variables.
A variable declared inside a function without storage class
specification is, by default, an automatic variable.
One important feature of automatic variables is that their value
cannot be changed accidentally by what happens in some other
function in the program. This assures that we may declare and use
the same variable name in different functions in the same program
without causing any confusion to the compiler.
Program: ILLUSTRATION OF WORKING OF auto VARIABLES
#include<stdio.h>
#include<conio.h>
void function1();
void function2();
void main()
{
int m = 1000;
clrscr();
function2();
printf(“%d\n”,m);
getch();
}
void function1()
{
int m = 10;
printf(“%d\n”,m);
}
void function2()
{
int m = 100;
function1();
printf(“%d\n”,m);
}
2. Register: It is possible for use to attribute the register storage
class to certain variables. We can tell the compiler that a
variable should be kept in one of the machine‟s registers, instead
of keeping in the memory (where normal variables are stored).
Since a register access is much faster than a memory access,
keeping the frequently accessed variables in the register will lead
to faster execution of programs. This is done as follows:
register int count;
The important point while using register variables is, registers of
CPU do not have addresses. Thus, we should not refer the address of
a register variable.
For example,
The following statement will result an error.
register int i;
scanf(“%d”,&i);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register int count;
int sum;
clrscr();
for(count=0;count<10;count++)
sum = sum + count;
printf(“The sum is:%d”,sum);
getch();
}
3. Extern: This is the default storage class for all global variables.
Extern storage class variables get initialized (to zero in the case
of integers) automatically, retain their value throughout the
execution of the program and can be shared by different
modules of the same program. However, assuming “int
intvar;”is present in a.c., to be also to have proper binding with
the same variable, b.c (another file) should have “extern int
intvar”.
Example:
a.c file b.c file
#include<stdio.h> float f = 84.237;
#include<conio.h> extern int intvar;
int intvar; funct(char c, int intvar)
extern float f; {
void main() char c1,c2;
{ :
char ch; :
funct(ch,intvar); }
printf(“%f”,f);
getch();
}
If we intend to share a variable say f, between a.c and b.c files, f
must be declared in both files. Note that it is qualified as extern in
a.c file. The extern qualifier indicated the compiler that f is a variable
of type float for which no memory needs to be allocated and it will be
allocated elsewhere. Note that if a variable is declared as extern, it
must appear as global variable once in another source file.
4. Static: The static storage class has a number of implications
depending upon its usage.
(a) The default storage class for all local variables is auto.
This can be changed to static by prefixing the declaration with
the keyword static as in static int intvar. A local variable with
static storage class is still a local variable as far as its scope is
concerned, it is still available only inside the function in which it
is declared. But certain other properties of the variable change;
It gets initialized to zero automatically, is initialized only once,
(during program startup) and it retains its value throughout the
execution of the program.
(b) When applied to a global variable, the global variable
becomes inaccessible outside the file in which it is declared.
(c) This storage class can be applied to functions too. Similar to
case 2, the functions become inaccessible outside the file.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
function1( );
function1( );
function1( );
getch();
}
void function1()
{
static int n;
n++;
printf(“\nThe value of n is:%d”,n);
}
The output of above program is
The value of n is 1
The value of n is 2
The value of n is 3
Note that the static variable is initialized to zero automatically.
Test the above program without the keyword static to understand the
static storage class clearly.
Storage Type Default initial Scope Life Storage
class value Where
declared
Auto An unpredictable within the only within the until function block Memory
or Local value, which is function or function / block is no longer active
none often called a block where it is
garbage value declared
Register Local Garbage value within the only within the until function block CPU
function or function / block is no longer active registers
block where it is
declared
Static Local Zero within the only within the until program ends, Memory
function or function / block value of the variable
block where it is persists between
declared different function
calls
Extern Global Zero A heat of all All files While any of these Memory
functions including other files are active.
within a file files where That is, as long as
declared the program‟s
extern execution doesn‟t
come to an end
-x -
7. Structures and Unions
7.1 INTRODUCTION
We seen that arrays can be used to represent a group of data items
that belong to the same type, such as int or float. However, if we
want to represent a collection of data items of different types using a
single name, then we cannot use an array. Fortunately, C supports a
constructed data type known as structure, which is a method for
packing data of different types. A structure is a convenient tool
for handling a group of logically related data items. These fields
are called structure elements or members.
7.2 Declaring A Structure
The general form of a structure declaration statement is given below:
struct <structure name>
{
structure element1;
structure element2;
structure element3;
……….
……….
}
Example:
struct book
{
char name[20];
char author[15];
int pages;
float price;
}
Note that the above declaration has not declared any variables.
It simply describes a format called template to represent information.
We can declare structure variables using the tag name anywhere
in the program. For example, the statement
struct book book1, book2,book3;
declares book1, book2, book3 as variables of type struct book.
It is also allowed to combine both the template declaration and
variables declaration in one statement. The declaration
struct book
{
char name[20];
char author[15];
int pages;
float price;
}book1,book2,book3;
is valid. The use of tag name is optional. For example,
struct
{
char name[20];
char author[15];
int pages;
float price;
}book1,book2,book3;
declares book1, book2, book3 as structure variables representing
three books, but does not include a tag name for later use in
declarations.
Note the following points while declaring a structure type:
(a) The closing brace in the structure type declaration must be
followed by a semicolon.
(b) It is important to understand that a structure type
declaration does not tell the compiler to reserve any space in
memory. All a structure declaration does is, it defines the „form‟
of the structure.
(c) Usually structure type declaration appears at the top of the
source code file, before any variables or functions are defined.
7.3 ACCESSING STRUCTURES ELEMENTS
We can assign values to the members of a structure in a number of
ways. As mentioned earlier, the members themselves are not
variables. They should be linked to the structure variables in order to
make them meaningful members. The link between a member and a
variable is established using the member operator „.‟ Which is also
known as „dot operator‟ or „period operator‟. The general form is
Structure-Variable. Structure-Member;
For example,
book1.price;
We can also use scanf to give the values through the keyboard.
scanf(“%s”,book1.name);
scanf(“%d”,&book1.pages);
are valid input statements.
Example:
Program: Defining and Assigning Values to Structure Members
#include<stdio.h>
#include<conio.h>
struct personal
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
void main()
{
struct personal person;
clrscr();
printf(“Input values\n”);
scanf(“%s%d%s%d%f”,person.name, &person.day, person.month,
&person.year, &person.salary);
printf(“%s %d %s %d,%.2f\n”,person.name,person.day,
person.month,person.month,person.year,person.salary);
getch();
}
Output
Input Values
Mahesh 15 February 1982 5000
Mahesh 15 February 1982 5000.00
Example:
Program: STRUCTURE AS FUNCTION PARAMETERS
#include<stdio.h>
#include<conio.h>
struct stores
{
char name[20];
float price;
int quantity;
};
struct stores update(struct stores,float,int);
float mul(struct stores);
void main()
{
float p_increment, value;
int q_increment;
static struct stores item={“XYZ”,25.75,12};
clrscr();
printf(“\nInput increment values:”) ;
printf(“price increment and quantity increment\n”);
scanf(“%f%d”,&p_increment,&q_increment);
item = update(item,p_increment,q_increment);
printf(“\nUpdate values of item”);
printf(“\n\nName:%s”,item.name);
printf(“\nPrice:%.2f”,item.price);
printf(“\nQuantity:%d”,item.quantity);
value = mul(item);
printf(“\nValue of the item=%.2f”,value);
getch();
}
struct stores update(struct stores product, float p, int q)
{
product.price+=p;
product.quantity+=q;
return(product);
}
float mul(struct stores stock)
{
return stock.price*stock.quantity;
}
7.8 UNIONS
Unions are a concept borrowed from structures and therefore follow
the same syntax as structures. However, there is major distinction
between them in terms of storage. In structures, each member has its
own storage location, whereas all the members of a union use the
same location. This implies that, although a union may contain many
members of different types, it can handle only one member at a time.
Like structures, a union can be declared using the keyword union as
follows:
union item
{
int m;
float x;
char c;
}code;
-x-
8. Pointers
8.1 INTRODUCTION Pointers are another important feature of C
language. They are a powerful tool and handy to use once they are
mastered. There are a number of reasons for using pointers.
1. A pointer enables us to access a variable that is defined outside
the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving
of data storage space in memory.
8.2 ACCESSING THE ADDRESS OF A VARIABLE
The actual location of a variable in the memory is system dependent
and therefore, the address of a variable is not known to us
immediately. We can determine the address of the variable with the
help of the operator & in C. We have already seen the use of this
address operator in the scanf function. The operator & immediately
preceding a variable returns the address of the variable associated
with it. For example,
p = &quantity;
would assign the address to the variable p. The & operator can be
remembered as „address of‟.
Example: Accessing Addresses of variables
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
int x;
float p, q;
clrscr();
a = „A‟;
x = 125;
p = 10.25, q = 18.76;
printf(“%c is stored at address %u”, a, &a);
printf(“\n%d is stored at address %u”, x, &x);
printf(“\n%f is stored at address %u”, p, &p);
printf(“\n%f is stored at address %u”, q, &q);
getch();
}
This tells the compiler three things about the variable pt_name.
1. The asterisk (*) tells the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type datatype.
For example,
int *p;
declares the variable p as a pointer variable that points to an integer
data type. Remember that the type int refers to the data type of the
variable being pointed to by p and not the type of the value of the
pointer. Similarly, the statement
float *x;
declares x as a pointer to a floating point variable.
Once a pointer variable has been declared, it can be made to point to a
variable using an assignment statement such as
p = &quantity;
which causes p to point to quantity. That is, p now contains the
address of quantity. This is known as pointer initialization. Before a
pointer is initialized, it should not be used.
A pointer variable can be initialized in its declaration itself. For
example,
int x, *p=&x;
is perfectly valid. It declares x as an integer variable and p as a
pointer variable and then initializes p to the address of x. Note
carefully that this is an initialization of p, not *p. And also remember
that the target variable x is declared first. The statement
int *p=&x, x;
is not valid.
8.4 ACCESSING A VARIABLE THROUGH ITS POINTER
Once a pointer has been assigned the address of a variable, the
question remains as to how to access the value of the variable using
the pointer. This is done by using another unary operator * (asterisk),
usually known as the indirection operator. Consider the following
statements:
int quantity, *p, n;
quantity = 179;
p = &quantity;
n = *p;
The first line declares quantity and n as integer variables and p as a
pointer variable pointing to an integer. The second line assigns the
value 179 to quantity and the third line assigns the address of
quantity to the pointer variable p. The fourth line contains the
indirection operator *. When the operator * is placed before a pointer
variable in an expression, the pointer returns the value of the variable
of which the pointer value is the address. In this case, *p returns the
value of the variable quantity, because p is the address of quantity.
The * can be remembered as „value of address‟. Thus the value of n
would be 179.
Example: Program to illustrate the use of indirection operator
„*‟
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y;
int *ptr;
clrscr();
x = 10;
ptr = &x;
y = *ptr;
printf(“Value of x is %d”,x);
printf(“\n%d is stored at address %u”, x, &x);
printf(“\n%d is stored at address %u”, *&x , &x);
printf(“\n%d is stored at address %u”, *ptr, ptr);
printf(“\n%d is stored at address %u”, y, &*ptr);
printf(“\n%d is stored at address %u”, ptr, &ptr);
printf(“\n%d is stored at address %u”, y, &y);
getch();
}
9. File Management in C
9.1 INTRODUCTION
A file is a place on the disk where a group of related data is stored.
Like most other languages, C supports a number of functions that
have the ability to perform basic file operations, which include:
Naming a file,
Opening a file,
Reading data from a file,
Writing data to a file, and
Closing a file.
High level I/O functions
Function Name Operation
fopen() Creates a new file for use
Opens an existing file for use.
fclose() Closes a file which has been opened for use.
Getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to file.
fseek() Sets the position to a desired point in the file
Ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file.
printf("Contents of %s file\n\n",argv[1]);
fp=fopen(argv[1],"r");
for(i=2;i<argc;i++)
{
fscanf(fp,"%s",word);
printf("%s",word);
}
fclose(fp);
printf("\n\n");
for(i=0;i<argc;i++)
printf("%*s\n",i*5,argv[i]);
getch();
}