SlideShare a Scribd company logo
1 of 97
C NOTES
EDITED BY
S.MUTHUGANESH M.Sc.,B.Ed.,
ASSISTANT PROFESSOR OF COMPUTER
SCIENCE
VIVEKANANDA COLLEGE
C-NOTES MUTHUGANESH S 1
Introduction
C is a powerful, flexible, portable and elegantly structured programming language.
Since C combines the features of high-level language with the elements of the assembler,
it is suitable for both system and application programming language.
History of c
1960 International Group
1967 Martin Richards
1970 Ken Thompson
1972 Dennis Richie
Kernighen and Richie
1978
ANSI Committee
1989
1990 ISO Committee
1999 Standardization Committee
ALGOL
BCPL
B
TRADITIONAL C
K&R C
ANSI ISO C
ANSI C
C99
C-NOTES MUTHUGANESH S 2
Importance of C
The increasing popularity of C is probably due to its many desirable qualities. It is a robust
language whose rich set of build-in functions and operators can be used to write any complex
program. The C compilers combines the capabilities of an assembly language with the
features of a high-level language and therefore it is well suited for writing both system
software and business packages. In fact, many of the C compilers available in the market are
written in C. The main importance of C are listed below.
 Program written in C are efficient and fast due to variety of data types and powerful
operators
 It provides various build-in functions.
 C is highly portable. The C program written in one computer with one operating
system can be run into another computer with another operating system. That means program
written in Windows can run in Linux or Unix as well with no or little modifications.
 C programming can be viewed as the collections of modules so it is highly structured.
 The modular programming makes testing and debugging easier.
 C has ability to extend itself.
C-NOTES MUTHUGANESH S 3
Basic structures of C
1. Documentation section: The documentation section consists of a set of comment
lines giving the name of the program, the author and other details, which the
programmer would like to use.
2. Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include<stdio.h>
3. Definition section: The definition section defines all symbolic constants such using
the #define max 10.
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions.
5. main () function section: Every C program must have one main function section.
This section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all variables used in the
executable part.
C-NOTES MUTHUGANESH S 4
2. Executable part: There is at least one statement in the executable part. These
two parts must appear between the opening and closing braces. It begins at the
opening brace and ends at the closing brace. The closing brace of the main
function is the logical end of the program. All statements in the declaration
and executable part end with a semicolon.
6. Subprogram section: If the program is then the subprogram section contains all that
are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.
Example Program
/*Documentation Section: program to find the area of circle*/
#include <stdio.h> /*link section*/
#include <conio.h> /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circlen"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
C-NOTES MUTHUGANESH S 5
C Library
Some functions are written by users, like us are stored in library. Library functions are
grouped category-wised and stored in different files known as header files. If you want to
access the functions from the library its necessary to tell compiler this achieved by using
preprocessor directive
#include<filename.h>
A header file is a file with extension .h
Example
#include<stdio.h>
Header Files
This is a list of the header files that you can include in your program if you want to
use the functions available in the C standard library:
Header File Type of Functions
<assert.h> Diagnostics Functions
<ctype.h> Character Handling Functions
<math.h> Mathematics Functions
<setjmp.h> Nonlocal Jump Functions
<signal.h> Signal Handling Functions
<stdio.h> Input/Output Functions
<stdlib.h> General Utility Functions
<string.h> String Functions
<time.h> Date and Time Functions
C-NOTES MUTHUGANESH S 6
Constants, Variables, and Data Types
Introduction
The task of processing of data is accomplished by executing a sequence of
instruction is called Program. These instructions are formed using certain symbols and words
according to some rules known as SYNTAX or Grammar.
C has own vocabulary and grammar they are constants, variable and their types related to C
programming language.
Characterset
The characters that can be used form words, numbers and expression depend upon the
computer on which program is run.
The characters in C are grouped into following categories
Letters
Digits
Special characters
White spaces
The character set is the fundamental raw material of any language and they are used
to represent information. Like natural languages, computer language will also have well
defined character set, which is useful to build the programs.
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z
DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
SPECIAL CHARACTERS
~ tilde % percent sign | vertical bar @ at symbol
+ plus sign < less than
_ underscore - minus sign > greater than ^ caret
# number sign = equal to
& ampersand $ dollar sign / slash ( left parenthesis
* asterisk  back slash
) right parenthesis ′ apostrophe : colon [ left bracket
C-NOTES MUTHUGANESH S 7
" quotation mark ; semicolon
] right bracket ! exclamation mark , comma { left flower brace
? Question mark . dot operator
} right flower brace
WHITESPACE CHARACTERS
b blank space t horizontal tab v vertical tab
r carriage return f form feed n new line
 Back slash ’ Single quote " Double quote
