C Programming Material-3
C Programming Material-3
UNIT ‐ I
Introduction to Computing – Computer Systems-Hardware and Software,
Computer Languages, Algorithm, Flowchart, Representation of Algorithm and
Flowchart with examples.
UNIT‐II
Statements‐Selection statements (Decision Making)- if and switch statements
with examples, Repetition statements (loops)- while, for, do‐while statements
with examples, Unconditional statements- break, continue, goto statements
with examples.
UNIT – III
Functions‐Designing Structured Programs, Types of Functions-User defined
functions, Standard functions, Categories of functions, Parameter Passing
techniques, Storage classes, Recursion.
UNIT‐IV
Arrays- Declaration and Initialization, One dimensional Arrays, Two
dimensional Arrays.
UNIT-V
Pointers- Introduction, Definition and Declaration of pointers, address
operator, Pointer variables, Pointers with Arrays.
Computer
System
Hardware Software
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the
computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or
an audio input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations,comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on
the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard
copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer,
or programs and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between
the hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
Software
System Application
software software
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access
to the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category ,system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to
ensure that the programs are error free and computer –assisted software engineering(CASE)
systems.
Application software
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software. They can
be used only for the task for which they were designed they cannot be used for other
generalized tasks.
The relation ship between system and application software is shown in fig-2.In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system,the typical user uses some form of application software. The
application software in turn interacts with the operating system ,which is apart of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
Computer Languages:
To write a program for a computer, we must use a computer language. Over the years
computer languages have evolved from machine languages to natural languages.
Machine Languages
In the earliest days of computers, the only programming languages available were machine
languages. Each computer has its own machine language, which is made of streams of 0’s and
1’s.
Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits
of a computer are made of switches transistors and other electronic devices that can be in one
of two states: off or on. The off state is represented by 0 , the on state is represented by 1.
Symbolic Languages:
In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the
concept of a special computer program that would convert programs into machine language.
The early programming languages simply mirror to the machine languages using symbols of
mnemonics to represent the various machine language instructions because they used symbols,
these languages were known as symbolic languages.
Computer does not understand symbolic language it must be translated to the machine
language. A special program called assembler translates symbolic code into machine language.
Because symbolic languages had to be assembled into machine language they soon became
known as assembly languages.
Symbolic language uses symbols or mnemonics to represent the various ,machine language
instructions.
Symbolic languages greatly improved programming effificiency; they still required programmers
to concentrate on the hardware that they were using. Working with symbolic languages was
also very tedious because each machine instruction has to be individually coded. The desire to
improve programmer efficiency and to change the focus from the computer to the problem
being solved led to the development of high-level language.
High level languages are portable to many different computers, allowing the programmer to
concentrate on the application problem at hand rather than the intricacies of the computer.
High-level languages are designed to relieve the programmer from the details of the assembly
language. High level languages share one thing with symbolic languages, They must be
converted into machine language. The process of converting them is known as compilation.
The first widely used high-level languages, FORTRAN (FORmula TRANslation)was created by
John Backus and an IBM team in 1957;it is still widely used today in scientific and engineering
applications. After FORTRAN was COBOL(Common Business-Oriented Language). Admiral
Hopper was played a key role in the development of the COBOL Business language.
C is a high-level language used for system software and new application code.
ALGORITHM:
Step 1: Start
Step 2:Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.
FLOW CHART :
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm.
Flow charts are drawn using certain special purpose symbols such as Rectangles, Diamonds,
Ovals and small circles. These symbols are connected by arrows called flow lines.
(or)
The diagrammatic representation of way to solve the given problem is called flow chart.
The following are the most common symbols used in Drawing flowcharts:
For processing(input) or
recording of the process
information(output).
type of operations.
C is the programming language most frequently associated with UNIX. Since the 1970s, the bulk
of the UNIX operating system and its applications have been written in C. Because the C
language does not directly rely on any specific hardware architecture, UNIX was one of the first
portable operating systems. In other words, the majority of the code that makes up UNIX does
not know and does not care which computer it is actually running on. Machine-specific features
are isolated in a few modules within the UNIX kernel, which makes it easy for you to modify
them when you are porting to a different hardware architecture.
C was first designed by Dennis Ritchie for use with UNIX on DEC PDP-11 computers. The
language evolved from Martin Richard's BCPL, and one of its earlier forms was the B language,
which was written by Ken Thompson for the DEC PDP-7. The first book on C was The C
Programming Language by Brian Kernighan and Dennis Ritchie, published in 1978.
It appears that there will be yet another ANSI C standard officially dated 1999 or in the early
2000 years; it is currently known as "C9X."
1. Documentation section
2. Linking section
3. Definition section
Declaration section
Executable section
2. LINKING SECTION : This section tells the compiler to link the certain occurrences of keywords
or functions in your program to the header files specified in this section.
3. DEFINITION SECTION : It is used to declare some constants and assign them some value.
Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables which are used through out the
program (including main and other functions) are declared so as to make them global(i.e
accessible to all parts of program)
5. MAIN FUNCTION SECTION : It tells the compiler where to start the execution from
main()
1. declaration section : In this the variables and their data types are declared.
2. Executable section : This has the part of program which actually performs the task we
need.
6. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the functions
which our program needs.
SIMPLE ‘C’ PROGRAM:
/* simple program in c */
#include<stdio.h>
main()
printf(“welcome to c programming”);
} /* End of main */
C-TOKENS :
Tokens are individual words and punctuations marks in English language sentence. The
smallest individual units are known as C tokens.
OPERATORS
E.g. +, -, *
E.g. [ ], { }
SPECIAL SYMBOLS
E.g. “asifia”
STRINGS
C TOKENS
CONSTANTS
E.g. -15.4, ‘a’, 200
IDENTIFIERS
E.g. rate,no_of_hours
KEYWORDS :
There are certain words, called keywords (reserved words) that have a
predefined meaning in ‘C’ language. These keywords are only to be used for their intended
purpose and not as identifiers.
Volatile While
IDENTIFIERS :
Names of the variables and other program elements such as functions, array,etc,are
known as identifiers.
There are few rules that govern the way variable are named(identifiers).
1. Identifiers can be named from the combination of A-Z, a-z, 0-9, _(Underscore).
Eg: name,ptr,sum
where data type could be float, int, char or any of the data types.
id1, id2, id3 are the names of variable we use. In case of single variable no commas are
required.
eg float a, b, c;
char present_or_absent;
ASSIGNING VALUES :
When we name and declare variables we need to assign value to the variable. In some
cases we assign value to the variable directly like
a=10;
in our program.
In some cases we need to assign values to variable after the user has given input for
that.
#include<stdio.h>
main()
int a;
float b;
b=190.5;
scanf("%d",&a);
CONSTANTS :
A quantity that does not vary during the execution of a program is known as a constant
supports two types of constants namely Numeric constants and character constants.
NUMERIC CONSTANTS:
2. Long constant is written with a terminal ‘l’or ‘L’,for example 1234567899L is a Long
constant.
3. Unsigned constants are written with a terminal ‘u’ or ‘U’,and the suffix ‘ul’ and ‘UL’
CHARACTER CONSTANTS:
A character constant is written as one character with in single quotes such as ‘a’. The
value of a character constant is the numerical value of the character in the machines character
set. certain character constants can be represented by escape sequences like ‘\n’. These
sequences look like two characters but represent only one.
\a Alert
\b Backspace
\f Form feed
\n New Line
\r Carriage return
\t Horizontal Tab
\v Vertical Tab
To distinguish between a character constant and a string that contains a single character
ex: ‘a’ is not same as “a”. ‘a’ is an integer used to produce the numeric value of letter a in the
machine character set, while “a” is an array of characters containing one character and a ‘\0’ as
a string in C is an array of characters terminated by NULL.
There is one another kind of constant i.e Enumeration constant , it is a list of constant
integer values.
The first name in the enum has the value 0 and the next 1 and so on unless explicit
values are specified.
If not all values specified , unspecified values continue the progression from the last
specified value. For example
VARIABLES :
A quantity that can vary during the execution of a program is known as a variable. To
identify a quantity we name the variable for example if we are calculating a sum of two
numbers we will name the variable that will hold the value of sum of two numbers as 'sum'.
DATA TYPES :
To represent different types of data in C program we need different data types. A data type
is essential to identify the storage representation and the type of operations that can be
performed on that data. C supports four different classes of data types namely
All arithmetic operations such as Addition , subtraction etc are possible on basic data
types.
Char c;
The following table shows the Storage size and Range of basic data types:
Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.
Char name[20];
C Provides a facility called typedef for creating new data type names defined by the
user. For Example ,the declaration ,
makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts,etc,like,
Integer num1,num2;
Which will be treated by the C compiler as the declaration of num1,num2as int variables.
varname=getchar();
The simplest of output operator is putchar to output a single character on the output
device.
putchar(varname)
The getchar() is used only for one input and is not formatted. Formatted input refers to an input
data that has been arranged in a particular format, for that we have scanf.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
%f floats
%l long
%c character
#include<stdio.h>
main()
int a,b;
float c;
a=getchar();
putchar(a);
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
OPERATORS :
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
7. Bit wise operators
8. Special operators
operator meaning
+ add
- subtract
* multiplication
/ division
% modulo division(remainder)
An arithmetic operation involving only real operands(or integer operands) is called real
arithmetic(or integer arithmetic). If a combination of arithmetic and real is called mixed mode
arithmetic.
operator meaning
== is equal to
!= is not equal to
It is the form of
3. LOGICAL OPERATORS : An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The
operators and truth values are
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
op-1 !op-1
non-zero zero
zero non-zero
5. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a variable.
The assignment operator is '='.
v op=exp
v is variable
op binary operator
exp expression
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
++ and == are called increment and decrement operators used to add or subtract.
++m or m++
--m or m--
It work as
8. BIT WISE OPERATORS : C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
^ Bitwise exclusive OR
~ one's complement
9. SPECIAL OPERATORS : These operators which do not fit in any of the above classification are
,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->). The
comma operator is used to link related expressions together.
#include<stdio.h>
main()
int i,j;
float l, m;
scanf("%d%d",&i,&j);
scanf("%f%f",&l,&m);
sum=i+j;
mul=i*j;
modu=i%j;
sub=l-m;
divi=l/m;
#include<stdio.h>
main()
int i, j, k;
if((i<j)&&(j<k))
printf("k is largest");
printf("j is largest");
else
#include<stdio.h>
main()
int i;
printf("Enter a number");
scanf("%d", &i);
i++;
i--;
#include<stdio.h>
main()
int i,j,large;
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
}
UNIT - II
The if statement is a two way decision statement and is used in conjunction with an
expression. It takes the following form
If(test expression)
If the test expression is true then the statement block after if is executed otherwise it is not
executed
if (test expression)
statement block;
statement–x ;
/* program for if */
#include<stdio.h>
main()
int a,b;
if a>b
printf(“ a is greater”);
if b>a
printf(“b is greater”);
If your have another set of statement to be executed if condition is false then if-else is
used
if (test expression)
statement block1;
else
statement block2;
statement –x ;
#include<stdio.h>
main()
int a,b;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b):
if a>b
printf(“ a is greater”)
else
printf(“b is greater”);
if(text cond1)
if (test expression2
statement block1;
else
statement block 2;
else
statement block2;
}
statement-x ;
if else ladder
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
The nesting of if-else depends upon the conditions with which we have to deal.
If for suppose we have more than one valid choices to choose from then we can use
switch statement in place of if statements.
switch(expression)
{.
case value-1
block-1
break;
case value-2
block-2
break;
--------
--------
default:
default block;
break;
statement–x
In case of
if(cond1)
statement-1
if (cond2)
statement 2
}
/* program to implement switch */
#include<stdio.h>
main()
int marks,index;
char grade[10];
scanf(“%d”,&marks);
index=marks/10;
switch(index)
case 10 :
case 9:
case 8:
case 7:
case 6: grade=”first”;
break;
case 5 : grade=”second”;
break;
case 4 : grade=”third”;
break;
break;
}
printf(“%s”,grade);
LOOPING :
condition is met.
We have two types of looping structures. One in which condition is tested before
entering the statement block called entry control.
The other in which condition is checked at exit called exit controlled loop.
WHILE STATEMENT :
While(test condition)
It is an entry controlled loop. The condition is evaluated and if it is true then body of
loop is executed. After execution of body the condition is once again evaluated and if is true
body is executed once again. This goes on until test condition becomes false.
#include<stdio.h>
main()
int count,n;
float x,y;
y=1.0;
count=1;
while(count<=n)
y=y*x;
count++;
}
DO WHILE STATEMENT :
The while loop does not allow body to be executed if test condition is false. The do while
is an exit controlled loop and its body is executed at least once.
do
body
}while(test condition);
#include<stdio.h>
#define COL 10
#define ROW 12
main()
{
int row,col,y;
row=1;
do
col=1;
do
y=row*col;
printf(“%d”,y);
col=col+1;
}while(col<=COL);
printf(“\n”);
row=row+1;
}while(row<=ROW);
body of loop
}
/* program of for loop */
#include<stdio.h>
main()
long int p;
int n;
double q;
p=1;
for(n=0;n<21;++n)
if(n==0)
p=1;
else
p=p*2;
q=1.0/(double)p;
printf(“%101d%10d”,p,n);
UNCONDITIONAL STATEMENTS:
BREAK STATEMENT:
This is a simple statement. It only makes sense if it occurs in the body of a switch, do,
while or for statement. When it is executed the control of flow jumps to the statement
immediately following the body of the statement containing the break. Its use is widespread in
switch statements, where it is more or less essential to get the control .
The use of the break within loops is of dubious legitimacy. It has its moments, but is really
only justifiable when exceptional circumstances have happened and the loop has to be
abandoned. It would be nice if more than one loop could be abandoned with a single break but
that isn't how it works. Here is an example.
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
It reads a single character from the program's input before printing the next in a sequence of
numbers. If an „s‟ is typed, the break causes an exit from the loop.
If you want to exit from more than one level of loop, the break is the wrong thing to use.
CONTINUE STATEMENT:
This statement has only a limited number of uses. The rules for its use are the same as for
break, with the exception that it doesn't apply to switch statements. Executing a continue
starts the next iteration of the smallest enclosing do, while or for statement immediately. The
use of continue is largely restricted to the top of loops, where a decision has to be made
whether or not to execute the rest of the body of the loop. In this example it ensures that division
by zero (which gives undefined behaviour) doesn't happen.
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
The continue can be used in other parts of a loop, too, where it may occasionally help to
simplify the logic of the code and improve readability. continue has no special meaning to a
switch statement, where break does have. Inside a switch, continue is only valid if there is a
loop that encloses the switch, in which case the next iteration of the loop will be started.
There is an important difference between loops written with while and for. In a while, a
continue will go immediately to the test of the controlling expression. The same thing in a for
will do two things: first the update expression is evaluated, then the controlling expression is
evaluated.
goto L1;
/* whatever you like here */
L1: /* anything else */
A label is an identifier followed by a colon. Labels have their own „name space‟ so they
can't clash with the names of variables or functions. The name space only exists for the function
containing the label, so label names can be re-used in different functions. The label can be used
before it is declared, too, simply by mentioning it in a goto statement.
Labels must be part of a full statement, even if it's an empty one. This usually only matters
when you're trying to put a label at the end of a compound statement—like this.
The goto works in an obvious way, jumping to the labelled statements. Because the name of
the label is only visible inside its own function, you can't jump from one function to another one.
It's hard to give rigid rules about the use of gotos but, as with the do, continue and the
break (except in switch statements), over-use should be avoided. More than one goto every 3–5
functions is a symptom that should be viewed with deep suspicion.
UNIT – III
The principles of top-down design and structured programming dictate that a program
should be divided into a main module and its related modules. Each module is in turn divided
into sub-modules until the resulting modules are intrinsic; that is, until they are implicitly
understood without further division.
Top-down design is usually done using a visual representation of the modules known as
a structure chart. The structure chart shows the relation between each module and its sub-
modules. The structure chart is read top-down, left-right. First we read Main Module. Main
Module represents our entire set of code to solve the problem.
Structure Chart
Moving down and left, we then read Module 1. On the same level with Module 1 are
Module 2 and Module 3. The Main Module consists of three sub-modules. At this level,
however we are dealing only with Module 1. Module 1 is further subdivided into three
modules, Module 1a, Module 1b, and Module 1c. To write the code for Module 1, we need to
write code for its three sub-modules.
The Main Module is known as a calling module because it has sub-modules. Each of the
sub-modules is known as a called module. But because Modules 1, 2, and 3 also have sub-
modules, they are also calling modules; they are both called and calling modules.
It first sends data to Module 1, which in turn sends it to the Main Module, which passes
it to Module 3, and then on to Module 3b.
The technique used to pass data to a function is known as parameter passing. The
parameters are contained in a list that is a definition of the data passed to the function by the
caller. The list serves as a formal declaration of the data types and names.
FUNCTIONS :
A function is a self contained program segment that carries out some specific well
defined tasks.
Advantages of functions:
1. Write your code as collections of small functions to make your program modular
2.Structured programming
4.Easier modification
declarations;
statements;
FUNCTION HEADER :
FUNCTION PROTOTYPES
If a function is not defined before it is used, it must be declared by specifying the return
type and the types of the parameters.
double sqrt(double);
Tells the compiler that the function sqrt() takes an argument of type double and returns
a double. This means, incidentally, that variables will be cast to the correct type; so sqrt(4) will
return the correct value even though 4 is int not double. These function prototypes are placed
at the top of the program, or in a separate header file, file.h, included as
#include "file.h"
void f (char c, int i); /*equivalent but makes code more readable */
If all functions are defined before they are used, no prototypes are needed. In this case, main()
is the last function of the program.
Variables defined within a function (including main) are local to this function and no
other function has direct access to them. The only way to pass variables to function is as
parameters. The only way to pass (a single) variable back to the calling
Ex:
printf(“%d\n”,b);
return n;
int a = 2, b = 1, c;
c = func(a);
return 0;
FUNCTION CALLS :
When a function is called, expressions in the parameter list are evaluated (in no
particular order!) and results are transformed to the required type. Parameters are copied to
local variables for the function and function body is executed when return is encountered, the
function is terminated and the result (specified in the return statement) is passed to the calling
function (for example main).
Ex:
int i, product = 1;
product *= i;
return product;
int i = 12;
printf(“%d”,fact(i));
return 0;
}
TYPES OF FUNCTIONS:
USER DEFINED FUNCTIONS:
Every program must have a main function to indicate where the program has to begin
its execution. While it is possible to code any program utilizing only main function, it leads to a
number of problems. The program may become too large and complex and as a result task of
debugging, testing and maintaining becomes difficult. If a program is divided into functional
parts, then each part may be independently coded and later combined into a single unit, these
subprograms called “functions” are much easier to understand debug and test.
There are times when some types of operation for calculation is repeated many times at
many points through out a program. For instance, we might use the factorial of a number at
several points in the program. In such situations, we may repeat the program statements
whenever they are needed. Another approach is to design a function that can be called and
used whenever required.
argument declaration;
executable statement 1;
executabie statement 2;
----------
----------
----------
return (expression) ;
The return statement is the mechanism for returning a value to the calling function. All
functions by default returns int type data. we can force a function to return a particular type of
data by using a type specifier in the header.
A function can be called by simply using the function name in the statement.
The C language is accompanied by a number of library functions that perform various tasks.The
ANSI committee has standardized header files which contain these functions.
MATH.H
The math library contains functions for performing common mathematical operations.
Some of the functions are :
ceil : The ceiling function rounds a number with a decimal part up to the next highest
integer (written mathematically as ⌈x⌉)
floor : The floor function rounds a number with a decimal part down to the next lowest
STRING.H
There are many functions for manipulating strings. Some of the more useful are:
STDIO.H
STDLIB.H
This library contains several functions for getting the current date and time.
Contains the assert macro, used to assist with detecting logical errors and other
<assert.h>
types of bug in debugging versions of a program.
<complex.h> A set of functions for manipulating complex numbers. (New with C99)
<inttypes.h> For precise conversion between integer types. (New with C99)
<iso646.h> For programming in ISO 646 variant character sets. (New with NA1)
<setjmp.h> Declares the macros setjmp and longjmp, which are used for non-local exits
Provides the core input and output capabilities of the C language. This file
<stdio.h>
includes the venerable printf function.
For manipulating wide streams and several kinds of strings using wide characters
<wchar.h>
- key to supporting a range of languages. (New with NA1)
CATEGORIES OF FUNCTIONS :
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to.
When a function has no arguments, it does not receive any data from calling function.
In effect, there is no data transfer between calling function and called function.
#include<stdio.h>
main()
{
printline();
value();
printline();
printline()
int i;
for(i=1;i<=35;i++0)
printf(“%c”,”-“);
printf(“\n”);
value()
float inrate,sum,principal;
scanf(“%f%f%f”,&principal,&inrate,&period);
sum=principal;
year=1;
while(year<=period)
sum=sum*(1+inrate);
year=year+1;
}
printf(“%f%f%d%f”,principal,inrate,period,sum);
The actual (sent through main) and formal(declared in header section) should match in number,
type and order.
In case actual arguments are more than formal arguments, extra actual arguments are
discarded. On other hand unmatched formal arguments are initialized to some garbage values.
#include<stdio.h>
main()
float prin,inrate;
int period;
scanf(“%f%f%d”,&principal,&inrate,&period);
printline(‘z’);
printline(‘c’);
printline(ch)
char ch;
int i;
for(i=1;i<=52;i++)
printf(“%c”,ch);
printf(“\n”);
The process of passing the actual value of variables is known as Call by Value.
The process of calling a function using pointers to pass the addresses of variables is
known as Call by Reference. The function which is called by reference can change the value
of the variable used in the call.
STORAGE CLASSES :
1. Automatic Variables
2. External Variables
3. Static Variables
4. Register Variables
SCOPE :
The Scope of variable determines over what parts of the program a variable is actually
available for use.
LONGEVITY :
Longevity refers to period during which a variable retains a given value during execution
of a program (alive). So Longevity has a direct effect on utility of a given variable.
The variables may also be broadly categorized depending on place of their declaration as
internal(local) or external(global). Internal variables are those which are declared within a
particular function, while external variables are declared outside of any function.
AUTOMATIC VARIABLES :
They are declared inside a function in which they are to be utilized. They are created
when 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 referred to as local or
internal variables.
#include<stdio.h>
main()
int m=1000;
func2();
printf(“%d\n”,m);
func1()
int m=10;
printf(“%d\n”,m);
}
func2()
int m=100;
func1();
printf(“%d”,m);
First, any variable local to main will normally live throughout the whole program, although it is
active only in main.
Secondly, during recursion, nested variables are unique auto variables, a situation similar to
function nested auto variables with identical names.
EXTERNAL VARIABLES :
Variables that are both alive and active throughout entire program are known as
external variables. They are also known as Global Variables. In case a local and global have
same name local variable will have precedence over global one in function where it is declared.
#include<stdio.h>
int x;
main()
x=10;
printf(“%d”,x);
printf(“x=%d”,fun1());
printf(“x=%d”,fun2());
printf(“x=%d”,fun3());
fun1()
x=x+10;
return(x);
fun2()
int x;
x=1;
return(x);
fun3()
x=x+10;
return(x);
An extern within a function provides the type information to just that one function.
STATIC VARIABLES :
The value of Static Variable persists until the end of program. A variable can be
declared Static using Keyword Static like Internal & External Static Variables are differentiated
depending whether they are declared inside or outside of auto variables, except that they
remain alive throughout the remainder of program.
#include<stdio.h>
main()
int I;
for (I=1;I<=3;I++)
stat();
stat()
x=x+1;
printf(“x=%d\n”,x);
REGISTER VARIABLES :
We can tell the Compiler that a variable should be kept in one of the machines registers,
instead of keeping in the memory. Since a register access is much faster than a memory
access, keeping frequently accessed variables in register will lead to faster execution
Syntax:
int fibonacci(int n)
if (n <= 1)
return n;
else
With recursion 1.4 x 10 9 function calls needed to find the 43rd Fibonacci number(which
has the value 433494437) .If possible, it is better to write iterative functions.
product *= n;
return product;
}
UNIT – IV
ARRAYS :
An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students are represented using an array name students. A
particular value is indicated by writing a number called index number or subscript in brackets
after array name. The complete set of value is referred to as an array, the individual values are
called elements.
A list of items can be given one variable index is called single subscripted variable or a
one-dimensional array.
The subscript value starts from 0. If we want 5 elements the declaration will be
int number[5];
This array is of type float. Its name is avg. and it can contains 50 elements only. The
range starting from 0 – 49 elements.
Initialization of Arrays :
Initialization of elements of arrays can be done in same way as ordinary variables are
done when they are declared.
If the number of values in the list is less than number of elements then only that elements will
be initialized. The remaining elements will be set to zero automatically.
The size may be omitted. In such cases, Compiler allocates enough space for all initialized
elements.
#include<stdio.h>
main()
int i;
float x[10],value,total;
for(i=0;i<10;i++)
scanf(“%f”,&value);
x[i]=value;
total=0;
for(i=0;i<10;i++)
total=total+x[i]
for(i=0;i<10;i++)
printf(“x*%2d+=%5.2f\n”,I+1,x*I+);
printf(“total=%0.2f”,total);
To store tables we need two dimensional arrays. Each table consists of rows and
columns. Two dimensional arrays are declare as
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
int row,cols,prod[ROWS][COLS];
int i,j;
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
row = i+1;
printf(“%2d|”,row);
COLS=j;
printf(“%4d”,prod*i+*j+);
}
}
They can be initialized by following their declaration with a list of initial values enclosed
in braces.
Initializes the elements of first row to zero and second row to one. The initialization is done by
row by row. The above statement can be written as
When all elements are to be initialized to zero, following short-cut method may be used.
STRINGS(CHARACTER ARRAYS) :
A String is an array of characters. Any group of characters (except double quote sign
)defined between double quotes is a constant string.
A string variable is any valid C variable name and is always declared as an array.
char string name [size];
size determines number of characters in the string name. When the compiler assigns a
character string to a character array, it automatically supplies a null character (‘\0’) at end of
String. Therefore, size should be equal to maximum number of character in String plus one.
char address[15];
scanf(“%s”,address);
The problem with scanf function is that it terminates its input on first white space it finds. So
scanf works fine as long as there are no spaces in between the text.
If we are required to read a line of text we use getchar(). which reads a single
characters. Repeatedly to read successive single characters from input and place in character
array.
#include<stdio.h>
main()
{
char line[80],ano_line[80],character;
int c;
c=0;
scanf(“%s”, line);
do
character = getchar();
ano_line[c] = character;
c++;
- while(character !=’\n’);
c=c-1;
ano_line*c+=’\0’;
The ..scanf functions provide a means to input formatted information from a stream
These functions take input in a manner that is specified by the format argument and store each
input field into the following arguments in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which specifies how
the input is to be stored in the appropriate variable. Other characters in the format string
specify characters that must be matched from the input, but are not stored in any of the
following arguments. If the input does not match then the function stops scanning and returns.
A whitespace character may match with any whitespace character (space, tab, carriage return,
new line, vertical tab, or formfeed) or the next incompatible character.
Declarations:
These functions take the format string specified by the format argument and apply each
following argument to the format specifiers in the string in a left to right fashion. Each
character in the format string is copied to the stream except for conversion characters which
specify a format specifier.
String Input/Output
In addition to the Formatted string functions,C has two sets of string functions that read and
write strings without reformatting any data.These functions convert text file lines to strings and
strings to text file lines.
gets():
Declaration:
Reads a line from stdin and stores it into the string pointed to by str. It stops when either the
newline character is read or when the end-of-file is reached, whichever comes first. The
newline character is not copied to the string. A null character is appended to the end of the
string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file
occurs before any characters have been read, the string remains unchanged.
puts:
Declaration:
Writes a string to stdout up to but not including the null character. A newline character is
appended to the output.
strcat() function:
strcat(string1,string2);
string1 = VERY
string2 = FOOLISH
strcat(string1,string2);
string1=VERY FOOLISH
string2 = FOOLISH
strcmp() function :
This function compares two strings identified by arguments and has a value 0 if they are
equal. If they are not, it has the numeric difference between the first non-matching characters
in the Strings.
strcmp(string1,string2);
Ex:- strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“ROM”,”Ram”);
strcpy() function :
strcpy(string1,string2);
strlen() function :
Counts and returns the number of characters in a string.
n= strlen(string);
/* Illustration of string-handling */
#include<stdio.h>
#include<string.h>
main()
char s1[20],s2[20],s3[20];
int X,L1,L2,L3;
scanf(“%s %s”,s1,s2);
X=strcmp(s1,s2);
if (X!=0)
strcat(s1,s2);
}
else
strcpy(s3,s1);
L1=strlen(s1);
L2=strlen(s2);
L3=strlen(s3);
}
UNIT – V
POINTERS:
One of the powerful features of C is ability to access the memory variables by their
memory address. This can be done by using Pointers. The real power of C lies in the proper use
of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a
pointer points to a variable that is stored at that address. A pointer itself usually occupies 4
bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side 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.
Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
The operator & returns the memory address of variable on which it is operated, this is
called Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to
display the contents of the Pointer Variable.
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following
printf statements is :
Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
When an array is declared, elements of array are stored in contiguous locations. The
address of the first element of an array is called its base address.
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we can
make the pointer P to point to the array a by following assignment
P = a;
We can access every value of array a by moving P from one element to another.
i.e., P points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd element
P +4 points to 4th element
main()
{
int *a,i;
printf(“Enter five elements:”);
for (i=0;i<5;i++)
scanf(“%d”,a+i);
printf(“The array elements are:”);
for (i=0;i<5;i++)
printf(“%d”, *(a+i));
}
STRUCTURES :
A Structure is a collection of elements of dissimilar data types. Structures provide the
ability to create user defined data types and also to represent real world data.
Suppose if we want to store the information about a book, we need to store its name
(String), its price (float) and number of pages in it(int). We have to store the above three items
as a group then we can use a structure variable which collectively store the information as a
book.
Structures can be used to store the real world data like employee, student, person etc.
Declaration :
The declaration of the Structure starts with a Key Word called Struct and ends with ; .
The Structure elements can be any built in types.
Initialization :
Structure elements are stored in contiguous memory locations as shown below. The
above Structure occupies totally 26 bytes.
main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;
printf (“ Enter Employee number: \n”);
scanf(“%d”,&e.empno);
printf (“ Enter Employee Name: \n”);
scanf(“%s”,&e.empname);
printf (“ Enter the Salary: \n”);
scanf(“%f”,&e.sal);
printf (“ Employee No = %d”, e.empno);
printf (“\n Emp Name = %s”, e.empname);
printf (“\n Salary = %f”, e.sal);
}
/* Program to read Student Details and Calculate total and average using structures */
#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s;
int tot;
float avg;
#include<stdio.h>
main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
struct item i;
float tot_amt;
ARRAY OF STRUCTURES :
To store more number of Structures, we can use array of Structures. In array of
Structures all elements of the array are stored in adjacent memory location.
main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];
int i;
for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”);
scanf(“%s%f%d”, b[i].name,&b[i].price,&b[i].pages);
}
for (i i=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}
UNIONS :
Union, similar to Structures, are collection of elements of different data types. However,
the members within a union all share the same storage area within the computer‟s memory,
whereas each member within a Structure is assigned its own unique Storage area.
Structure enables us to treat a member of different variables stored at different places in
memory, a union enables us to treat the same space in memory as a number of different
variables. That is, a union offers a way for a section of memory to be treated as a variable of one
type on one occasion and as a different variable of a different type on another occasion.
Unions are used to conserve memory. Unions are useful for applications involving
multiple members, where values need not be assigned to all of the members at any given time.
An attempt to access the wrong type of information will produce meaningless results.
The union elements are accessed exactly the same way in which the structure elements
are accessed using dot(.) operator.
The difference between the structure and union in the memory representation is as
follows.
struct cx
int i;
char ch[2];
};
struct cx s1;
union ex
int i;
char ch[2];
union ex u;
--------u.i ---------------
u.ch[0] u.ch[0]
main()
{
union example
int i;
char ch[2];
};
union exaple u;
u.i = 412;
Output :
u.i = 512
u.ch[0] = 0
u.ch[1] =2
u.i = 562
u.ch[0] = 50
u.ch[1] =2
A union may be a member of a structure, and a structure may be a member of a union. And
also structures and unions may be freely mixed with arrays.
/* Program to illustrate union with in a Structure */
main()
{
union id
char color;
int size;
};
struct {
char supplier[20];
float cost;
union id desc;
}pant, shirt;
shirt.desc.color = ‘w’;
shirt.desc.size = 12;