? Question mark 0 Null a Alarm (bell)
C Tokens
In a passage of text, individual words and punctuation marks are called tokens or
lexical units. Similarly, the smallest individual unit in a c program is known as a token or a
lexical unit. C tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords
C keywords have fixed meanings and these meanings cannot be changed. The keywords
cannot be used as variable names.
C has 32 key words they are
C-NOTES MUTHUGANESH S 8
The list of C keywords is given below:
auto Break Case Char const
continue Default Do Double else
enum Extern Float For goto
If Int Long register return
short Signed Sizeof static struct
switch Typedef Union unsigned void
volatile While
Identifiers
Identifiers are used as the general terminology for the names of variables, functions
and arrays. These are user defined names consisting of long sequence of letters and digits
with either a letter or the underscore (_) as a first character.
There are certain rules that should be followed while naming C identifiers:
 They must begin with a letter or underscore (_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:
C-NOTES MUTHUGANESH S 9
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C Constants
C constants refers to the data items that do not change their value during the program
execution. Several types of C constants that are allowed in C are:
IntegerConstants
Integer constants are whole numbers without any fractional part. It must have at least
one digit and may contain either + or – sign. A number with no sign is assumed to be
positive.
There are three types of integer constants:
DecimalIntegerConstants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or +
sign.
Example of valid decimal integer constants
341, -341, 0, 8972
OctalInteger Constants
Integer constants consisting of sequence of digits from the set 0 through 7
starting with 0 is said to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540
HexadecimalInteger Constants
Hexadecimal integer constants are integer constants having sequence of digits
preceded by 0x or 0X. They may also include alphabets from A to F representing numbers 10
to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
C-NOTES MUTHUGANESH S 10
It should be noted that, octal and hexadecimal integer constants are rarely used in
programming.
RealConstants
The numbers having fractional parts are called real or floating point constants. These
may be represented in one of the two forms called fractional form or the exponent form and
may also have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constantin exponent form
The general format in which a real number may be represented in exponential or
scientific form is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
CharacterConstants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‘a’ , ‘Z’, ‘5’
It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‘A’ is 65 which is its ASCII value.
Escape Characters/Escape Sequences
C allows us to have certain non graphic characters in character constants. Non graphic
characters are those characters that cannot be typed directly from keyboard, for example,
tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences represented by a
backslash () followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single
character.
C-NOTES MUTHUGANESH S 11
Escape Sequence Description
A Audible alert(bell)
B Backspace
F Form feed
N New line
R Carriage return
T Horizontal tab
V Vertical tab
 Backslash
“ Double quotation mark
‘ Single quotation mark
? Question mark
Null
String Constants
String constants are sequence of characters enclosed within double quotes. For
example,
“hello”
“abc”
“hello911”
Every sting constant is automatically terminated with a special character ‘’ called the null
character which represents the end of the string.
For example, “hello” will represent “hello” in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.
C-NOTES MUTHUGANESH S 12
SpecialSymbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
Data types
 C language has rich data type. Used to storage representations and machine instructions.
 Data types specify how we enter data into our programs and what type of data we enter.
C supports three classes of data types
C-NOTES MUTHUGANESH S 13
The following table provides the details with their storage sizes and value ranges −
Type Storage size Value range
Char 1 byte -128 to 127 or0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or4 bytes 0 to 65,535 or0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Integer type
 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use.
C-NOTES MUTHUGANESH S 14
 Integers occupy one word of storage(depending on machines)
 If 16 bit the size of the integer value is limited range is -32768 to +32767.
 C has three classes of integer storage namely short int, int and long int in both signed
and unsigned.
int a=2; C stores like one word as 8-bit(1byte)
0 0 0 0 0 0 1 0
FLOATING POINT DATA TYPE:
Floating point data type consists of 2 types. They are,
1. float
2. double
1. FLOAT:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the
CPU as “int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.
2. DOUBLE:
 Double data type is also same as float data type which allows up-to 15 digits after
decimal.
 Storage size of float data type is 8
 Long Storage size of float data type is 10
 The range for double data type is from 1E–37 to 1E+37.
Long int 4byte
Int2byte
Short int 1b
C-NOTES MUTHUGANESH S 15
Void
Void has no values. This is usually used to specify the type of function. The type of
function is said to be void when it does not return value to calling function.
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
Variables in C Language
The naming of an address is known as variable. Variable is the name of memory
location. Unlike constant, variables are changeable, we can change value of a variable during
execution of a program. A programmer can choose a meaningful variable name. Example :
average, height, age, total etc.
Rules to define variable name
 Variable name must not start with a digit.
 Variable name can consist of alphabets, digits and special symbols like underscore.
 Blank or spaces are not allowed in variable name.
 Keywords are not allowed as variable name.
Declarationand Definition of variable
Declaration of variables must be done before they are used in the program.
Declaration does two things.
 It tells the compiler what the variable name is.
 It specifies what type of data the variable will hold.
Long double
double
float
C-NOTES MUTHUGANESH S 16
Definition of variable means to assign a value to a variable. Definition specify what code or
data the variable describes. A variable must be declared before it can be defined.
SYNTAX
datatype v1,v2,v3,……vn;
int a;
Assigning value of variable
int a;
a=5;
/*---------------Sample program-------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
char name[25];
int n,c,dig,dm,tot,rollno;
float avg;
clrscr();
printf("Enter your name");
scanf("%s",&name);
printf("Enter Your Rollno");
scanf("%d",&rollno);
printf("Enter Your Marks One by One like C,DIG,DMn");
scanf("%d",&c);
scanf("%d",&dig);
scanf("%d",&dm);
tot=c+dig+dm;
avg=tot/3;
printf("Hi Mr.%s Your Rollno is %d You get Marks in Your Subjectsn
C=t%dnDig=t%dnDM=t%dn",name,rollno,c,dig,dm);
printf("Your Total is %d and Average is %f",tot,avg);
getch();
C-NOTES MUTHUGANESH S 17
}
After the execute the program the output will appear
User-Defined Data Types:
C supports the features “typedef” that allows users to define the identifier which
would represent an existing data type. This defined data type can then be used to declare
variables:
Syntax:
typedef int numbers;
numbers num1,num2;
In this example, num1 and num2 are declared as int variables. The main advantage
of user defined data type is that it increases the program’s readability.
Another type is enumerated type. This is also a user defined data type
C-NOTES MUTHUGANESH S 18
Syntax:
enum identifier {value1,value2, value 3,…}
“Enum” is the keyword and “identifier” is the user defined data type that is used to
declare the variables. It can have any value enclosed within the curly braces. For example:
enum day {January, February,March,April,..};
enum day month_st,month_end;
The compiler automatically assigns integer digits beginning from 0 to all the
enumeration constants. For example, “January ” will have value 0 assigned, “February”
value 1 assigned and so on. You can also explicitly assign the enumeration constants.
Operator
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following types of
operators −
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Increment and Decrement operators
 Conditional operator
 Special operator
Arithmetic operator
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).
C-NOTES MUTHUGANESH S 19
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* Multiplication
/ Division
% remainder after division( modulo division)
/*----------------operator example programs-------------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=4,c;
c=a+b;
clrscr();
printf("a+b= %dn",c);
c=a-b;
printf("a-b= %dn",c);
c=a*b;
printf("a*b= %dn",c);
c=a/b;
printf("a/b= %dn",c);
c=a%b;
printf("amodulb= %dn",c);
getch();
}
Output:
C-NOTES MUTHUGANESH S 20
Increment and decrement operators
C programming has two operators increment ++ and decrement -- to change the value
of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These
two operators are unary operators, meaning they only operate on a single operand.
a=5;
a++; act as a=a+1;
a--; act as a=a-1;
Suppose you use ++ operator as prefix like: ++var. The value of var is incremented by 1 then,
it returns the value.
Suppose you use ++ operator as postfix like: var++. The original value of var is returned first
then, var is incremented by 1.
Relational Operators
Weoften compare two quantities and depending ontheir relation, take certain decisions.
The following table shows all the relational operators supported by C.
C-NOTES MUTHUGANESH S 21
Operator Description
== Checks if the values of two operands are equal or not. If yes, then the condition
becomes true.
!= Checks if the values of two operands are equal or not. If the values are not equal,
then the condition becomes true.
> Checks if the value of left operand is greater than the value of right operand. If
yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of right operand. If yes,
then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right
operand. If yes, then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right
operand. If yes, then the condition becomes true.
LogicalOperators
The logical operators are used when we want test more than one condition. Following table
shows all the logical operators supported by C language.
C-NOTES MUTHUGANESH S 22
Operator Description
&& Called Logical AND operator. If both the operands are non-zero, then the condition
becomes true.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the
condition becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand.
If a condition is true, then Logical NOT operator will make it false.
The if else is actually just on extension of the general format of if statement. If the
result of the condition is true, then program statement 1 is executed, otherwise program
statement 2 will be executed.
The if...else statement executes some code if the test expression is true (nonzero) then
body of if statements will be executed otherwise the false statement else statements executes .
Assignment Operators
The assignment operators are used to assign values result of an expression to a
variable.The following table lists the assignment operators supported by the C language –
Operator Description Example
= Simple assignment operator. Assigns values from right side operands
to left side operand
C = A + B will
assign the
value of A + B
to C
+= Add AND assignment operator. It adds the right operand to the left
operand and assign the result to the left operand.
C += A is
equivalent to
C = C + A
C-NOTES MUTHUGANESH S 23
-= Subtract AND assignment operator. It subtracts the right operand
from the left operand and assigns the result to the left operand.
C -= A is
equivalent to
C = C - A
*= Multiply AND assignment operator. It multiplies the right operand
with the left operand and assigns the result to the left operand.
C *= A is
equivalent to
C = C * A
/= Divide AND assignment operator. It divides the left operand with the
right operand and assigns the result to the left operand.
C /= A is
equivalent to
C = C / A
%= Modulus AND assignment operator. It takes modulus using two
operands and assigns the result to the left operand.
C %= A is
equivalent to
C = C % A
Bitwise operators
Bitwise operators are used in C programming to perform bit-level operations. These
operators are used for testing the bits, or shifting them right or left.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
C-NOTES MUTHUGANESH S 24
Operators Meaning of operators
>> Shift right
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The size of operator
Its compile time operator,To get the exact size of a type or a variable on a particular
platform, youcan use the sizeof operator. The expressions sizeof(type) yields the storage
size of the object or type in bytes.
Conditional operator
A conditional operator is a ternary operator, that is, it works on 3 operands.
Conditional OperatorSyntax
conditionalExpression ? expression1 : expression2
The conditional operator works as follows:
 The first expression conditional Expression is evaluated first. This expression
evaluates to 1 if it's true and evaluates to 0 if it's false.
 If conditional Expression is true, expression1 is evaluated.
 If conditional Expression is false, expression2 is evaluated.
/*------------conditional.c---------------------*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
C-NOTES MUTHUGANESH S 25
printf("Enter the number");
scanf("%d",&num);
((num%2==0)?printf("even"):printf("odd"));
getch();
}
Storage class
Storage class that provides information about their location and visibility. C has four different
types of Storage Class.
Storage class Meaning
Auto Local variable known only to the function in
which declared
Static
Local variable which exists and retains its
values even after control transferred to the
calling function.
Extern Global variable known to all function in the
file.
Register Local variable which is stored to register.
C-NOTES MUTHUGANESH S 26
Operator precedence in C
Operator Description Associativity
( )
[ ]
.
->
++ --
Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)
left-to-right
++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary value of type)
Dereference
Address (of operand)
Determine size in bytes on this implementation
right-to-left
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <=
> >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
| | Logical OR left-to-right
? : Ternary conditional right-to-left
=
+= -=
*= /=
%= &=
^= |=
<<= >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left
, Comma (separate expressions) left-to-right
C-NOTES MUTHUGANESH S 27
scanf
Usually input statement is used in C is scanf()
Syntax
scanf (“control string”, &v1,&v2,&v3,…&vn);
 The control string must be a text enclosed in double quotes.
 It contains the data format of data being received.
 The ampersand & before each variable is an operator that specified the variable’s
names address and connecting it into internal representation in memory.
 Example for control string : integer (%d) , float (%f) , character (%c) or string (%s).
 Format specification contained in the control string should match the argument order.
Printf()
 printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.
 We use printf() function with %d , %f, %s format specifier to display the value of an
variable.
 To generate a newline,we use “n” in printf() statement.
Syntax
printf (“outputstring identifiers(like %s,%d)”, variablenames);
Example
printf(“hai hello%s”,name);
Format Specifier Description
%c Accepts and prints characters
%d Accepts and prints signed integer
%e or %E Scientific notation of floats
%f Accepts and prints float numbers
%i Accepts and prints integer values
C-NOTES MUTHUGANESH S 28
Format Specifier Description
%l or %ld or %li Long integer values
%lf Double values
%Lf Long double values
%lu Unsigned int or unsigned long
%o Provides the octal form of representation
%s Accepts and prints String values
%u Accepts and prints unsigned int
%x or %X Provides the hexadecimal form of representation
getchar()
getchar is a function in C programming language that reads a single character.
getchar() function is used to get/read a character from keyboard input. When this statement
encountered the computer waits until key is pressed.
Syntax
Variable_name=getchar();
Example
char name;
name = getchar();
putchar()
putchar() function is a file handling function in C programming language which is used to
write a character on standard output/screen.
Syntax
putchar(variablename);
Example
Choice=’y’;
putchar(Choice);
C-NOTES MUTHUGANESH S 29
Decision Making and Branching
We want to executes some certain statements executes certain conditions are
met. This involves a kind of particular decision making to see whether a particular
condition has occurred or not then the computer to execute certain statements
accordingly.
C language possess such decision-making capabilities by supporting the following
statements
1. If statement
2. Switch statement
3. Conditional operator statement
4. Goto statement
if Statement:
The simplest form of the control statement is the If statement. It is very frequently
used in decision making and allowing the flow of program execution.
The If structure has the following syntax
if (test expression)
{
body of the statement;
}
Statement-x;
The if statement evaluates the test expression inside the parenthesis.
If the test expression is evaluated to true (nonzero), statements inside the body of if is
executed.
If the test expression is evaluated to false (0), statements inside the body of if is skipped from
execution.
C-NOTES MUTHUGANESH S 30
if...else statement
The if...else statement executes some code if the test expression is true (nonzero) and some
other code if the test expression is false (0).
if (test expression)
{
body of true-block statement;
}
else
{
body of false-block statement;
}
Statement-x;
If test expression is true, codes inside the body of if statement is executed and, codes inside
the body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes
inside the body of if statement is skipped.
Then the control transferred to statement-x.
C-NOTES MUTHUGANESH S 31
/*odd or even*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Please Enter the Number");
scanf("%d",&n);
if((n%2)==0)
{
printf("%d nThe given Number is even",n);
}
else
{
printf("%d nThe Given Number is odd",n);
}
printf("nHave a Nice Day");
getch();
}
Output
Nestedif..else statement
Syntax
if (condition1)
{
if (condition2)
{
statement-1;
C-NOTES MUTHUGANESH S 32
}
else
{
statement-2;
}
}
else
{
statement-3;
}
Statement-x;
The if statement may be nested as deeply as you need to nest it. One block of code
will only be executed if two conditions are true. Condition 1 is tested first and then condition
2 is tested. The second if condition is nested in the first. The second if condition is tested only
when the first condition is true else the program flow will skip to the corresponding else
statement
C-NOTES MUTHUGANESH S 33
/*nested if*/
#include<stdio.h>
#include<conio.h>
void main()
{
float balance,bonus,total=0;
char sex;
clrscr();
printf("Enter your Sex like Male(m)/Female(f)");
scanf("%s",&sex);
printf("Enter your Balance");
scanf("%f",&balance);
if(sex=='f')
{
if(balance>=5000)
{
bonus=0.05*balance;
total=balance+bonus;
printf("nThe Total salary is %f",total);
}
else
{
bonus=0.03*balance;
total=balance+bonus;
printf("nThe Total Salary is %f",total);
}
}
else
{
bonus=0.02*balance;
total=balance+bonus;
printf("nThe total Salary is %f",total);
}
printf("nHave a Nice Day");
getch();
}
Output
C-NOTES MUTHUGANESH S 34
if else ladder statement
There is another way to putting ifs together when the multipath decisions are
involved. The condition evaluated from top to downwards, as soon as true condition is found,
the statement associated with it is executed and the control transferred to next
statement(skipping the rest of the ladder). When all the n conditions false, then final else
containing the default statement will be executed.
Syntax
if(condition_expression_1)
{
statement1;
}
else if (condition_expression_2)
{
statement2;
}
else if (condition_expression_3)
{
statement3;
}
else
{
statement4;
}
C-NOTES MUTHUGANESH S 35
 First of all condition_expression_1 is tested and if it is true then statement1 will be
executed and control comes out out of whole if else ladder.
 If condition_expression_1 is false then only condition_expression_2 is tested. Control
will keep on flowing downward, If none of the conditional expression is true.
 The last else is the default block of code which will gets executed if none of the
conditional expression is true.
/*biggest of among three numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,n3;
clrscr();
printf("Enter Numbers One by Onen");
scanf("%dn%dn%d",&n1,&n2,&n3);
if((n1>n2)&&(n1>n3))
{
printf("%d is the largest number",n1);
}
else if((n2>n1)&&(n2>n3))
C-NOTES MUTHUGANESH S 36
{
printf("%d is the largest number",n2);
}
else
{
printf("%d is the largest number",n3);
}
getch();
}
Output
Switch statement
When you want to solve multiple option type problems, for example, menu like
program, where one value is associated with each option and you need to choose only one at
a time, then, switch statement is used. Switch statement is a control statement that allows us
to choose only one choice among the many given choices. The expression in switch evaluates
to return an integral value, which is then compared to the values present in different cases. It
executes that block of code which matches the case value. If there is no match, then default
block is executed (If present).The general form of switch statement is,
C-NOTES MUTHUGANESH S 37
Syntax
The syntax for a switch statement in C programming language is as follows −
switch(expression)
{
case value 1:
block-1;
break;
case value 2:
block-2;
break;
case value 3:
block-3;
break;
case value 4:
block-4;
break;
default:
default-block;
break;
}
The following rules apply to a switch statement −
 The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral
or enumerated type.
 You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon(:).
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
C-NOTES MUTHUGANESH S 38
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
/*vibgyor.c*/
#include<stdio.h>
#include<conio.h>
void main()
{
char color;
clrscr();
C-NOTES MUTHUGANESH S 39
printf("Enter your choice");
scanf("%s",&color);
switch(color)
{
case 'v' :
printf("Voilet");
break;
case 'i':
printf("Indigo");
break;
case 'b':
printf("Blue");
break;
case 'g':
printf("Green");
break;
case 'y':
printf("Yellow");
break;
case 'o':
printf("Orange");
break;
case 'r':
printf("Red");
break;
default:
printf("Your Entered Wrong Option");
break;
}
getch();
}
Output
C-NOTES MUTHUGANESH S 40
Decision Making and Looping
 Execution of a statement or set of statement repeatedly is called as looping.
 The loop may be executed a specified number of times and this depends on the
satisfaction of a test condition.
 Depending on the position of the control statement in the loop, a control structure may
be classified either as an entry controlled loop or as an exit controlled loop.
 When the control statement is placed before the body of the loop then such loops are
called as entry controlled loops. If the test condition in the control statement is true
then only the body of the loop is executed.
 When the control statement is placed after the body of the loop then such loops are
called as exit controlled loop. In this the body of the loop is executed first then the
test condition in the control statement is checked.
The For statement
For loop is entry controlled loop statement. The general structure form of for loop
Syntax
for (initialization; test condition; increment)
{
body of the loop
}
When the control enters for loop the variables used in for loop is initialized with the
starting value
The value which was initialized is then checked with the given test condition. The test
condition is a relational expression, such as I < 5 that checks whether the given condition is
satisfied or not if the given condition is satisfied the control enters the body of the loop or
else it will exit the loop.
The body of the loop is entered only if the test condition is satisfied and after the
completion of the execution of the loop the control is transferred back to the increment part of
the loop. The control variable is incremented using an assignment statement such as I=I+1 or
C-NOTES MUTHUGANESH S 41
simply I++ and the new value of the control variable is again tested to check whether it
satisfies the loop condition. If the value of the control variable satisfies then the body of the
loop is again executed. The process goes on till the control variable fails to satisfy the
condition.
For loop Flowchart
Example program
/*sum of n numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,sum=0;
printf("Enter positive integer");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("sum=%d",sum);
getch();
}
C-NOTES MUTHUGANESH S 42
The While Statement:
The simplest of all looping structure in C is the while statement and its entry
controlled loop statement. The general format of the while statement is:
while (test condition)
{
body of the loop
}
The while loop flow chart
C-NOTES MUTHUGANESH S 43
Here the given test condition is evaluated and if the condition is true then the body of
the loop is executed. After the execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. This process of repeated execution
of the body continues until the test condition finally becomes false and the control is
transferred out of the loop. On exit, the program continues with the statements immediately
after the body of the loop. Example program for while statement
/* sum of digit*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum;
clrscr();
printf("Enter Value");
scanf("%d",&n);
sum=0;
while(n>0)
{
sum=sum+(n%10);
n=n/10;
}
printf("Sum Of Digit=%d",sum);
getch();
}
Output
C-NOTES MUTHUGANESH S 44
The Do while statement:
The do while loop is also a kind of loop and its exit controlled loop, which is similar
to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop
after executing the body of the loop. Since the body of the loop is executed first and then the
loop condition is checked we can be assured that the body of the loop is executed at least
once.
The syntax of the do while loop is:
do
{
statement;
}
while(expression);
Here the statement is executed, then expression is evaluated. If the condition
expression is true then the body is executed again and this process continues till the
conditional expression becomes false. When the expression becomes false. When the
expression becomes false the loop terminates.
The flow chart of do..while statement
C-NOTES MUTHUGANESH S 45
Example program
/*print n umbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0,n;
clrscr();
printf("Enter the limit");
scanf("%d",&n);
printf("The numbers are ");
do
{
printf("n %d",i);
i++;
}
while(i<=n);
getch();
}
C-NOTES MUTHUGANESH S 46
The Break Statement:
Sometimes while executing a loop it becomes desirable to skip a part of the loop or
quit the loop as soon as certain condition occurs, for example consider searching a particular
number in a set of 100 numbers as soon as the search number is found it is desirable to
terminate the loop. C language permits a jump from one statement to another within a loop as
well as to jump out of the loop. The break statement allows us to accomplish this task. A
break statement provides an early exit from for, while, do and switch constructs. A break
causes the innermost enclosing loop or switch to be exited immediately.
Syntax of break statement
break;
C-NOTES MUTHUGANESH S 47
Continue statement:
During loop operations it may be necessary to skip a part of the body of the loop
under certain conditions. Like the break statement C supports similar statement called
continue statement. The continue statement causes the loop to be continued with the next
C-NOTES MUTHUGANESH S 48
iteration after skipping any statement in between. The continue with the next iteration the
format of the continue statement is simply:
Syntax :
Continue;
Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
C-NOTES MUTHUGANESH S 49
One dimensional Array
A list of items can be given one variable name using only one subscript and such a
variable is called one-dimensional array.
Syntax
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant or
symbolic constant greater than zero and type can be any valid C data type.
Example
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.
Computer reserves five storage locations as shown below
Mark[0]
Mark[1]
Mark[2]
Mark[3]
Mark[4]
 Arrays have 0 as the first index not 1
 If the size of an array is n, to access the last element, (n-1) index is used.
After declaration an array elements to be initialized as follows
 At compile time
 At runtime
At Compile time
It's possible to initialize an array during declaration. For example,
C-NOTES MUTHUGANESH S 50
int mark[5]={40,54,78,90,80};
Another method to initialize array during declaration:
int mark[]={45,67,89,90};
At Runtime
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
/* sorting numbers*/
#include<stdio.h>
#include<conio.h>
# define max 15
void main()
{
int n[6]={52,45,78,100,56,10};
int i,j,temp;
clrscr();
printf("the sorting list are");
for(i=0;i<6;i++)
{
for(j=i+1;j<6;j++)
{
if(n[i]<n[j])
{
temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}
for(i=0;i<6;i++)
{
printf("n%dn",n[i]);
}
getch();
}
C-NOTES MUTHUGANESH S 51
Output
Two Dimentional array
Often there is a need to store and manipulate two dimensional data structure such as
matrices & tables. Here the array has two subscripts. One subscript denotes the row & the
other the column.
The declaration of two dimension arrays is as follows:
data_type array_name[row_size][column_size];
int m[5][6];
Here m is declared as a matrix having 5 rows (numbered from 0 to 4) and 6 columns
(numbered 0 through 5). The first element of the matrix is m [0][0] and the last row last
column is m[4][5].
A two dimensional array marks [4][3] is shown below figure. The first element is
given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and
so on.
marks [0][0]
35.5
Marks [0][1]
40.5
Marks [0][2]
45.5
marks [1][0]
50.5
Marks [1][1]
55.5
Marks [1][2]
60.5
marks [2][0] Marks [2][1] Marks [2][2]
marks [3][0] Marks [3][1] Marks [3][2]
C-NOTES MUTHUGANESH S 52
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to 0 and second row to 1. The initialization is done
row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
By surrounding the elements of each row by braces.
/* Multiarray.c*/
#include<stdio.h>
#include<conio.h>
#define rows 5
#define columns 5
void main()
{
int row,column,product[rows][columns];
int i,j;
clrscr();
printf("Multiplication Table");
for(j=1;j<=columns;j++)
{
printf("%4d",j);
printf("n");
printf("-------------------------");
for(i=0;i<rows;i++)
{
row=i+1;
printf("%2d |",row);
for(j=1;j<=columns;j++)
{
column=j;
product[i][j]=row*column;
printf("%4d",product[i][j]);
}
printf("n");
}
}
getch();
}
OUTPUT
C-NOTES MUTHUGANESH S 53
Multi-dimensional array
C allows arrays of three or more dimensions. The compiler determines the maximum
number of dimension. The general form of a multidimensional array declaration is:
data_type array_name[s1][s2][s3]…..[sn];
Where s is the size of the ith dimension. Some examples are:
int survey[3][5][12];
float table[5][4][5][3];
Strings
A string is a sequence of characters. Any sequence or set of characters defined within
double quotation.
 C Strings are nothing but array of characters ended with null character (‘0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is enclosed by
single quotes in C.
Declaring and initializing string variables
C does not support string as data type. It allows to represent string as character arrays.
The general form of declaration of string variable is
char string_name[size];
Size determines the number of characters in the string name. Its automatically assigns
null character (‘0’) at the end of the string.
Character array may be initialized when they declared as follows
char name[10]=”Madurai”;
We can also declare the size much longer than the string size in the initializer. From
the above statement C permits in computer character array of size 10, place the value
“Madurai” and initializes all elements to null.
Reading Strings from the terminal:
The function scanf with %s format specification is needed to read the character string
from the terminal.
C-NOTES MUTHUGANESH S 54
Example:
char address[15];
scanf(“%s”,address);
Scanf statement has a drawback it just terminates the statement as soon as it finds a blank
space, suppose if we type the string new york then only the string new will be read and since
there is a blank space after word “new” it will terminate the string.
Note that we can use the scanf without the ampersand symbol before the variable name.
Writing strings to screen:
The printf statement along with format specifier %s to print strings on to the screen.
The format %s can be used to display an array of characters that is terminated by the null
character.
Example
printf(“%s”,name);
Can be used to display the entire contents of the array name.
getchar() and putchar()
Single Character functions are used for reading and displaying a single character respectively.
These functions are :
getchar() – reads a character from the keyboard.
putchar() – prints a character to the screen.
Example of getchar() and putchar() :
character = getchar();
The statement 1 reads a character and stores it in variable character.
So, it waits for the character input until a character is typed at the keyboard.
putchar(b);
The statement 2 prints the given character on the screen at the current cursor
position..So, it will display a character (‘b’) on the screen.
Another Example of getchar and putchar :
char ch;
ch = getchar();
C-NOTES MUTHUGANESH S 55
putchar(ch);
The getchar() waits for the character input until a character is typed at the keyboard.
Whatever is stored inside ch, gets displayed on the screen.
gets() and puts() :
The single character functions defined above can handle single character at a time and
cannot handle multiple characters. To solve this problem, there are functions that can handle
strings also. These functions are :
 gets() – accepts a string of characters entered at the keyboard and places them
in the string variable mentioned with it.
 puts() – writes a string on the screen and advances the cursor to the newline.
i.e. it ends with a new line character.
Syntax
char name[15];
gets(name);
 gets() read a string of maximum 15 characters and stores it in memory address
pointed to by ‘name’.
 A null terminator ‘0’ is automatically placed at the end of the string, if the
enter or carriage return is pressed.
puts(name);
whatever stored in name it displays on the screen.
strlen() function:
This function counts and returns the number of characters in a string. The length does
not include a null character.
Syntax
n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
Example
length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.
C-NOTES MUTHUGANESH S 56
strcat() function:
when you combine two strings, you add the characters of one string to the end of
other string. This process is called concatenation. The strcat() function joins 2 strings
together. It takes the following form
Syntax
strcat(string1,string2);
string1 & string2 are character arrays. When the function strcat is executed string2 is
appended to string1. the string at string2 remains unchanged.
strcmp function:
In c you cannot directly compare the value of 2 strings in a condition like
if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are
equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given
below:
Syntax
Strcmp(string1,string2);
String1 & string2 may be string variables or string constants. String1, & string2 may
be string variables or string constants some computers return a negative if the string1 is
alphabetically less than the second and a positive number if the string is greater than the
second.
strcpy() function:
C does not allow you to assign the characters to a string directly as in the statement
name=”Robert”;
Instead use the strcpy(0 function found in most compilers the syntax of the function is
illustrated below.
Syntax
strcpy(string1,string2);
Strcpy function assigns the contents of string2 to string1. string2 may be a character
array variable or a string constant.
C-NOTES MUTHUGANESH S 57
Function & Purpose
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1,’a’);
Returns locate the first occurrence of character ‘m’
strstr(s1,s2);
Searches the string s1 to see wheather the string s2 is contained s1
Example strfunc.c
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char s1[20],s2[20],s3[20],s4='a',s5[25];
int x,y;
clrscr();
C-NOTES MUTHUGANESH S 58
printf("enter 1st string");
scanf("%s",&s1);
printf("Enter 2nd string");
scanf("%s",&s2);
x=strcmp(s1,s2);
if(x==0)
{
printf("Strings are Equaln");
printf("%sn",strcat(s1,s2));
}
else
{
y=strlen(s1);
printf("length of the string%dn",y);
}
if(strchr(s2,s4)==NULL)
{
printf("nsubstring is not found");
}
else
{
printf("nsubstring found");
printf("%s",strcpy(s5,s3));
}
getch();
}
C-NOTES MUTHUGANESH S 59
User-Defined Functions
A function is a complete and independent program which is used (or invoked) by the
main program or other subprograms. A subprogram receives values called arguments from a
calling program, performs calculations and returns the results to the calling program.
The basic philosophy of function is divide and conquer by which a complicated tasks
are successively divided into simpler and more manageable tasks which can be easily
handled. A program can be divided into smaller subprograms that can be developed and
tested successfully.
There are many advantages in using functions in a program they are:
1. It facilitates top down modular programming. In this programming style, the high
level logic of the overall problem is solved first while the details of each lower level
functions is addressed later.
2. The length of the source program can be reduced by using functions at appropriate
places. This factor is critical with microcomputers where memory space is limited.
3. It is easy to locate and isolate a faulty function for further investigation.
4. A function may be used by many other programs this means that a c programmer
can build on what others have already done, instead of starting over from scratch.
5. A program can be used to avoid rewriting the same sequence of code at two or
more locations in a program. This is especially useful if the code involved is long or
complicated.
We already know that C support the use of library functions and use defined
functions. The library functions are used to carry out a number of commonly used operations
or calculations. The user-defined functions are written by the programmer to carry out
various individual tasks.
Functions are used in C for the following reasons:
1. Many programs require that a specific function is repeated many times instead of
writing the function code as many timers as it is required we can write it as a single function
and access the same function again and again as many times as it is required.
2. We can avoid writing redundant program code of some instructions again and
again.
C-NOTES MUTHUGANESH S 60
3. Programs with using functions are compact & easy to understand.
4. Testing and correcting errors is easy because errors are localized and corrected.
5. We can understand the flow of program, and its code easily since the readability is
enhanced while using the functions.
6. A single function written in a program can also be used in other programs also.
In order to make user-defined function, we need to establish three elements that are related
to function.
 Function Definition
 Function Call
 Function Declaration
Function declaration
In C program must be declared before they invoked. It consists of four parts
 Function type (return type)
 Function name
 Parameter list
 Terminating semicolon
General form of function declaration
function_type function_name (parameter list);
Function Definition
A function definition provides the actual body of the function that is specially
written to implement requirements of the functions. In order to invoke to use this function
required place in the function program is called function call. The program that calls the
function is called calling function the calling function that is used to be later in the program
is called function declaration or function prototype.
Definition of the Function is also called function implementation shall include the
following parts
 Function Name
 Function Type
 List of parameters local variables declarations
 Function Statements
 A return statements
C-NOTES MUTHUGANESH S 61
All six parts are grouped into two parts
Function Header (function_type, function_name and parameterlist)
Function Body(local declaration, function statements and return)
The general form of function definition as follows
function _type function_name(parameter_list)
{
local variables declarations;
executable statements;
…………………..;
……………………..;
return statement;
}
Example
int mul(int a,int b)
{
printf (“Enter values”);
scanf(“%d%d”,&a,&b);
return(a*b);
}
Function type
Function type specifies the type of value (like float or double) that function is
expected to return to the program calling function. If the function not explicitly specified, C
will assume that is integer type.
If the function not return anything than we need to specify that the return type as
void.
Function name
The function name is any valid C identifier and therefore must follow the same rules
of formation as other variable name in C.
Parameter list
The parameter list declares the variables that will receive the data sent by calling
program. They serve as input data the function. They represent actual input values and also
called formal parameters. These parameters sent values to the calling programs.
C-NOTES MUTHUGANESH S 62
Return
If function return values it does through the return statement.
The general form of return statement
return
Or
return(expression);
Function calls
Function calls can be called by simple using the function name followed by list of
parameters or arguments, if any enclosed in parentheses
main()
{
int y;
y=mul(10,5);
printf(“%d”,y);
}
Categories of function
 Function with no arguments and no return values
 Function with arguments and no return values
 Function with no arguments and one return value
 Function with no arguments but return a value
 Function that return multiple values
C-NOTES MUTHUGANESH S 63
No arguments and no return values
If function has no values, it does not receive any data from the calling function, when
does not return value, the calling function does not receive any data from the called function.
In simply says there is no data transfer from calling function and called function.
No Input
No output
Fuuntion 2()
{
………………;
…………………;
}
Function 1()
{
………………..;
…………………..;
………………;
Fuuntion 2()
{
………………;
…………………;
}
}
Example funcsum.c
#include<stdio.h>
#include<conio.h>
void sum(); //function declaration
void main()
{
clrscr();
sum(); // function call
getch();
}
void sum(); // function definition
{
int n,r,s=0; // local declaration
printf("Enter the Number"); // statements
scanf("%d",&n);
while(n>0)
C-NOTES MUTHUGANESH S 64
{
r=n%10;
s=s+r;
n=n/10;
}
printf("sum of number%d",s);
}
Output
C-NOTES MUTHUGANESH S 65
Function with arguments and no return values
The main function has no control over the way functions receive input data. We could
make the calling function to read data from terminal and pass it on the called function.
Values of
arguments
No return value
Function 1()
{
………………..;
…………………..;
………………;
Fuuntion 2(a)
{
………………;
…………………;
}
}
Fuuntion 2(f)
{
………………;
…………………;
}
Example funcintr.c
#include<stdio.h>
#include<conio.h>
void printline(char ch);
void intrest(int p,int n);// function declaration with arguments no return value
void main()
{
int p,n;
clrscr();
printf("Enter principle amount");
scanf("%d",&p);
printf("Enter No of Years");
scanf("%d",&n);
printline('*'); //function call with arguments
intrest(p,n); //function call with arguments
printline('-'); //function call with arguments
getch();
}
void printline(char ch) //function definition with arguments no return value
{
C-NOTES MUTHUGANESH S 66
int i;
for(i=1;i<=45;i++)
printf("%c",ch);
printf("n");
}
void intrest(int p,int n) //function definition with arguments no return value
{
float intr,r=0.15;
intr=(p*n*r)/100;
printf("n%fn",intr);
}
output
Function With arguments and one return value
The function value receives data from the calling function through arguments, but
does not send back any value. Rather displays the calculations at the terminal. However we
may not always wish to have the result of function displayed. We may use it the calling
function for further processing.
A self-contained and independent function should behave like ‘black-box’ that receives a
predefined form of input and output a desired value is called two-way communication.
C-NOTES MUTHUGANESH S 67
Values of
arguments
function result
Function 1()
{
………………..;
…………………..;
………………;
Fuuntion 2(a)
{
………………;
…………………;
}
}
Fuuntion 2(f)
{
………………;
…………………;
return;
}
Example funcarea.c
#include<stdio.h>
#include<conio.h>
void printline(char ch, int len);
int sqrarea(int a); //Function declaration With arguments and return value
float cirarea(float r);//Function declaration With arguments and return value
double recarea(float l, float b);//Function declaration With arguments return value
void main()
{
clrscr();
printline('*',50); //function call with value
printf("narea of square %dn",sqrarea(15)); //function call with value
printf("area of circle %fn",cirarea(2.0)); //function call with value
printf("area of rectangle %gn",recarea(3.4,5.6)); //function call with value
printline('@',50); //function call with value
getch();
}
int sqrarea(int a)// function definition with return
{
return(a*a);
}
float cirarea(float r) // function definition with return
{
float pi=3.14;
C-NOTES MUTHUGANESH S 68
return(pi*r*r);
}
double recarea(float l,float b) // function definition with return type
{
return(l*b); //return
}
void printline(char ch,int len)
{
int i;
for(i=1;i<=len;i++)
{
printf("%c",ch);
//printf("n");
}
}
Output
C-NOTES MUTHUGANESH S 69
Function with no arguments but returns value
There we may need to design that may not take any argument but returns a returns value to
the calling function.
Example funceven.c
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int even();
void main()
{
clrscr();
even(); // function calling
getch();
}
int even() // declaration no arguments with return value
{
int n;
printf("Enter n value");
scanf("%d",&n);
if(n%2==0)
printf("the number in even%d",n);
else
printf("the number is odd%d",n);
return 0; //return
}
Output
C-NOTES MUTHUGANESH S 70
Function that returns multiple value
The return statement returns only one value. Suppose we want to get more
information from function. We can achieve this in C using arguments not only to receive
information but also to send back information to the calling function. The arguments that are
used “send out’’ information are called output parameters.
The mechanism of sending back information through arguments is achieved using the
address operator (&) and indirection operator (*).
Example funcmulti.c
#include<stdio.h>
#include<conio.h>
int getvalue(int a, int b, int *product)//function definition using *
{
*product=a*b;
return a+b; //return
}
main()
{
int a,b,s,product;
clrscr();
printf("Enter values");
scanf("%d%d",&a,&b);
s=getvalue(a,b,&product); //function call with &
printf("sum=%dnproduct=%d",s,product);
getch();
}
output
C-NOTES MUTHUGANESH S 71
Recursive function
Recursion is a programming technique that allows the programmer to express
operations in terms of themselves. In C, this takes the form of a function that calls itself. A
useful way to think of recursive functions is to imagine them as a process being performed
where one of the instructions is to "repeat the process".
Example
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int f,n;
clrscr();
printf("Enter the number");
scanf("%d",&n);
f=fact(n); //function call
printf("Factorial value is %d",f);
getch();
}
int fact(int n)
{
int f;
if(n==1)
{
return; //function call itself
}
else
{
f=n*fact(n-1); //recursive function
return f;
}
}
Output
C-NOTES MUTHUGANESH S 72
Call by reference and call by value
There are two ways to pass arguments/parameters to function calls -- call by
value and call by reference. The major difference between call by value and call by reference
is that in call by value a copy of actual arguments is passed to respective formal arguments.
While, in call by reference the location (address) of actual arguments is passed to formal
arguments, hence any change made to formal arguments will also reflect in actual arguments.
Point Call by Value Call by Reference
Copy
Duplicate Copy of Original
Parameter is Passed
Actual Copy of Original Parameter is
Passed
Modification
No effect on Original Parameter
after modifying parameter in
function
Original Parameter gets affected if value
of parameter changed inside function
Example Call by reference swapref.c
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y);
main()
{
int a=100,b=200;
clrscr();
C-NOTES MUTHUGANESH S 73
printf("Before swap, the value of a:%dn",a);
printf("Before swap, the value of b:%dn",b);
swap(&a,&b);
printf("After swap, value of a:%dn",a);
printf("After swap, value of b:%dn",b);
getch();
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output
Rules for pass by pointers
 The types of actual and formal arguments must be same.
 The actual arguments (in the function call) must be the addresses of variables that the local to
the calling function.
 The formal arguments in the function header must be prefixed by the indirection operatior *.
 In the prototype, the arguments must be prfixed by the symbol *.
 To access the value of actual arguments in the called function, we must use the
corrresponding formal argument prefixed with the indirection operator.
C-NOTES MUTHUGANESH S 74
Example call by value swapval.c
#include<stdio.h>
#include<conio.h>
void swap(int x,int y);
main()
{
int a=100,b=200;
clrscr();
printf("Before swap, the value of a:%dn",a);
printf("Before swap, the value of b:%dn",b);
swap(a,b);
printf("After swap, value of a:%dn",a);
printf("After swap, value of b:%dn",b);
getch();
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Output
Nesting of function
C permits nesting function freely. Main can call funtion1, which calls function2, which calls
funtion3,…………. And so on. There is in principle no limit as to how deeply functions can be
nested.
#include<stdio.h>
#include<conio.h>
float add(int x,int y,int z);
int diff(int x,int y);
void main()
{
int a,b,c;
clrscr();
printf("please Enter Values");
scanf("%d%d%d",&a,&b,&c);
C-NOTES MUTHUGANESH S 75
printf("%dn",add(a,b,c));
getch();
}
float add(int x,int y,int z)
{
if(diff(x,y))
return(x/(y-z));
else
return (0);
}
int diff(int p,int q)
{
if(p!=q)
return(1);
else
return(0);
}
Passing arrays to function
Like values of simple variables, it is also to pass the value of an array to function. To pass an array to
called function, its sufficient to list the name of the array,without any subscripts, and the size of array
as arguments.
 The function must be called bypassing only the name of the array
 In the function definition the formal parameter must be an array type the size of array does
not need to be specified.
 The function prototype must show that argument is array
Example Funcarr.c
#include<stdio.h>
#include<conio.h>
float avg(int marks[], int size);
void main()
{
int i;
int marks[10],size;
clrscr();
printf("Enter your number of subject to enter");
scanf("%d",&size);
printf("Enter the marks");
for(i=0;i<size;i++)
{
scanf("%d",&marks[i]);
}
printf("%f",avg(marks,size));
getch();
}
float avg(int marks[],int size)
{
int tot=0,i;
for(i=0;i<size;i++)
{
C-NOTES MUTHUGANESH S 76
tot=tot+marks[i];
}
return(tot/size);
}
Output
Passing as two dimentional array
 The function must be called bypassing only the name of the array
 In the function definition the formal parameter must be an array has two-dimentional by
including two set of brackets.
 The size of second dimention must be specified
 The function prototype should be similar to the function header.
Example
double average(int x[][n],int m,int n) //function defintion
{
int i,j;
double sum=0;
}
main()
{
int m=3,n=2;
double average(int [][n],int int); //function declaration
double mean;
C-NOTES MUTHUGANESH S 77
int matrix[m][n]={{1,2},{3,4},{5,6}};
mean=average(matrix,m,n); // function call
}
Passing srtrings to functions
The strings are treated as character arrray in C and therefore rules are same to functions as similar to
passings array to functions.
The strings to be passed must be declared as formal argument of the function when its defined.
void display(char name[])
{
Statements;
}
The function prototype must be show the arrguments is string
void display(char str[]);
the call function must have a string array name without subscript as actual argument.
void display(name);
The scope, visiblity, and life time ofthe varriables
Variables in C differ in behaviour from those in most in other languages. In C not only do all
variables have data type, they must also have a storage class
The following storage classes are most oftenly used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Registervariables
Automatic variables
The auto storage class is the default storage class for all local variables.
Scope: Local to the method block in which the variable is defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of method block where the variable is defined.
A variable declared inside a function without any storage class specification, is by default
an automatic variable. They are created when a function is called and are
destroyed automatically when the function exits. Automatic variables can also be called
C-NOTES MUTHUGANESH S 78
local variables because they are local to a function. By default they are assigned garbage
value by the compiler.
Syntax
auto int n;
Example
void main()
{
int detail;
or
auto int detail; //Both are same
}
External variables
Scope: Global. When you have multiple files and you define a global variable or function,
which will also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to declare a
global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below.
Default initial value: 0(zero).
Lifetime: Till the whole program doesn't finish its execution.
A variable that is declared outside any function is a Global Variable. Global variables
remain available throughout the entire program. By default, initial value of the Global
variable is 0(zero). One important thing to remember about global variable is that their values
can be changed by any function in the program.
Syntax
extern int a;
#include<stdio.h>
int number; // by default global variable
void main()
{
extern int a; // by declared as global variable using extern
getch();
C-NOTES MUTHUGANESH S 79
}
Static variable
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
A static variable tells the compiler to persist the variable until the end of program. Instead of
creating and destroying a variable every time when it comes into and goes out of
scope, static is initialized only once and remains into existence till the end of program. A
static variable can either be internal or external depending upon the place of declaraction.
Scope of internal staticvariable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.
Syntax
static int a;
Example
void test();
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%dt",a);
}
C-NOTES MUTHUGANESH S 80
output :
1 2 3
Registervariable
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of method block, where the variable is defined, doesn't finish its
execution.
Register variable inform the compiler to store the variable in CPU register instead of
memory. Register variable has faster access than normal variable. Frequently used variables
are kept in register. Only few variables can be placed inside register. An application of
register storage class can be in using loops, where the variable gets used a number of times in
the program.
We can never get the address of such variables.
Syntax :
register int number;
Note: Even though we have declared the storage class of variable number as register, we
cannot surely say that the value of the variable would be stored in a register. This is because
the number of registers in a CPU are limited. Also, CPU registers are meant to do a lot of
important work.Thus, sometimes it may not be free. In such scenario, the variable works as if
its storage class is auto.
C-NOTES MUTHUGANESH S 81
STRUCTURE
structure is another user defined data type available in C that allows to combine data
items of different kinds.
A structure is a user defined data type in C. A structure creates a data type that can be
used to group items of possibly different types into a single type.
struct keyword is used to define a structure. struct defines a new data type which is a
collection of primary and derived datatypes.
Syntax:
struct structure_tag
{
//member variable 1
//member variable 2
//member variable 3
...
};structure_variables
Example of Structure
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
int m1,m2,m3;
float avg;
};
Here struct Student declares a structure to hold the details of a student which consists
of 4 data fields, namely name, age, branch, gender, marks(1,2 and 3) and average. These
fields are called structure elements or members.
C-NOTES MUTHUGANESH S 82
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition
or after the structure is defined. Structure variable declaration is similar to the declaration of
any normal variable of any other datatype. Structure variables can be declared in following
two ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
int m1,m2,m3;
float avg;
};
struct Student S1, S2; //declaring variables of struct Student
2) Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
int m1,m2,m3;
float avg;
}S1, S2;
Here S1 and S2 are variables of structure Student
C-NOTES MUTHUGANESH S 83
Accessing Structure Members
Structure members can be accessed and assigned values in a number of ways.
Structure members have no meaning individually without the structure. In order to assign a
value to any structure member, the member name must be linked with the structure variable
using a dot(.) operator also called period or member access operator.
include<stdio.h>
#include<conio.h>
struct student
{
char name[30];
int age;
};
void main()
{
struct student s;
clrscr();
printf("Enter your Name");
scanf("%s",&s.name);
printf("Enter your age");
scanf("%d",&s.age);
printf("Hai Mr.%s welcome your age is %d",s.name,s.age);
getch();
}
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s.name);
scanf(" %d ", &s.age);
C-NOTES MUTHUGANESH S 84
Output
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at
compile time.
struct student
{
float height;
int weight;
int age;
};
struct student s1 = { 180.75 , 73, 23 }; //initialization
or,
struct student s1;
s1.height = 180.75; //initialization of each member separately
s1.weight = 73;
s1.age = 23;
C-NOTES MUTHUGANESH S 85
Nested Structures
Nesting of structures, is also permitted in C language. Nested structures means,that one
structure has another stucture as member variable.
Example:
struct Student
{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
Structure as Function Arguments
We can pass a structure as a function argument just like we pass any other variable or an
array as a function argument.
Example:
#include<stdio.h>
struct Student
{
char name[10];
int roll;
};
void show(struct Student st);
void main()
{
struct Student std;
printf("nEnter Student record:n");
printf("nStudent name:t");
scanf("%s", std.name);
C-NOTES MUTHUGANESH S 86
printf("nEnter Student rollno.:t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("nstudent name is %s", st.name);
printf("nroll is %d", st.roll);
}
Unions
Unions are conceptually similar to structures. The syntax to declare/define a union is also
similar to that of a structure. The only differences is in terms of storage. In structure each member has
its own storage location, whereas all members of union uses a single shared memory location which
is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot
handle all the members at the same time. A union is declared using the union keyword.
C-NOTES MUTHUGANESH S 87
union hai
{
int m;
float x;
char c;
}h;
Accessing a Union Member in C
Syntax for accessing any union member is similar to accessing structure members,
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
Pointer
A Pointer in C language is a variable which holds the address of another variable of
same data type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language.
Concept of Pointers
Whenever a variable is declared in a program, system allocates a location i.e an
address to that variable in the memory, to hold the assigned value. This location has its own
address number, which we just saw above.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10;
C-NOTES MUTHUGANESH S 88
We can access the value 10 either by using the variable name a or by using its address 80F.
The variables which are used to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other
variable. And the value of a pointer variable gets stored in another memory location.
Benefits of using pointers
Below we have listed a few benefits of using pointers:
1. Pointers are more efficient in handling Arrays and Structures.
2. Pointers allow references to function and thereby helps in passing of function as
arguments to other functions.
3. It reduces length of the program and its execution time as well.
4. It allows C language to support Dynamic Memory management.
Declaration of C Pointer variable
General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. void type pointer works with all data types, but is not often used.
Here are a few examples:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
C-NOTES MUTHUGANESH S 89
Initialization of C Pointer variable
Pointer Initialization is the process of assigning address of a variable to a pointer
variable. Pointer variable can only contain address of a variable of the same data type. In C
language address operator & is used to determine the address of a variable. The &
(immediately preceding a variable name) returns the address of the variable associated with
it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variable always point to variables of same datatype. Let's have an example to
showcase this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULL value is called a NULL pointer.
C-NOTES MUTHUGANESH S 90
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
Points to remember while using pointers
1. While declaring/initializing the pointer variable, * indicates that the variable is a
pointer.
2. The address of any variable is given by preceding the variable name with
Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't
mean that a is going to contain an integer value. It means that a is going to contain the
address of a variable storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here,
the * can be read as 'value at'.
Pointer and Arrays in C
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:
C-NOTES MUTHUGANESH S 91
Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of the array and it acts as a pointer pointing towards the first
element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to
another.
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that pointer
to access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
We can also use the Base address (a in above case) to act as a pointer and print all the values
C-NOTES MUTHUGANESH S 92
Pointer and Character strings
Pointer can also be used to create strings. Pointer variables of char type are treated as
string.
char *str = "Hello";
The above code creates a string and stores its address in the pointer variable str. The
pointer str now points to the first character of the string "Hello". Another important thing to
note here is that the string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
Pointer to Array of Structures in C
Like we have array of integers, array of pointers etc,we can also have array of structure
variables. And to use the array of structure variables efficiently, we use pointers of structure type. We
can also have pointer to a single structure variable, but it is mostly used when we are dealing with
array of structure variables.
C-NOTES MUTHUGANESH S 93
#include <stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
Accessing Structure Members with Pointer
To access members of structure using the structure variable, we used the dot . operator. But
when we have a pointer of structure type, we use arrow -> to access structure members.
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"ProgramminginC", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %sn", ptr->name);
printf("NUMBER: %dn", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
C-NOTES MUTHUGANESH S 94
FILE
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer offile type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function Description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
Opening a File or Creating a File
The fopen() function is used to create a new file or to open an existing file.
General Syntax:
fp = FILE fopen(“filename”, “mode”);
C-NOTES MUTHUGANESH S 95
filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types,
mode Description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
fclose(filename);
Here fclose() function closes the file and returns zero on success,or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char name[35];
int age;
FILE *f1;
clrscr();
f1=fopen("first","w");
printf("Writting to the file");
scanf("%s",name);
scanf("%d",&age);
fclose(f1);
f1=fopen("first","r");
C-NOTES MUTHUGANESH S 96
printf("Name:%s",name);
printf("Age%d",age);
fclose(f1);
getch();

More Related Content

What's hot

Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSBESTECH SOLUTIONS
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpen Gurukul
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Rumman Ansari
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILEDipta Saha
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for EngineeringVincenzo De Florio
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers Appili Vamsi Krishna
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programmingRumman Ansari
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingRutvik Pensionwar
 
Basic Structure of C Language and Related Term
Basic Structure of C Language  and Related TermBasic Structure of C Language  and Related Term
Basic Structure of C Language and Related TermMuhammadWaseem305
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c languageIndia
 

What's hot (20)

C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Structure
StructureStructure
Structure
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
C LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONSC LANGUAGE - BESTECH SOLUTIONS
C LANGUAGE - BESTECH SOLUTIONS
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
C language for Semester Exams for Engineers
C language for Semester Exams for Engineers C language for Semester Exams for Engineers
C language for Semester Exams for Engineers
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programming
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Casa lab manual
Casa lab manualCasa lab manual
Casa lab manual
 
Basic Structure of C Language and Related Term
Basic Structure of C Language  and Related TermBasic Structure of C Language  and Related Term
Basic Structure of C Language and Related Term
 
C tutorial
C tutorialC tutorial
C tutorial
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
 

Similar to Cnotes

Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
Copy of UNIT 2 -- Basics Of Programming.pptx
Copy of UNIT 2 -- Basics Of Programming.pptxCopy of UNIT 2 -- Basics Of Programming.pptx
Copy of UNIT 2 -- Basics Of Programming.pptxrahulrajbhar06478
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centrejatin batra
 
Diploma ii cfpc u-2 datatypes and variables in c language
Diploma ii  cfpc u-2 datatypes and variables in c languageDiploma ii  cfpc u-2 datatypes and variables in c language
Diploma ii cfpc u-2 datatypes and variables in c languageRai University
 
Mca i pic u-2 datatypes and variables in c language
Mca i pic u-2 datatypes and variables in c languageMca i pic u-2 datatypes and variables in c language
Mca i pic u-2 datatypes and variables in c languageRai University
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c languageRai University
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programmingMithun DSouza
 
Btech i pic u-2 datatypes and variables in c language
Btech i pic u-2 datatypes and variables in c languageBtech i pic u-2 datatypes and variables in c language
Btech i pic u-2 datatypes and variables in c languageRai University
 
Bsc cs i pic u-2 datatypes and variables in c language
Bsc cs i pic u-2 datatypes and variables in c languageBsc cs i pic u-2 datatypes and variables in c language
Bsc cs i pic u-2 datatypes and variables in c languageRai University
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptxmadhurij54
 

Similar to Cnotes (20)

C introduction
C introductionC introduction
C introduction
 
Module 1 PCD.docx
Module 1 PCD.docxModule 1 PCD.docx
Module 1 PCD.docx
 
fds unit1.docx
fds unit1.docxfds unit1.docx
fds unit1.docx
 
C Language
C LanguageC Language
C Language
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Copy of UNIT 2 -- Basics Of Programming.pptx
Copy of UNIT 2 -- Basics Of Programming.pptxCopy of UNIT 2 -- Basics Of Programming.pptx
Copy of UNIT 2 -- Basics Of Programming.pptx
 
C notes
C notesC notes
C notes
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centre
 
Diploma ii cfpc u-2 datatypes and variables in c language
Diploma ii  cfpc u-2 datatypes and variables in c languageDiploma ii  cfpc u-2 datatypes and variables in c language
Diploma ii cfpc u-2 datatypes and variables in c language
 
Mca i pic u-2 datatypes and variables in c language
Mca i pic u-2 datatypes and variables in c languageMca i pic u-2 datatypes and variables in c language
Mca i pic u-2 datatypes and variables in c language
 
datatypes and variables in c language
 datatypes and variables in c language datatypes and variables in c language
datatypes and variables in c language
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
Btech i pic u-2 datatypes and variables in c language
Btech i pic u-2 datatypes and variables in c languageBtech i pic u-2 datatypes and variables in c language
Btech i pic u-2 datatypes and variables in c language
 
Bsc cs i pic u-2 datatypes and variables in c language
Bsc cs i pic u-2 datatypes and variables in c languageBsc cs i pic u-2 datatypes and variables in c language
Bsc cs i pic u-2 datatypes and variables in c language
 
UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
 
Aniket tore
Aniket toreAniket tore
Aniket tore
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptx
 
C LANGUAGE NOTES
C LANGUAGE NOTESC LANGUAGE NOTES
C LANGUAGE NOTES
 
C
CC
C
 

More from Muthuganesh S

More from Muthuganesh S (11)

javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptx
 
OR
OROR
OR
 
Operation Research VS Software Engineering
Operation Research VS Software EngineeringOperation Research VS Software Engineering
Operation Research VS Software Engineering
 
CSS
CSSCSS
CSS
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
Php notes
Php notesPhp notes
Php notes
 
Php Basics Iterations, looping
Php Basics Iterations, loopingPhp Basics Iterations, looping
Php Basics Iterations, looping
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php
PhpPhp
Php
 
Javascript dom
Javascript domJavascript dom
Javascript dom
 

Recently uploaded

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 

Recently uploaded (20)

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 

Cnotes

  • 1. C NOTES EDITED BY S.MUTHUGANESH M.Sc.,B.Ed., ASSISTANT PROFESSOR OF COMPUTER SCIENCE VIVEKANANDA COLLEGE
  • 2. C-NOTES MUTHUGANESH S 1 Introduction C is a powerful, flexible, portable and elegantly structured programming language. Since C combines the features of high-level language with the elements of the assembler, it is suitable for both system and application programming language. History of c 1960 International Group 1967 Martin Richards 1970 Ken Thompson 1972 Dennis Richie Kernighen and Richie 1978 ANSI Committee 1989 1990 ISO Committee 1999 Standardization Committee ALGOL BCPL B TRADITIONAL C K&R C ANSI ISO C ANSI C C99
  • 3. C-NOTES MUTHUGANESH S 2 Importance of C The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of build-in functions and operators can be used to write any complex program. The C compilers combines the capabilities of an assembly language with the features of a high-level language and therefore it is well suited for writing both system software and business packages. In fact, many of the C compilers available in the market are written in C. The main importance of C are listed below.  Program written in C are efficient and fast due to variety of data types and powerful operators  It provides various build-in functions.  C is highly portable. The C program written in one computer with one operating system can be run into another computer with another operating system. That means program written in Windows can run in Linux or Unix as well with no or little modifications.  C programming can be viewed as the collections of modules so it is highly structured.  The modular programming makes testing and debugging easier.  C has ability to extend itself.
  • 4. C-NOTES MUTHUGANESH S 3 Basic structures of C 1. Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use. 2. Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include<stdio.h> 3. Definition section: The definition section defines all symbolic constants such using the #define max 10. 4. Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. 5. main () function section: Every C program must have one main function section. This section contains two parts; declaration part and executable part 1. Declaration part: The declaration part declares all variables used in the executable part.
  • 5. C-NOTES MUTHUGANESH S 4 2. Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. It begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. 6. Subprogram section: If the program is then the subprogram section contains all that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order. Example Program /*Documentation Section: program to find the area of circle*/ #include <stdio.h> /*link section*/ #include <conio.h> /*link section*/ #define PI 3.14 /*definition section*/ float area; /*global declaration section*/ void main() { float r; /*declaration part*/ printf("Enter the radius of the circlen"); /*executable part starts here*/ scanf("%f",&r); area=PI*r*r; printf("Area of the circle=%f",area); getch(); }
  • 6. C-NOTES MUTHUGANESH S 5 C Library Some functions are written by users, like us are stored in library. Library functions are grouped category-wised and stored in different files known as header files. If you want to access the functions from the library its necessary to tell compiler this achieved by using preprocessor directive #include<filename.h> A header file is a file with extension .h Example #include<stdio.h> Header Files This is a list of the header files that you can include in your program if you want to use the functions available in the C standard library: Header File Type of Functions <assert.h> Diagnostics Functions <ctype.h> Character Handling Functions <math.h> Mathematics Functions <setjmp.h> Nonlocal Jump Functions <signal.h> Signal Handling Functions <stdio.h> Input/Output Functions <stdlib.h> General Utility Functions <string.h> String Functions <time.h> Date and Time Functions
  • 7. C-NOTES MUTHUGANESH S 6 Constants, Variables, and Data Types Introduction The task of processing of data is accomplished by executing a sequence of instruction is called Program. These instructions are formed using certain symbols and words according to some rules known as SYNTAX or Grammar. C has own vocabulary and grammar they are constants, variable and their types related to C programming language. Characterset The characters that can be used form words, numbers and expression depend upon the computer on which program is run. The characters in C are grouped into following categories Letters Digits Special characters White spaces The character set is the fundamental raw material of any language and they are used to represent information. Like natural languages, computer language will also have well defined character set, which is useful to build the programs. ALPHABETS Uppercase letters A-Z Lowercase letters a-z DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 SPECIAL CHARACTERS ~ tilde % percent sign | vertical bar @ at symbol + plus sign < less than _ underscore - minus sign > greater than ^ caret # number sign = equal to & ampersand $ dollar sign / slash ( left parenthesis * asterisk back slash ) right parenthesis ′ apostrophe : colon [ left bracket
  • 8. C-NOTES MUTHUGANESH S 7 " quotation mark ; semicolon ] right bracket ! exclamation mark , comma { left flower brace ? Question mark . dot operator } right flower brace WHITESPACE CHARACTERS b blank space t horizontal tab v vertical tab r carriage return f form feed n new line Back slash ’ Single quote " Double quote ? Question mark 0 Null a Alarm (bell) C Tokens In a passage of text, individual words and punctuation marks are called tokens or lexical units. Similarly, the smallest individual unit in a c program is known as a token or a lexical unit. C tokens can be classified as follows: 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special Symbols 6. Operators Keywords C keywords have fixed meanings and these meanings cannot be changed. The keywords cannot be used as variable names. C has 32 key words they are
  • 9. C-NOTES MUTHUGANESH S 8 The list of C keywords is given below: auto Break Case Char const continue Default Do Double else enum Extern Float For goto If Int Long register return short Signed Sizeof static struct switch Typedef Union unsigned void volatile While Identifiers Identifiers are used as the general terminology for the names of variables, functions and arrays. These are user defined names consisting of long sequence of letters and digits with either a letter or the underscore (_) as a first character. There are certain rules that should be followed while naming C identifiers:  They must begin with a letter or underscore (_).  They must consist of only letters, digits, or underscore. No other special character is allowed.  It should not be a keyword.  It must not contain white space.  It should be up to 31 characters long as only first 31 characters are significant. Some examples of c identifiers:
  • 10. C-NOTES MUTHUGANESH S 9 Name Remark _A9 Valid Temp.var Invalid as it contains special character other than the underscore void Invalid as it is a keyword C Constants C constants refers to the data items that do not change their value during the program execution. Several types of C constants that are allowed in C are: IntegerConstants Integer constants are whole numbers without any fractional part. It must have at least one digit and may contain either + or – sign. A number with no sign is assumed to be positive. There are three types of integer constants: DecimalIntegerConstants Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign. Example of valid decimal integer constants 341, -341, 0, 8972 OctalInteger Constants Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said to be octal integer constants. Example of valid octal integer constants 010, 0424, 0, 0540 HexadecimalInteger Constants Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or 0X. They may also include alphabets from A to F representing numbers 10 to 15. Example of valid hexadecimal integer constants 0xD, 0X8d, 0X, 0xbD
  • 11. C-NOTES MUTHUGANESH S 10 It should be noted that, octal and hexadecimal integer constants are rarely used in programming. RealConstants The numbers having fractional parts are called real or floating point constants. These may be represented in one of the two forms called fractional form or the exponent form and may also have either + or – sign preceding it. Example of valid real constants in fractional form or decimal notation 0.05, -0.905, 562.05, 0.015 Representing a real constantin exponent form The general format in which a real number may be represented in exponential or scientific form is mantissa e exponent The mantissa must be either an integer or a real number expressed in decimal notation. The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E And, the exponent must be an integer. Examples of valid real constants in exponent form are: 252E85, 0.15E-10, -3e+8 CharacterConstants A character constant contains one single character enclosed within single quotes. Examples of valid character constants ‘a’ , ‘Z’, ‘5’ It should be noted that character constants have numerical values known as ASCII values, for example, the value of ‘A’ is 65 which is its ASCII value. Escape Characters/Escape Sequences C allows us to have certain non graphic characters in character constants. Non graphic characters are those characters that cannot be typed directly from keyboard, for example, tabs, carriage return, etc. These non graphic characters can be represented by using escape sequences represented by a backslash () followed by one or more characters. NOTE: An escape sequence consumes only one byte of space as it represents a single character.
  • 12. C-NOTES MUTHUGANESH S 11 Escape Sequence Description A Audible alert(bell) B Backspace F Form feed N New line R Carriage return T Horizontal tab V Vertical tab Backslash “ Double quotation mark ‘ Single quotation mark ? Question mark Null String Constants String constants are sequence of characters enclosed within double quotes. For example, “hello” “abc” “hello911” Every sting constant is automatically terminated with a special character ‘’ called the null character which represents the end of the string. For example, “hello” will represent “hello” in the memory. Thus, the size of the string is the total number of characters plus one for the null character.
  • 13. C-NOTES MUTHUGANESH S 12 SpecialSymbols The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose. [] () {} , ; : * … = # Braces{}: These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement. Parentheses(): These special symbols are used to indicate function calls and function parameters. Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts. Data types  C language has rich data type. Used to storage representations and machine instructions.  Data types specify how we enter data into our programs and what type of data we enter. C supports three classes of data types
  • 14. C-NOTES MUTHUGANESH S 13 The following table provides the details with their storage sizes and value ranges − Type Storage size Value range Char 1 byte -128 to 127 or0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 Int 2 or4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 unsigned int 2 or4 bytes 0 to 65,535 or0 to 4,294,967,295 Short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 Long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 Integer type  Integer data type allows a variable to store numeric values.  “int” keyword is used to refer integer data type.  The storage size of int data type is 2 or 4 or 8 byte.  It varies depend upon the processor in the CPU that we use.
  • 15. C-NOTES MUTHUGANESH S 14  Integers occupy one word of storage(depending on machines)  If 16 bit the size of the integer value is limited range is -32768 to +32767.  C has three classes of integer storage namely short int, int and long int in both signed and unsigned. int a=2; C stores like one word as 8-bit(1byte) 0 0 0 0 0 0 1 0 FLOATING POINT DATA TYPE: Floating point data type consists of 2 types. They are, 1. float 2. double 1. FLOAT:  Float data type allows a variable to store decimal values.  Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type.  We can use up-to 6 digits after decimal using float data type.  For example, 10.456789 can be stored in a variable using float data type. 2. DOUBLE:  Double data type is also same as float data type which allows up-to 15 digits after decimal.  Storage size of float data type is 8  Long Storage size of float data type is 10  The range for double data type is from 1E–37 to 1E+37. Long int 4byte Int2byte Short int 1b
  • 16. C-NOTES MUTHUGANESH S 15 Void Void has no values. This is usually used to specify the type of function. The type of function is said to be void when it does not return value to calling function. Character type Character types are used to store characters value. Size and range of Integer type on 16-bit machine Type Size(bytes) Range char or signed char 1 -128 to 127 unsigned char 1 0 to 255 Variables in C Language The naming of an address is known as variable. Variable is the name of memory location. Unlike constant, variables are changeable, we can change value of a variable during execution of a program. A programmer can choose a meaningful variable name. Example : average, height, age, total etc. Rules to define variable name  Variable name must not start with a digit.  Variable name can consist of alphabets, digits and special symbols like underscore.  Blank or spaces are not allowed in variable name.  Keywords are not allowed as variable name. Declarationand Definition of variable Declaration of variables must be done before they are used in the program. Declaration does two things.  It tells the compiler what the variable name is.  It specifies what type of data the variable will hold. Long double double float
  • 17. C-NOTES MUTHUGANESH S 16 Definition of variable means to assign a value to a variable. Definition specify what code or data the variable describes. A variable must be declared before it can be defined. SYNTAX datatype v1,v2,v3,……vn; int a; Assigning value of variable int a; a=5; /*---------------Sample program-------------*/ #include<stdio.h> #include<conio.h> void main() { char name[25]; int n,c,dig,dm,tot,rollno; float avg; clrscr(); printf("Enter your name"); scanf("%s",&name); printf("Enter Your Rollno"); scanf("%d",&rollno); printf("Enter Your Marks One by One like C,DIG,DMn"); scanf("%d",&c); scanf("%d",&dig); scanf("%d",&dm); tot=c+dig+dm; avg=tot/3; printf("Hi Mr.%s Your Rollno is %d You get Marks in Your Subjectsn C=t%dnDig=t%dnDM=t%dn",name,rollno,c,dig,dm); printf("Your Total is %d and Average is %f",tot,avg); getch();
  • 18. C-NOTES MUTHUGANESH S 17 } After the execute the program the output will appear User-Defined Data Types: C supports the features “typedef” that allows users to define the identifier which would represent an existing data type. This defined data type can then be used to declare variables: Syntax: typedef int numbers; numbers num1,num2; In this example, num1 and num2 are declared as int variables. The main advantage of user defined data type is that it increases the program’s readability. Another type is enumerated type. This is also a user defined data type
  • 19. C-NOTES MUTHUGANESH S 18 Syntax: enum identifier {value1,value2, value 3,…} “Enum” is the keyword and “identifier” is the user defined data type that is used to declare the variables. It can have any value enclosed within the curly braces. For example: enum day {January, February,March,April,..}; enum day month_st,month_end; The compiler automatically assigns integer digits beginning from 0 to all the enumeration constants. For example, “January ” will have value 0 assigned, “February” value 1 assigned and so on. You can also explicitly assign the enumeration constants. Operator An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −  Arithmetic Operators  Relational Operators  Logical Operators  Bitwise Operators  Assignment Operators  Increment and Decrement operators  Conditional operator  Special operator Arithmetic operator An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication on numerical values (constants and variables).
  • 20. C-NOTES MUTHUGANESH S 19 Operator Meaning of Operator + addition or unary plus - subtraction or unary minus * Multiplication / Division % remainder after division( modulo division) /*----------------operator example programs-------------------*/ #include<stdio.h> #include<conio.h> void main() { int a=5,b=4,c; c=a+b; clrscr(); printf("a+b= %dn",c); c=a-b; printf("a-b= %dn",c); c=a*b; printf("a*b= %dn",c); c=a/b; printf("a/b= %dn",c); c=a%b; printf("amodulb= %dn",c); getch(); } Output:
  • 21. C-NOTES MUTHUGANESH S 20 Increment and decrement operators C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand. a=5; a++; act as a=a+1; a--; act as a=a-1; Suppose you use ++ operator as prefix like: ++var. The value of var is incremented by 1 then, it returns the value. Suppose you use ++ operator as postfix like: var++. The original value of var is returned first then, var is incremented by 1. Relational Operators Weoften compare two quantities and depending ontheir relation, take certain decisions. The following table shows all the relational operators supported by C.
  • 22. C-NOTES MUTHUGANESH S 21 Operator Description == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. LogicalOperators The logical operators are used when we want test more than one condition. Following table shows all the logical operators supported by C language.
  • 23. C-NOTES MUTHUGANESH S 22 Operator Description && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. The if...else statement executes some code if the test expression is true (nonzero) then body of if statements will be executed otherwise the false statement else statements executes . Assignment Operators The assignment operators are used to assign values result of an expression to a variable.The following table lists the assignment operators supported by the C language – Operator Description Example = Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C += Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
  • 24. C-NOTES MUTHUGANESH S 23 -= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A Bitwise operators Bitwise operators are used in C programming to perform bit-level operations. These operators are used for testing the bits, or shifting them right or left. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left
  • 25. C-NOTES MUTHUGANESH S 24 Operators Meaning of operators >> Shift right Comma Operator Comma operators are used to link related expressions together. For example: int a, c = 5, d; The size of operator Its compile time operator,To get the exact size of a type or a variable on a particular platform, youcan use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Conditional operator A conditional operator is a ternary operator, that is, it works on 3 operands. Conditional OperatorSyntax conditionalExpression ? expression1 : expression2 The conditional operator works as follows:  The first expression conditional Expression is evaluated first. This expression evaluates to 1 if it's true and evaluates to 0 if it's false.  If conditional Expression is true, expression1 is evaluated.  If conditional Expression is false, expression2 is evaluated. /*------------conditional.c---------------------*/ #include<stdio.h> #include<conio.h> void main() { int num; clrscr();
  • 26. C-NOTES MUTHUGANESH S 25 printf("Enter the number"); scanf("%d",&num); ((num%2==0)?printf("even"):printf("odd")); getch(); } Storage class Storage class that provides information about their location and visibility. C has four different types of Storage Class. Storage class Meaning Auto Local variable known only to the function in which declared Static Local variable which exists and retains its values even after control transferred to the calling function. Extern Global variable known to all function in the file. Register Local variable which is stored to register.
  • 27. C-NOTES MUTHUGANESH S 26 Operator precedence in C Operator Description Associativity ( ) [ ] . -> ++ -- Parentheses (function call) (see Note 1) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement (see Note 2) left-to-right ++ -- + - ! ~ (type) * & sizeof Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (convert value to temporary value of type) Dereference Address (of operand) Determine size in bytes on this implementation right-to-left * / % Multiplication/division/modulus left-to-right + - Addition/subtraction left-to-right << >> Bitwise shift left, Bitwise shift right left-to-right < <= > >= Relational less than/less than or equal to Relational greater than/greater than or equal to left-to-right == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right | | Logical OR left-to-right ? : Ternary conditional right-to-left = += -= *= /= %= &= ^= |= <<= >>= Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment right-to-left , Comma (separate expressions) left-to-right
  • 28. C-NOTES MUTHUGANESH S 27 scanf Usually input statement is used in C is scanf() Syntax scanf (“control string”, &v1,&v2,&v3,…&vn);  The control string must be a text enclosed in double quotes.  It contains the data format of data being received.  The ampersand & before each variable is an operator that specified the variable’s names address and connecting it into internal representation in memory.  Example for control string : integer (%d) , float (%f) , character (%c) or string (%s).  Format specification contained in the control string should match the argument order. Printf()  printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen.  We use printf() function with %d , %f, %s format specifier to display the value of an variable.  To generate a newline,we use “n” in printf() statement. Syntax printf (“outputstring identifiers(like %s,%d)”, variablenames); Example printf(“hai hello%s”,name); Format Specifier Description %c Accepts and prints characters %d Accepts and prints signed integer %e or %E Scientific notation of floats %f Accepts and prints float numbers %i Accepts and prints integer values
  • 29. C-NOTES MUTHUGANESH S 28 Format Specifier Description %l or %ld or %li Long integer values %lf Double values %Lf Long double values %lu Unsigned int or unsigned long %o Provides the octal form of representation %s Accepts and prints String values %u Accepts and prints unsigned int %x or %X Provides the hexadecimal form of representation getchar() getchar is a function in C programming language that reads a single character. getchar() function is used to get/read a character from keyboard input. When this statement encountered the computer waits until key is pressed. Syntax Variable_name=getchar(); Example char name; name = getchar(); putchar() putchar() function is a file handling function in C programming language which is used to write a character on standard output/screen. Syntax putchar(variablename); Example Choice=’y’; putchar(Choice);
  • 30. C-NOTES MUTHUGANESH S 29 Decision Making and Branching We want to executes some certain statements executes certain conditions are met. This involves a kind of particular decision making to see whether a particular condition has occurred or not then the computer to execute certain statements accordingly. C language possess such decision-making capabilities by supporting the following statements 1. If statement 2. Switch statement 3. Conditional operator statement 4. Goto statement if Statement: The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program execution. The If structure has the following syntax if (test expression) { body of the statement; } Statement-x; The if statement evaluates the test expression inside the parenthesis. If the test expression is evaluated to true (nonzero), statements inside the body of if is executed. If the test expression is evaluated to false (0), statements inside the body of if is skipped from execution.
  • 31. C-NOTES MUTHUGANESH S 30 if...else statement The if...else statement executes some code if the test expression is true (nonzero) and some other code if the test expression is false (0). if (test expression) { body of true-block statement; } else { body of false-block statement; } Statement-x; If test expression is true, codes inside the body of if statement is executed and, codes inside the body of else statement is skipped. If test expression is false, codes inside the body of else statement is executed and, codes inside the body of if statement is skipped. Then the control transferred to statement-x.
  • 32. C-NOTES MUTHUGANESH S 31 /*odd or even*/ #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("Please Enter the Number"); scanf("%d",&n); if((n%2)==0) { printf("%d nThe given Number is even",n); } else { printf("%d nThe Given Number is odd",n); } printf("nHave a Nice Day"); getch(); } Output Nestedif..else statement Syntax if (condition1) { if (condition2) { statement-1;
  • 33. C-NOTES MUTHUGANESH S 32 } else { statement-2; } } else { statement-3; } Statement-x; The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement
  • 34. C-NOTES MUTHUGANESH S 33 /*nested if*/ #include<stdio.h> #include<conio.h> void main() { float balance,bonus,total=0; char sex; clrscr(); printf("Enter your Sex like Male(m)/Female(f)"); scanf("%s",&sex); printf("Enter your Balance"); scanf("%f",&balance); if(sex=='f') { if(balance>=5000) { bonus=0.05*balance; total=balance+bonus; printf("nThe Total salary is %f",total); } else { bonus=0.03*balance; total=balance+bonus; printf("nThe Total Salary is %f",total); } } else { bonus=0.02*balance; total=balance+bonus; printf("nThe total Salary is %f",total); } printf("nHave a Nice Day"); getch(); } Output
  • 35. C-NOTES MUTHUGANESH S 34 if else ladder statement There is another way to putting ifs together when the multipath decisions are involved. The condition evaluated from top to downwards, as soon as true condition is found, the statement associated with it is executed and the control transferred to next statement(skipping the rest of the ladder). When all the n conditions false, then final else containing the default statement will be executed. Syntax if(condition_expression_1) { statement1; } else if (condition_expression_2) { statement2; } else if (condition_expression_3) { statement3; } else { statement4; }
  • 36. C-NOTES MUTHUGANESH S 35  First of all condition_expression_1 is tested and if it is true then statement1 will be executed and control comes out out of whole if else ladder.  If condition_expression_1 is false then only condition_expression_2 is tested. Control will keep on flowing downward, If none of the conditional expression is true.  The last else is the default block of code which will gets executed if none of the conditional expression is true. /*biggest of among three numbers*/ #include<stdio.h> #include<conio.h> void main() { int n1,n2,n3; clrscr(); printf("Enter Numbers One by Onen"); scanf("%dn%dn%d",&n1,&n2,&n3); if((n1>n2)&&(n1>n3)) { printf("%d is the largest number",n1); } else if((n2>n1)&&(n2>n3))
  • 37. C-NOTES MUTHUGANESH S 36 { printf("%d is the largest number",n2); } else { printf("%d is the largest number",n3); } getch(); } Output Switch statement When you want to solve multiple option type problems, for example, menu like program, where one value is associated with each option and you need to choose only one at a time, then, switch statement is used. Switch statement is a control statement that allows us to choose only one choice among the many given choices. The expression in switch evaluates to return an integral value, which is then compared to the values present in different cases. It executes that block of code which matches the case value. If there is no match, then default block is executed (If present).The general form of switch statement is,
  • 38. C-NOTES MUTHUGANESH S 37 Syntax The syntax for a switch statement in C programming language is as follows − switch(expression) { case value 1: block-1; break; case value 2: block-2; break; case value 3: block-3; break; case value 4: block-4; break; default: default-block; break; } The following rules apply to a switch statement −  The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.  You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon(:).  The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.  When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • 39. C-NOTES MUTHUGANESH S 38  When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.  Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.  A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. /*vibgyor.c*/ #include<stdio.h> #include<conio.h> void main() { char color; clrscr();
  • 40. C-NOTES MUTHUGANESH S 39 printf("Enter your choice"); scanf("%s",&color); switch(color) { case 'v' : printf("Voilet"); break; case 'i': printf("Indigo"); break; case 'b': printf("Blue"); break; case 'g': printf("Green"); break; case 'y': printf("Yellow"); break; case 'o': printf("Orange"); break; case 'r': printf("Red"); break; default: printf("Your Entered Wrong Option"); break; } getch(); } Output
  • 41. C-NOTES MUTHUGANESH S 40 Decision Making and Looping  Execution of a statement or set of statement repeatedly is called as looping.  The loop may be executed a specified number of times and this depends on the satisfaction of a test condition.  Depending on the position of the control statement in the loop, a control structure may be classified either as an entry controlled loop or as an exit controlled loop.  When the control statement is placed before the body of the loop then such loops are called as entry controlled loops. If the test condition in the control statement is true then only the body of the loop is executed.  When the control statement is placed after the body of the loop then such loops are called as exit controlled loop. In this the body of the loop is executed first then the test condition in the control statement is checked. The For statement For loop is entry controlled loop statement. The general structure form of for loop Syntax for (initialization; test condition; increment) { body of the loop } When the control enters for loop the variables used in for loop is initialized with the starting value The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or
  • 42. C-NOTES MUTHUGANESH S 41 simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition. For loop Flowchart Example program /*sum of n numbers*/ #include<stdio.h> #include<conio.h> void main() { int i, n,sum=0; printf("Enter positive integer"); scanf("%d",&n); for(i=1;i<=n;i++) { sum=sum+i; } printf("sum=%d",sum); getch(); }
  • 43. C-NOTES MUTHUGANESH S 42 The While Statement: The simplest of all looping structure in C is the while statement and its entry controlled loop statement. The general format of the while statement is: while (test condition) { body of the loop } The while loop flow chart
  • 44. C-NOTES MUTHUGANESH S 43 Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statements immediately after the body of the loop. Example program for while statement /* sum of digit*/ #include<stdio.h> #include<conio.h> void main() { int n,sum; clrscr(); printf("Enter Value"); scanf("%d",&n); sum=0; while(n>0) { sum=sum+(n%10); n=n/10; } printf("Sum Of Digit=%d",sum); getch(); } Output
  • 45. C-NOTES MUTHUGANESH S 44 The Do while statement: The do while loop is also a kind of loop and its exit controlled loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once. The syntax of the do while loop is: do { statement; } while(expression); Here the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false. When the expression becomes false the loop terminates. The flow chart of do..while statement
  • 46. C-NOTES MUTHUGANESH S 45 Example program /*print n umbers*/ #include<stdio.h> #include<conio.h> void main() { int i=0,n; clrscr(); printf("Enter the limit"); scanf("%d",&n); printf("The numbers are "); do { printf("n %d",i); i++; } while(i<=n); getch(); }
  • 47. C-NOTES MUTHUGANESH S 46 The Break Statement: Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately. Syntax of break statement break;
  • 48. C-NOTES MUTHUGANESH S 47 Continue statement: During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next
  • 49. C-NOTES MUTHUGANESH S 48 iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply: Syntax : Continue; Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
  • 50. C-NOTES MUTHUGANESH S 49 One dimensional Array A list of items can be given one variable name using only one subscript and such a variable is called one-dimensional array. Syntax To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant or symbolic constant greater than zero and type can be any valid C data type. Example float mark[5]; Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values. Computer reserves five storage locations as shown below Mark[0] Mark[1] Mark[2] Mark[3] Mark[4]  Arrays have 0 as the first index not 1  If the size of an array is n, to access the last element, (n-1) index is used. After declaration an array elements to be initialized as follows  At compile time  At runtime At Compile time It's possible to initialize an array during declaration. For example,
  • 51. C-NOTES MUTHUGANESH S 50 int mark[5]={40,54,78,90,80}; Another method to initialize array during declaration: int mark[]={45,67,89,90}; At Runtime int x[3]; scanf(“%d%d%d”,&x[0],&x[1],&x[2]); /* sorting numbers*/ #include<stdio.h> #include<conio.h> # define max 15 void main() { int n[6]={52,45,78,100,56,10}; int i,j,temp; clrscr(); printf("the sorting list are"); for(i=0;i<6;i++) { for(j=i+1;j<6;j++) { if(n[i]<n[j]) { temp=n[i]; n[i]=n[j]; n[j]=temp; } } } for(i=0;i<6;i++) { printf("n%dn",n[i]); } getch(); }
  • 52. C-NOTES MUTHUGANESH S 51 Output Two Dimentional array Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row & the other the column. The declaration of two dimension arrays is as follows: data_type array_name[row_size][column_size]; int m[5][6]; Here m is declared as a matrix having 5 rows (numbered from 0 to 4) and 6 columns (numbered 0 through 5). The first element of the matrix is m [0][0] and the last row last column is m[4][5]. A two dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on. marks [0][0] 35.5 Marks [0][1] 40.5 Marks [0][2] 45.5 marks [1][0] 50.5 Marks [1][1] 55.5 Marks [1][2] 60.5 marks [2][0] Marks [2][1] Marks [2][2] marks [3][0] Marks [3][1] Marks [3][2]
  • 53. C-NOTES MUTHUGANESH S 52 int table[2][3]={0,0,0,1,1,1}; Initializes the elements of first row to 0 and second row to 1. The initialization is done row by row. The above statement can be equivalently written as int table[2][3]={{0,0,0},{1,1,1}} By surrounding the elements of each row by braces. /* Multiarray.c*/ #include<stdio.h> #include<conio.h> #define rows 5 #define columns 5 void main() { int row,column,product[rows][columns]; int i,j; clrscr(); printf("Multiplication Table"); for(j=1;j<=columns;j++) { printf("%4d",j); printf("n"); printf("-------------------------"); for(i=0;i<rows;i++) { row=i+1; printf("%2d |",row); for(j=1;j<=columns;j++) { column=j; product[i][j]=row*column; printf("%4d",product[i][j]); } printf("n"); } } getch(); } OUTPUT
  • 54. C-NOTES MUTHUGANESH S 53 Multi-dimensional array C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is: data_type array_name[s1][s2][s3]…..[sn]; Where s is the size of the ith dimension. Some examples are: int survey[3][5][12]; float table[5][4][5][3]; Strings A string is a sequence of characters. Any sequence or set of characters defined within double quotation.  C Strings are nothing but array of characters ended with null character (‘0’).  This null character indicates the end of the string.  Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. Declaring and initializing string variables C does not support string as data type. It allows to represent string as character arrays. The general form of declaration of string variable is char string_name[size]; Size determines the number of characters in the string name. Its automatically assigns null character (‘0’) at the end of the string. Character array may be initialized when they declared as follows char name[10]=”Madurai”; We can also declare the size much longer than the string size in the initializer. From the above statement C permits in computer character array of size 10, place the value “Madurai” and initializes all elements to null. Reading Strings from the terminal: The function scanf with %s format specification is needed to read the character string from the terminal.
  • 55. C-NOTES MUTHUGANESH S 54 Example: char address[15]; scanf(“%s”,address); Scanf statement has a drawback it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word “new” it will terminate the string. Note that we can use the scanf without the ampersand symbol before the variable name. Writing strings to screen: The printf statement along with format specifier %s to print strings on to the screen. The format %s can be used to display an array of characters that is terminated by the null character. Example printf(“%s”,name); Can be used to display the entire contents of the array name. getchar() and putchar() Single Character functions are used for reading and displaying a single character respectively. These functions are : getchar() – reads a character from the keyboard. putchar() – prints a character to the screen. Example of getchar() and putchar() : character = getchar(); The statement 1 reads a character and stores it in variable character. So, it waits for the character input until a character is typed at the keyboard. putchar(b); The statement 2 prints the given character on the screen at the current cursor position..So, it will display a character (‘b’) on the screen. Another Example of getchar and putchar : char ch; ch = getchar();
  • 56. C-NOTES MUTHUGANESH S 55 putchar(ch); The getchar() waits for the character input until a character is typed at the keyboard. Whatever is stored inside ch, gets displayed on the screen. gets() and puts() : The single character functions defined above can handle single character at a time and cannot handle multiple characters. To solve this problem, there are functions that can handle strings also. These functions are :  gets() – accepts a string of characters entered at the keyboard and places them in the string variable mentioned with it.  puts() – writes a string on the screen and advances the cursor to the newline. i.e. it ends with a new line character. Syntax char name[15]; gets(name);  gets() read a string of maximum 15 characters and stores it in memory address pointed to by ‘name’.  A null terminator ‘0’ is automatically placed at the end of the string, if the enter or carriage return is pressed. puts(name); whatever stored in name it displays on the screen. strlen() function: This function counts and returns the number of characters in a string. The length does not include a null character. Syntax n=strlen(string); Where n is integer variable. Which receives the value of length of the string. Example length=strlen(“Hollywood”); The function will assign number of characters 9 in the string to a integer variable length.
  • 57. C-NOTES MUTHUGANESH S 56 strcat() function: when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. It takes the following form Syntax strcat(string1,string2); string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged. strcmp function: In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below: Syntax Strcmp(string1,string2); String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second. strcpy() function: C does not allow you to assign the characters to a string directly as in the statement name=”Robert”; Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below. Syntax strcpy(string1,string2); Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.
  • 58. C-NOTES MUTHUGANESH S 57 Function & Purpose strcpy(s1, s2); Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1,’a’); Returns locate the first occurrence of character ‘m’ strstr(s1,s2); Searches the string s1 to see wheather the string s2 is contained s1 Example strfunc.c #include<stdio.h> #include<string.h> #include<conio.h> #include<stdlib.h> void main() { char s1[20],s2[20],s3[20],s4='a',s5[25]; int x,y; clrscr();
  • 59. C-NOTES MUTHUGANESH S 58 printf("enter 1st string"); scanf("%s",&s1); printf("Enter 2nd string"); scanf("%s",&s2); x=strcmp(s1,s2); if(x==0) { printf("Strings are Equaln"); printf("%sn",strcat(s1,s2)); } else { y=strlen(s1); printf("length of the string%dn",y); } if(strchr(s2,s4)==NULL) { printf("nsubstring is not found"); } else { printf("nsubstring found"); printf("%s",strcpy(s5,s3)); } getch(); }
  • 60. C-NOTES MUTHUGANESH S 59 User-Defined Functions A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program. The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully. There are many advantages in using functions in a program they are: 1. It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 2. The length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited. 3. It is easy to locate and isolate a faulty function for further investigation. 4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch. 5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated. We already know that C support the use of library functions and use defined functions. The library functions are used to carry out a number of commonly used operations or calculations. The user-defined functions are written by the programmer to carry out various individual tasks. Functions are used in C for the following reasons: 1. Many programs require that a specific function is repeated many times instead of writing the function code as many timers as it is required we can write it as a single function and access the same function again and again as many times as it is required. 2. We can avoid writing redundant program code of some instructions again and again.
  • 61. C-NOTES MUTHUGANESH S 60 3. Programs with using functions are compact & easy to understand. 4. Testing and correcting errors is easy because errors are localized and corrected. 5. We can understand the flow of program, and its code easily since the readability is enhanced while using the functions. 6. A single function written in a program can also be used in other programs also. In order to make user-defined function, we need to establish three elements that are related to function.  Function Definition  Function Call  Function Declaration Function declaration In C program must be declared before they invoked. It consists of four parts  Function type (return type)  Function name  Parameter list  Terminating semicolon General form of function declaration function_type function_name (parameter list); Function Definition A function definition provides the actual body of the function that is specially written to implement requirements of the functions. In order to invoke to use this function required place in the function program is called function call. The program that calls the function is called calling function the calling function that is used to be later in the program is called function declaration or function prototype. Definition of the Function is also called function implementation shall include the following parts  Function Name  Function Type  List of parameters local variables declarations  Function Statements  A return statements
  • 62. C-NOTES MUTHUGANESH S 61 All six parts are grouped into two parts Function Header (function_type, function_name and parameterlist) Function Body(local declaration, function statements and return) The general form of function definition as follows function _type function_name(parameter_list) { local variables declarations; executable statements; …………………..; ……………………..; return statement; } Example int mul(int a,int b) { printf (“Enter values”); scanf(“%d%d”,&a,&b); return(a*b); } Function type Function type specifies the type of value (like float or double) that function is expected to return to the program calling function. If the function not explicitly specified, C will assume that is integer type. If the function not return anything than we need to specify that the return type as void. Function name The function name is any valid C identifier and therefore must follow the same rules of formation as other variable name in C. Parameter list The parameter list declares the variables that will receive the data sent by calling program. They serve as input data the function. They represent actual input values and also called formal parameters. These parameters sent values to the calling programs.
  • 63. C-NOTES MUTHUGANESH S 62 Return If function return values it does through the return statement. The general form of return statement return Or return(expression); Function calls Function calls can be called by simple using the function name followed by list of parameters or arguments, if any enclosed in parentheses main() { int y; y=mul(10,5); printf(“%d”,y); } Categories of function  Function with no arguments and no return values  Function with arguments and no return values  Function with no arguments and one return value  Function with no arguments but return a value  Function that return multiple values
  • 64. C-NOTES MUTHUGANESH S 63 No arguments and no return values If function has no values, it does not receive any data from the calling function, when does not return value, the calling function does not receive any data from the called function. In simply says there is no data transfer from calling function and called function. No Input No output Fuuntion 2() { ………………; …………………; } Function 1() { ………………..; …………………..; ………………; Fuuntion 2() { ………………; …………………; } } Example funcsum.c #include<stdio.h> #include<conio.h> void sum(); //function declaration void main() { clrscr(); sum(); // function call getch(); } void sum(); // function definition { int n,r,s=0; // local declaration printf("Enter the Number"); // statements scanf("%d",&n); while(n>0)
  • 65. C-NOTES MUTHUGANESH S 64 { r=n%10; s=s+r; n=n/10; } printf("sum of number%d",s); } Output
  • 66. C-NOTES MUTHUGANESH S 65 Function with arguments and no return values The main function has no control over the way functions receive input data. We could make the calling function to read data from terminal and pass it on the called function. Values of arguments No return value Function 1() { ………………..; …………………..; ………………; Fuuntion 2(a) { ………………; …………………; } } Fuuntion 2(f) { ………………; …………………; } Example funcintr.c #include<stdio.h> #include<conio.h> void printline(char ch); void intrest(int p,int n);// function declaration with arguments no return value void main() { int p,n; clrscr(); printf("Enter principle amount"); scanf("%d",&p); printf("Enter No of Years"); scanf("%d",&n); printline('*'); //function call with arguments intrest(p,n); //function call with arguments printline('-'); //function call with arguments getch(); } void printline(char ch) //function definition with arguments no return value {
  • 67. C-NOTES MUTHUGANESH S 66 int i; for(i=1;i<=45;i++) printf("%c",ch); printf("n"); } void intrest(int p,int n) //function definition with arguments no return value { float intr,r=0.15; intr=(p*n*r)/100; printf("n%fn",intr); } output Function With arguments and one return value The function value receives data from the calling function through arguments, but does not send back any value. Rather displays the calculations at the terminal. However we may not always wish to have the result of function displayed. We may use it the calling function for further processing. A self-contained and independent function should behave like ‘black-box’ that receives a predefined form of input and output a desired value is called two-way communication.
  • 68. C-NOTES MUTHUGANESH S 67 Values of arguments function result Function 1() { ………………..; …………………..; ………………; Fuuntion 2(a) { ………………; …………………; } } Fuuntion 2(f) { ………………; …………………; return; } Example funcarea.c #include<stdio.h> #include<conio.h> void printline(char ch, int len); int sqrarea(int a); //Function declaration With arguments and return value float cirarea(float r);//Function declaration With arguments and return value double recarea(float l, float b);//Function declaration With arguments return value void main() { clrscr(); printline('*',50); //function call with value printf("narea of square %dn",sqrarea(15)); //function call with value printf("area of circle %fn",cirarea(2.0)); //function call with value printf("area of rectangle %gn",recarea(3.4,5.6)); //function call with value printline('@',50); //function call with value getch(); } int sqrarea(int a)// function definition with return { return(a*a); } float cirarea(float r) // function definition with return { float pi=3.14;
  • 69. C-NOTES MUTHUGANESH S 68 return(pi*r*r); } double recarea(float l,float b) // function definition with return type { return(l*b); //return } void printline(char ch,int len) { int i; for(i=1;i<=len;i++) { printf("%c",ch); //printf("n"); } } Output
  • 70. C-NOTES MUTHUGANESH S 69 Function with no arguments but returns value There we may need to design that may not take any argument but returns a returns value to the calling function. Example funceven.c #include<stdio.h> #include<conio.h> #include<stdlib.h> int even(); void main() { clrscr(); even(); // function calling getch(); } int even() // declaration no arguments with return value { int n; printf("Enter n value"); scanf("%d",&n); if(n%2==0) printf("the number in even%d",n); else printf("the number is odd%d",n); return 0; //return } Output
  • 71. C-NOTES MUTHUGANESH S 70 Function that returns multiple value The return statement returns only one value. Suppose we want to get more information from function. We can achieve this in C using arguments not only to receive information but also to send back information to the calling function. The arguments that are used “send out’’ information are called output parameters. The mechanism of sending back information through arguments is achieved using the address operator (&) and indirection operator (*). Example funcmulti.c #include<stdio.h> #include<conio.h> int getvalue(int a, int b, int *product)//function definition using * { *product=a*b; return a+b; //return } main() { int a,b,s,product; clrscr(); printf("Enter values"); scanf("%d%d",&a,&b); s=getvalue(a,b,&product); //function call with & printf("sum=%dnproduct=%d",s,product); getch(); } output
  • 72. C-NOTES MUTHUGANESH S 71 Recursive function Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". Example #include<stdio.h> #include<conio.h> int fact(int); void main() { int f,n; clrscr(); printf("Enter the number"); scanf("%d",&n); f=fact(n); //function call printf("Factorial value is %d",f); getch(); } int fact(int n) { int f; if(n==1) { return; //function call itself } else { f=n*fact(n-1); //recursive function return f; } } Output
  • 73. C-NOTES MUTHUGANESH S 72 Call by reference and call by value There are two ways to pass arguments/parameters to function calls -- call by value and call by reference. The major difference between call by value and call by reference is that in call by value a copy of actual arguments is passed to respective formal arguments. While, in call by reference the location (address) of actual arguments is passed to formal arguments, hence any change made to formal arguments will also reflect in actual arguments. Point Call by Value Call by Reference Copy Duplicate Copy of Original Parameter is Passed Actual Copy of Original Parameter is Passed Modification No effect on Original Parameter after modifying parameter in function Original Parameter gets affected if value of parameter changed inside function Example Call by reference swapref.c #include<stdio.h> #include<conio.h> void swap(int *x,int *y); main() { int a=100,b=200; clrscr();
  • 74. C-NOTES MUTHUGANESH S 73 printf("Before swap, the value of a:%dn",a); printf("Before swap, the value of b:%dn",b); swap(&a,&b); printf("After swap, value of a:%dn",a); printf("After swap, value of b:%dn",b); getch(); } void swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; } Output Rules for pass by pointers  The types of actual and formal arguments must be same.  The actual arguments (in the function call) must be the addresses of variables that the local to the calling function.  The formal arguments in the function header must be prefixed by the indirection operatior *.  In the prototype, the arguments must be prfixed by the symbol *.  To access the value of actual arguments in the called function, we must use the corrresponding formal argument prefixed with the indirection operator.
  • 75. C-NOTES MUTHUGANESH S 74 Example call by value swapval.c #include<stdio.h> #include<conio.h> void swap(int x,int y); main() { int a=100,b=200; clrscr(); printf("Before swap, the value of a:%dn",a); printf("Before swap, the value of b:%dn",b); swap(a,b); printf("After swap, value of a:%dn",a); printf("After swap, value of b:%dn",b); getch(); } void swap(int x,int y) { int temp; temp=x; x=y; y=temp; } Output Nesting of function C permits nesting function freely. Main can call funtion1, which calls function2, which calls funtion3,…………. And so on. There is in principle no limit as to how deeply functions can be nested. #include<stdio.h> #include<conio.h> float add(int x,int y,int z); int diff(int x,int y); void main() { int a,b,c; clrscr(); printf("please Enter Values"); scanf("%d%d%d",&a,&b,&c);
  • 76. C-NOTES MUTHUGANESH S 75 printf("%dn",add(a,b,c)); getch(); } float add(int x,int y,int z) { if(diff(x,y)) return(x/(y-z)); else return (0); } int diff(int p,int q) { if(p!=q) return(1); else return(0); } Passing arrays to function Like values of simple variables, it is also to pass the value of an array to function. To pass an array to called function, its sufficient to list the name of the array,without any subscripts, and the size of array as arguments.  The function must be called bypassing only the name of the array  In the function definition the formal parameter must be an array type the size of array does not need to be specified.  The function prototype must show that argument is array Example Funcarr.c #include<stdio.h> #include<conio.h> float avg(int marks[], int size); void main() { int i; int marks[10],size; clrscr(); printf("Enter your number of subject to enter"); scanf("%d",&size); printf("Enter the marks"); for(i=0;i<size;i++) { scanf("%d",&marks[i]); } printf("%f",avg(marks,size)); getch(); } float avg(int marks[],int size) { int tot=0,i; for(i=0;i<size;i++) {
  • 77. C-NOTES MUTHUGANESH S 76 tot=tot+marks[i]; } return(tot/size); } Output Passing as two dimentional array  The function must be called bypassing only the name of the array  In the function definition the formal parameter must be an array has two-dimentional by including two set of brackets.  The size of second dimention must be specified  The function prototype should be similar to the function header. Example double average(int x[][n],int m,int n) //function defintion { int i,j; double sum=0; } main() { int m=3,n=2; double average(int [][n],int int); //function declaration double mean;
  • 78. C-NOTES MUTHUGANESH S 77 int matrix[m][n]={{1,2},{3,4},{5,6}}; mean=average(matrix,m,n); // function call } Passing srtrings to functions The strings are treated as character arrray in C and therefore rules are same to functions as similar to passings array to functions. The strings to be passed must be declared as formal argument of the function when its defined. void display(char name[]) { Statements; } The function prototype must be show the arrguments is string void display(char str[]); the call function must have a string array name without subscript as actual argument. void display(name); The scope, visiblity, and life time ofthe varriables Variables in C differ in behaviour from those in most in other languages. In C not only do all variables have data type, they must also have a storage class The following storage classes are most oftenly used in C programming, 1. Automatic variables 2. External variables 3. Static variables 4. Registervariables Automatic variables The auto storage class is the default storage class for all local variables. Scope: Local to the method block in which the variable is defined. Default Initial Value: Any random value i.e garbage value. Lifetime: Till the end of method block where the variable is defined. A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called
  • 79. C-NOTES MUTHUGANESH S 78 local variables because they are local to a function. By default they are assigned garbage value by the compiler. Syntax auto int n; Example void main() { int detail; or auto int detail; //Both are same } External variables Scope: Global. When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. Default initial value: 0(zero). Lifetime: Till the whole program doesn't finish its execution. A variable that is declared outside any function is a Global Variable. Global variables remain available throughout the entire program. By default, initial value of the Global variable is 0(zero). One important thing to remember about global variable is that their values can be changed by any function in the program. Syntax extern int a; #include<stdio.h> int number; // by default global variable void main() { extern int a; // by declared as global variable using extern getch();
  • 80. C-NOTES MUTHUGANESH S 79 } Static variable Scope: Local to the block in which the variable is defined Default initial value: 0(Zero). Lifetime: Till the whole program doesn't finish its execution. A static variable tells the compiler to persist the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static is initialized only once and remains into existence till the end of program. A static variable can either be internal or external depending upon the place of declaraction. Scope of internal staticvariable remains inside the function in which it is defined. External static variables remain restricted to scope of file in each they are declared. They are assigned 0 (zero) as default value by the compiler. Syntax static int a; Example void test(); main() { test(); test(); test(); } void test() { static int a = 0; //Static variable a = a+1; printf("%dt",a); }
  • 81. C-NOTES MUTHUGANESH S 80 output : 1 2 3 Registervariable Scope: Local to the function in which it is declared. Default initial value: Any random value i.e garbage value Lifetime: Till the end of method block, where the variable is defined, doesn't finish its execution. Register variable inform the compiler to store the variable in CPU register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register. An application of register storage class can be in using loops, where the variable gets used a number of times in the program. We can never get the address of such variables. Syntax : register int number; Note: Even though we have declared the storage class of variable number as register, we cannot surely say that the value of the variable would be stored in a register. This is because the number of registers in a CPU are limited. Also, CPU registers are meant to do a lot of important work.Thus, sometimes it may not be free. In such scenario, the variable works as if its storage class is auto.
  • 82. C-NOTES MUTHUGANESH S 81 STRUCTURE structure is another user defined data type available in C that allows to combine data items of different kinds. A structure is a user defined data type in C. A structure creates a data type that can be used to group items of possibly different types into a single type. struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived datatypes. Syntax: struct structure_tag { //member variable 1 //member variable 2 //member variable 3 ... };structure_variables Example of Structure struct Student { char name[25]; int age; char branch[10]; char gender; int m1,m2,m3; float avg; }; Here struct Student declares a structure to hold the details of a student which consists of 4 data fields, namely name, age, branch, gender, marks(1,2 and 3) and average. These fields are called structure elements or members.
  • 83. C-NOTES MUTHUGANESH S 82 Declaring Structure Variables It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other datatype. Structure variables can be declared in following two ways: 1) Declaring Structure variables separately struct Student { char name[25]; int age; char branch[10]; char gender; int m1,m2,m3; float avg; }; struct Student S1, S2; //declaring variables of struct Student 2) Declaring Structure variables with structure definition struct Student { char name[25]; int age; char branch[10]; char gender; int m1,m2,m3; float avg; }S1, S2; Here S1 and S2 are variables of structure Student
  • 84. C-NOTES MUTHUGANESH S 83 Accessing Structure Members Structure members can be accessed and assigned values in a number of ways. Structure members have no meaning individually without the structure. In order to assign a value to any structure member, the member name must be linked with the structure variable using a dot(.) operator also called period or member access operator. include<stdio.h> #include<conio.h> struct student { char name[30]; int age; }; void main() { struct student s; clrscr(); printf("Enter your Name"); scanf("%s",&s.name); printf("Enter your age"); scanf("%d",&s.age); printf("Hai Mr.%s welcome your age is %d",s.name,s.age); getch(); } We can also use scanf() to give values to structure members through terminal. scanf(" %s ", s.name); scanf(" %d ", &s.age);
  • 85. C-NOTES MUTHUGANESH S 84 Output Structure Initialization Like a variable of any other datatype, structure variable can also be initialized at compile time. struct student { float height; int weight; int age; }; struct student s1 = { 180.75 , 73, 23 }; //initialization or, struct student s1; s1.height = 180.75; //initialization of each member separately s1.weight = 73; s1.age = 23;
  • 86. C-NOTES MUTHUGANESH S 85 Nested Structures Nesting of structures, is also permitted in C language. Nested structures means,that one structure has another stucture as member variable. Example: struct Student { char[30] name; int age; /* here Address is a structure */ struct Address { char[50] locality; char[50] city; int pincode; }addr; }; Structure as Function Arguments We can pass a structure as a function argument just like we pass any other variable or an array as a function argument. Example: #include<stdio.h> struct Student { char name[10]; int roll; }; void show(struct Student st); void main() { struct Student std; printf("nEnter Student record:n"); printf("nStudent name:t"); scanf("%s", std.name);
  • 87. C-NOTES MUTHUGANESH S 86 printf("nEnter Student rollno.:t"); scanf("%d", &std.roll); show(std); } void show(struct Student st) { printf("nstudent name is %s", st.name); printf("nroll is %d", st.roll); } Unions Unions are conceptually similar to structures. The syntax to declare/define a union is also similar to that of a structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member. This implies that although a union may contain many members of different types, it cannot handle all the members at the same time. A union is declared using the union keyword.
  • 88. C-NOTES MUTHUGANESH S 87 union hai { int m; float x; char c; }h; Accessing a Union Member in C Syntax for accessing any union member is similar to accessing structure members, union test { int a; float b; char c; }t; t.a; //to access members of union t t.b; t.c; Pointer A Pointer in C language is a variable which holds the address of another variable of same data type. Pointers are used to access memory and manipulate the address. Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language. Concept of Pointers Whenever a variable is declared in a program, system allocates a location i.e an address to that variable in the memory, to hold the assigned value. This location has its own address number, which we just saw above. Let us assume that system has allocated memory location 80F for a variable a. int a = 10;
  • 89. C-NOTES MUTHUGANESH S 88 We can access the value 10 either by using the variable name a or by using its address 80F. The variables which are used to hold memory addresses are called Pointer variables. A pointer variable is therefore nothing but a variable which holds an address of some other variable. And the value of a pointer variable gets stored in another memory location. Benefits of using pointers Below we have listed a few benefits of using pointers: 1. Pointers are more efficient in handling Arrays and Structures. 2. Pointers allow references to function and thereby helps in passing of function as arguments to other functions. 3. It reduces length of the program and its execution time as well. 4. It allows C language to support Dynamic Memory management. Declaration of C Pointer variable General syntax of pointer declaration is, datatype *pointer_name; Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. void type pointer works with all data types, but is not often used. Here are a few examples: int *ip // pointer to integer variable float *fp; // pointer to float variable double *dp; // pointer to double variable char *cp; // pointer to char variable
  • 90. C-NOTES MUTHUGANESH S 89 Initialization of C Pointer variable Pointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it. #include<stdio.h> void main() { int a = 10; int *ptr; //pointer declaration ptr = &a; //pointer initialization } Pointer variable always point to variables of same datatype. Let's have an example to showcase this: #include<stdio.h> void main() { float a; int *ptr; ptr = &a; // ERROR, type mismatch } If you are not sure about which variable's address to assign to a pointer variable while declaration, it is recommended to assign a NULL value to your pointer variable. A pointer which is assigned a NULL value is called a NULL pointer.
  • 91. C-NOTES MUTHUGANESH S 90 #include <stdio.h> int main() { int *ptr = NULL; return 0; } Points to remember while using pointers 1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer. 2. The address of any variable is given by preceding the variable name with Ampersand &. 3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value. It means that a is going to contain the address of a variable storing integer value. 4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be read as 'value at'. Pointer and Arrays in C When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array is also allocated by the compiler. Suppose we declare an array arr, int arr[5] = { 1, 2, 3, 4, 5 }; Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:
  • 92. C-NOTES MUTHUGANESH S 91 Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards the first element in the array. arr is equal to &arr[0] by default We can also declare a pointer of type int to point to the array arr. int *p; p = arr; // or, p = &arr[0]; //both the statements are equivalent. Now we can access every element of the array arr using p++ to move from one element to another. Pointer to Array As studied above, we can use a pointer to point to an array, and then we can use that pointer to access the array elements. Lets have an example, #include <stdio.h> int main() { int i; int a[5] = {1, 2, 3, 4, 5}; int *p = a; // same as int*p = &a[0] for (i = 0; i < 5; i++) { printf("%d", *p); p++; } return 0; } In the above program, the pointer *p will print all the values stored in the array one by one. We can also use the Base address (a in above case) to act as a pointer and print all the values
  • 93. C-NOTES MUTHUGANESH S 92 Pointer and Character strings Pointer can also be used to create strings. Pointer variables of char type are treated as string. char *str = "Hello"; The above code creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello". Another important thing to note here is that the string created using char pointer can be assigned a value at runtime. char *str; str = "hello"; //this is Legal Pointer to Array of Structures in C Like we have array of integers, array of pointers etc,we can also have array of structure variables. And to use the array of structure variables efficiently, we use pointers of structure type. We can also have pointer to a single structure variable, but it is mostly used when we are dealing with array of structure variables.
  • 94. C-NOTES MUTHUGANESH S 93 #include <stdio.h> struct Book { char name[10]; int price; } int main() { struct Book a; //Single structure variable struct Book* ptr; //Pointer of Structure type ptr = &a; struct Book b[10]; //Array of structure variables struct Book* p; //Pointer of Structure type p = &b; return 0; } Accessing Structure Members with Pointer To access members of structure using the structure variable, we used the dot . operator. But when we have a pointer of structure type, we use arrow -> to access structure members. #include <stdio.h> struct my_structure { char name[20]; int number; int rank; }; int main() { struct my_structure variable = {"ProgramminginC", 35, 1}; struct my_structure *ptr; ptr = &variable; printf("NAME: %sn", ptr->name); printf("NUMBER: %dn", ptr->number); printf("RANK: %d", ptr->rank); return 0; }
  • 95. C-NOTES MUTHUGANESH S 94 FILE A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure. In C language, we use a structure pointer offile type to declare a file. FILE *fp; C provides a number of functions that helps to perform basic file operations. Following are the functions, Function Description fopen() create a new file or open a existing file fclose() closes a file getc() reads a character from a file putc() writes a character to a file fscanf() reads a set of data from a file fprintf() writes a set of data to a file getw() reads a integer from a file putw() writes a integer to a file fseek() set the position to desire point ftell() gives current position in the file rewind() set the position to the begining point Opening a File or Creating a File The fopen() function is used to create a new file or to open an existing file. General Syntax: fp = FILE fopen(“filename”, “mode”);
  • 96. C-NOTES MUTHUGANESH S 95 filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types, mode Description r opens a text file in reading mode w opens or create a text file in writing mode. a opens a text file in append mode r+ opens a text file in both reading and writing mode w+ opens a text file in both reading and writing mode a+ opens a text file in both reading and writing mode Closing a File The fclose() function is used to close an already opened file. General Syntax : fclose(filename); Here fclose() function closes the file and returns zero on success,or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h. #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { char name[35]; int age; FILE *f1; clrscr(); f1=fopen("first","w"); printf("Writting to the file"); scanf("%s",name); scanf("%d",&age); fclose(f1); f1=fopen("first","r");
  • 97. C-NOTES MUTHUGANESH S 96 printf("Name:%s",name); printf("Age%d",age); fclose(f1); getch();