7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 1/143
1
Programming in “ C ” Index
Basic Concepts required for Introduction to C 2
Introduction to C 4
Operators in C 20
Decision Control Structure 23
If Statement
If-Else Statement 24
If-Else-If Statement 25
Ternary Operator (ConditionalOperator) 34
ASCII
SwitchStatement 36
Loop Control Structure 42
While loop 43
Do-While loop 50
For-loop 52
Functions 65
Storage Classes in C 79
Pointers 81
Arrays 87
Introduction to Arrays
PassingArrayelementstoFunction 91
Multidimensional Arrays 97
Two Dimensional Arrays
Three Dimensional Arrays 100
String Functions 102
Structures 110
Union 116
File Handling 119
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 2/143
2
Basic Concepts Required for Introduction to C
User language System language
(English language) (Language of 0’s and 1’s i.e.
Binary language)
Interpreter
OS
(Mediator, which converts user language
Into system language)
Introduction to Number system
There are two types of number system in a computer i.e. Decimal number system and Binary number system.
Decimal Number System: The decimal number contains 10 natural numbers from 0 to 9, which are
used by human being.
Binary Number System: The binary number system contains only two numbers i.e. 0 and 1 which is
used by compiler, because compiler cannot understand any other language except 0 and 1 in the form
of electronic signals.
0 1 0 1 0 1 0 1 0 1
ASCII
ASCII ranges from 0 to 255.
A – American
S – Standard
C – Code for
I – Information
I – Interchange
In ASCII language,
A – 65 a – 97
B – 66 b – 98
| |
| |
| |
Z – 90 z – 122
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 3/143
3
Conversion of Decimal number in to Binary number system
2 65 1
2 32 02 16 0
2 8 0
2 4 0
2 2 0
1
A 1 0 0 0 0 0 1
In System language, A= 1000001
Two directories called <stdio.h> and <conio.h> are always included before starting the ‘C’ program.
These are included in the given way.
#include<stdio.h>
#include<conio.h>
void main( )
{
- - -
- - -
- - - }
printf – To print on screen.
scanf - To get value from keyboard/user.
stdio.h – standard input/output. header
This directory is included because printf() and scanf() functions are present in this directory and if
this directory is not included, printing and scanning is not possible. conio.h – console input/output.header
This directory is included because clrscr() and getch() functions are present in this directory.
In C, semicolon (;) is used to terminate the statement.
In C,
= Represents assignment operator
E.g. a=10 (here 10 is assigned to variable a.
= = Represents equality
E.g. a==b(here variable a and variable b represents equality)
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 4/143
4
Steps of C-program using flowchart Representation
Datatype
int 10,20,4,9 int a, b; %d int a; a
float 18.84,20.54 float a, b; %f float a; a
char ‘a’, ‘i’, ‘b’ char a; %c char a; a
string “chester” char a[20]; %s char a[7]; a
START
INPUT
CALCULATE
STOP
START
a, b, c
c=a+b
Print c
STOP
10
18.84
c
chester
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 5/143
5
Introduction to ‘C’
Dennis Ritchie developed the ‘C’ language at AT & T Bell’s laboratory in 1972. It was originally written for
programmes under the operating system UNIX.
The early version written by Ken Thomson adopted in the form of a language by the initials BCPL which
stands for Basic Combined Programming Language. To distinguish this language from BCPL, he termed it as
‘B’, the first character.
When the language was modified and was improved to its present st ate, the second letter of BCPL, ‘C’ waschosen to represent new version.
There is no single compiler for ‘C’. Many different organizations have written and implemented ‘C’
compiler.
Power, Portability, Performance and flexibility are the most important results for ‘C’ popularity.
‘C’ combines the features of both high level language which is the functionality of the assembly language.
Being a middle level language, it allows the manipulation of bits, bytes and the address directly make it more
suitable for system programming and hence ‘C’ is mostly used for writing interpreters, compilers, assembler
editions, database management.
Advantages of ‘C’
It is a structural programming language. ‘C’ source code is portable.
Being a middle level language suitable for commercial application.
‘C’ is designed so that compiler can translate a program into efficient machine instructions.
For Normal language
‘C’ consist of
Rules for C Program
C is a case sensitive.
Alphabets Words Sentences Paragraphs
AlphabetsDigits
Special symbols
ConstantsVariables
Keywords
Instructions Programs
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 6/143
6
All keywords have to be in lowercase.
Keywords have fixed meaning and are reserved i.e. keyword if, int, char.
Instructions about C program
‘C’ always start from main() [because ‘C’ compiler starts compiling always from main()
function.
There should be {(opening brace) and }(closing brace) to indicate the start and the end
of C program. For terminating the statements ;(semicolon) is used.
For inputting the data from the keyboard, scanf() function is used.
For output printf() function is used, where f is formatted input as well as for formatted
output.
C has no specific rules for the position at which a statement is to be written. That’s why
it is often called a free-form language.
Blank spaces may be inserted between two words to improve the readability of the
statement. However, no blank spaces are allowed within a variable, constant or
keyword.
Basic Structure of C program
DOCUMENTATION SECTION.
LINK SECTION.
DEFINITION SECTION.
GLOBAL DECLARATION SECTION.
main() : FUNCTION SECTION
{
Declaration part
Executable part
}
Subprogram section
function1
function2(User defined functions)
|
|
|
|
function n.
Syntax of scanf() statement
scanf(“control string”,&variable1 ,&variable2 - - -);
address
Syntax of printf() statement
printf(“<format string>”,<List of variables>)
where format string can be %f, %d, %c.
Format String
%f : It is used for declaring float variables.
%d : It is used for declaring integer variables.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 7/143
7
%c : It is used for declaring character variables.
General Structure of C-program
main()
{
declaration of variables/initialization
scanf(“ _____ ”);
printf(“ _____ ”);
_______
_______ C-instructions
_______
printf(“ _____ ”);
}
Comments
Comments about the program should be enclosed within /* */
Any number of comments can be given at any place in the program.
Comments cannot be nested. For example, /*Cal of SI /* Author sam date 01/01/90 */*/
is invalid.
A comment can be split over more than one line, as in,
/* This isa jazzy
comment */
Comments should be used at any place where there is a possibility of confusion.
Any program is nothing but a combination of functions. main() is one such function.
Empty parentheses after main are necessary.
The set of statements belonging to a function are enclosed within a pair of braces.
For e.g.
main()
{
statement 1;
statement 2;
statement 3;
}
Any variable used in the program must be declared before using it.
// Program to calculate simple interest.
main()
{
int p,n;
float r,si;
p=1000;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 8/143
8
n=3;
r=8.5;
si=p*n*r/100;
printf(“%f”,si);
}
In the above program we assumed the values of p,
n and r to be 1000, 3 and 8.5. If we want to make a provision for supplying the values of p, n and r
through the keyboard, scanf() function should be used. This is illustrated in the program shownbelow:
main()
{
int p, n;
float r, si;
printf(“ \nEnter values of p, n, r:”);
scanf(“%d %d %f”,&p,&n,&r);
si=p*n*r/100;
printf(“%f”,si);
}
The 1st printf() statement outputs the message “Enter values of p, n, r” on the screen. Here we have
not used any variables in printf(), which means that using variables in printf() is optional. Note thatthe ampersand (&) before the variables in the scanf() statement is a must.
Also, note that the values for p, n and r to be supplied through the keyboard, must be separated by a
blank, a tab or a newline.
E.g. The three values separated by blank.
5 15.5
E.g. The three values separated by tab.
1000 5 15.5
E.g. The three values separated by newline.
1000
5
15.5
‘C’-Character Set
C-Character Set consists of alphabets, digits and special symbols.
Alphabets: A---------Z
a----------z
Digits: 0--------9
Special symbols: +, -, =, {, }, [, ], ;, :, <, >, ?, /, \, @, #, *
Constants
Constant is a quantity which does not change during the execution of program. This quantity can bestored as a location in the memory of computer.
Variables
Variable are those which can change during the execution of program (compilation of program).
Example of constants and variables:
2a+3b=23
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 9/143
9
Here a and b can vary but 2,3,23 cannot vary as those are values.
Therefore, a &b are variables & 2,3,23 are constants.
//Program to convert Fahrenheit into celsius.
#include<stdio.h>
#include<conio.h>
void main()
{
float f,c;
clrscr();
printf("\nEnter the value of fahrenheit:");
scanf("%f",&f);c=5.0/9*(f-32);
printf("%f",c);
getch();
}
***************************************************************************
//Program to convert Pound into Kgs.
#include<stdio.h>
#include<conio.h>
void main()
{
float pound,kg;clrscr();
printf("\nEnter the pounds:");
scanf("%f",£);
kg=pound/2.204;
printf("Kg=%f",kg);
getch();
}
*******************************************************************************
//Program to calculate the area & volume of sphere
#include<stdio.h>
#include<conio.h>
void main()
{
int radius;
float volume,area;
clrscr();
printf("\nEnter the radius of sphere:");
scanf("%d",&radius);
volume=(4.0/3)*3.14*radius*radius*radius;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 10/143
10
area=4*3.14*radius*radius;
printf("Volume=%f Area=%f",volume,area);
getch();
}
********************************************************************************
//Program to convert Km into m.
#include<stdio.h>
#include<conio.h>
void main()
{
float km,m;
clrscr();
printf("\nEnter the value of Km:");
scanf("%f",&km); m=(1.0/1000)*km;
printf("%f",m);
getch();
}
*******************************************************************************
//Program to convert Byte into Bits, Kilobytes, Megabytes
#include<stdio.h>
#include<conio.h>
void main()
{
float byte,bit,kb,mb;clrscr();
printf("\nEnter the bytes:");
scanf("%f",&byte);
bit=1.0/8*byte;
kb=byte*1000;
mb=byte*1000000;
printf("Bit=%f Kilobyte=%f Megabyte=%f",bit,kb,mb);
getch();
}
********************************************************************************
//Program to calculate the sum of digits of three digit number
//entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,n1,n2,sum;
clrscr();
printf("\nEnter any 3 digit number:");
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 11/143
11
scanf("%d",&num);
n1=num%10;
num=num/10;
n2=num%10;
num=num/10;
sum=n1+n2+num;
printf("\nSum of 3 digits=%d",sum);
getch();
}
************************************************************************************
//Program to calculate the sum of 1st and last digit of four digit
//number entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,n1,n2,sum;
clrscr(); printf("\nEnter any 4 digit number:");
scanf("%d",&num);
n1=num%10;
n2=num/1000;
sum=n1+n2;
printf("\nSum of 1st and last digit=%d",sum);
getch();
}
************************************************************************************
//Program to find the reverse of a 3 digit number
//entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,n1,n2,rev;
clrscr();
printf("\nEnter any 3 digit number:");
scanf("%d",&num);
n1=num%10;
num=num/10;
n2=num%10;
num=num/10;
rev=n1*100+n2*10+num;
printf("\nReverse of 3 digit number=%d",rev);
getch();
}
***************************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 12/143
12
KeywordsKeywords are the words whose meaning has been already explained to the ‘C’ compiler. The
keywords cannot be used as variables. There are 32 keywords in a ‘C’ language. The keywords arealso called reserve words.
E.g. if, int, else, float, goto.
The 32 keywords are as follows:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
Do if static while
Data Type
Data type specifies the size and arrangement of memory storage for an object of that type.
Variable Declaration
Every variable must have a datatype. Use a type specifier, such as char, int, short or long to show the
variables type.
Syntax: type name[value];
Data Type in ‘C’
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 13/143
13
Character (char): 1 byte
Integer (int): Positive 2 bytes
Float (float): 4 bytes
Data Type Modifiers
Signed/Unsigned type: Signed on integer in actual is redundant as the default integer assumes
signed no. Signed is used to modify character (char), as character by default is unsigned. Unsigned can be
applied to float. Long/Short type: Long or short are applied to basic types. They are used when an integer of
shorter or longer length than its normal length is required. Short is 16 bits, long is 32 bits.
E.g. int a, char p, float length, double area, long distance, short miles.
C-Tokens
In a passage of text, individual words and punctuation marks are called as tokens. Similarly in a
C-program, the smallest individual units are known as C-Tokens. C has 6 types of tokens.
E.g. float E.g. – 15.5 E.g. max E.g. “ABC” E.g. +, -, *, / E.g. { }
while 100 amount(amt)“XYZ”
[ ]
if “name” !
Identifier
Identifier refers to the names of variables, functions and arrays. These are user-defined names
and consist of sequence of letters and digits with a letter as a first character.
Both uppercase and lowercase letters are permitted and the underscore( _ ) is also permitted
while defining the identifiers.
C-Tokens
Keywords SpecialConstants Identifier Strings Operators
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 14/143
14
Types of C Constants
C-Constants can be divided into two major categories: Primary Constants
Secondary Constants
These constants are further categorized as follows:
For constructing these different types of constants certain rules have been laid down and
they are as follows:
Rules for Constructing Integer Constants
An integer constant must have at least one digit.
C- Constants
Primary Constants Secondary Constants
CharacterNumericArrays
PointersStructures
Union
Real
Constants
Integer
Constants
Character String Constant
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 15/143
15
It must not have a decimal point.
It could be either positive or negative.
If no sign precedes an integer constant it is assumed to be positive.
No commas or blanks are allowed within an integer constant.
The allowable range for integer constants is – 32768 to +32767 for 16-bit numbers. It is defined in a
program as ‘int’.
E.g. 426, +782, -8000, -7605
E.g.
Invalid Valid2_9 -15
-13m 2903
1.9 0
Rules For Constructing Real Constants
Real Constants are often called Floating Point Constants. The real constants can be written in two forms,
Fractional form and Exponential form.
Rules for constructing real constants expressed in Fractional form:
A real constant must have at least one digit.
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a real constant.
E.g. +325.34, 426.0, -32.76, -48.5792
The exponential form of representation of real constant is usually used if the value of the
constant is either too small or too large.
In exponential form of representation, the real constant is represented in two parts. The part
appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.
Rules for constructing real constants expressed in exponential form:
The mantissa part and the exponential part should be separated by a letter ‘e’.
The mantissa part may have a positive or negative sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit which must be a positive or negative integer.
Default sign is positive.
Range of real constants expressed in exponential form is – 3.4e38 to 3.4e38.
E.g. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5
Rules For Constructing Character Constants
Rules for Constructing Single Character Constants
A character constant is either a single alphabet, a single digit or a single special symbol enclosed
within single inverted commas. Both the inverted commas should point to the left. For example,
’A’ is a valid character constant whereas ‘A’ is not.
The maximum length of a character constant can be 1 character.
E.g. ’x’, ’z’, ’9’, ’=’
String Constants
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 16/143
16
String: It is a sequence of characters.
Rules For Constructing String Constants
It consists of multiple characters.
It is represented in double quotation marks.
E.g. “Chester”, “x=ymg”
Variable Names
Variable names are names given to locations in the memory of computer where different constants are stored.
These locations can contain integer, real or character constants.
Rules For Constructing Variable Names
It must begin with a letter. Some system permits underscore ( _ ) as a first character .
It is a combination of 1 to 8 characters. Some compilers allow the length of 40 characters.
No commas or blanks are allowed for constructing the variables.
It should not be a keyword.
No special symbol other than underscore can be used.
It is case sensitive.
E.g.
Valid Invalid
x_y x-y
x y
DatatypesIt allows the programmer to select the type appropriate to the need of the application. It
supports four classes.
Primary Datatype
User-Defined Datatype
Derived Datatype
Empty data set
Primary Datatype
There are 3 types of primary datatype.
Integer (int)
Real/Float (float)
Character (char)
Integer (int)
int (16-bit)
short int (8-bit)
long int (32-bit)
unsigned short int (32-bit)
unsigned long int (64-bit)
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 17/143
17
Character (char)
Signed char
Unsigned char
Float/Real (float)
Float
Double
Long double
Size and Ranges
1 byte=8 bits
Datatype Range Size
Char -128 to +127 1 byte
Int -32768 to +32767 2 bytes
Float 3.4e-38 to 3.4e+38 4 bytes
Double 1.7e-308 to 1.7e+308 8 bytes
Declaration of Primary Data types
Syntax: datatype a1, a2, a3 - - - - - - -an;
E.g. int xyz;
float val;
char name[20];
float sal;
User-Defined Datatype
User-Defined type declaration
Syntax: typedef type identifier;
Where, type refers to existing datatype and identifier refers to the new name given to
datatype.
E.g. typedef int xyz;
typedef int sal;
C-Instructions
Type Declaration Instruction
Input/Output Instruction
Arithmetic Instruction
Control Instruction
Type Declaration Instruction
This instruction is used to declare the type of variables being used in the program. Any
variable used in the program must be declared before using it in any statement. It is usually
written at the beginning of the C-Program.
E.g. int a; float amount;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 18/143
18
Input/Output Instruction
This instruction is used to perform the function of supplying input data to a program
and obtaining the output results from it.
E.g. printf( ), scanf( )
Arithmetic Instruction
This instruction is used to perform arithmetic operations between constants and
variables.
E.g. c=a+2b;
In this instruction one arithmetic operator is used and also one assignment operator is
used.
This instruction is divided into 3 types.
Integer Mode: In this mode arithmetic integer variables and arithmetic integer
constants are used. E.g. int i;
i=i+2;
Real Mode: In this mode real variables and real constants are used.
E.g. float b;
float c;
c=3.2+b;
Mixed Mode: In this mode some operands are integer and some operands are real.
E.g. float b;
int c;
float a;
a=b+c+3
Note: C allows the variables or constants with arithmetic operators on the left
side of equation.
In C language 3+a=b is an invalid expression whereas b=3+a is a valid
expression.
Control Instructions
This instruction is used to control the sequence of execution of various
statements.
E.g. while, for
Integer and float conversions
The rules that are used for the implicit conversion of floating point and integer values in C are asfollows:
An arithmetic operation between an integer and integer always yields an integer result.
Operation between a real and real always yields a real result.
Operation between an integer and real always yields a real result.
E.g.
Operation Result Operation Result
5/2 2 2/5 0
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 19/143
19
5.0/2 2.5 2.0/5 0.4
5/2.0 2.5 2/5.0 0.4
5.0/2.0 2.5 2.0/5.0 0.4
Type Conversion in Assignments
It may happen that the type of the expression and the type of the variable on the left side of the
assignment operator may not be same. In such a case the value of the expression is promoted
or demoted depending on the type of the variables on the left side of =.
E.g.
int i;
float b;
i=3.5;
b=30;
Here in the first assignment statement though the expression’s value is a float(3.5) it cannot be
stored in ‘i’ since it is an integer. In such a case the float is demoted to an intege r and then its
value is stored. Hence what gets stored in ‘i’ is 3. Exactly opposite happens in the next
statement. Here, 30 is promoted to 30.000000 and then stored in ‘b’, since ‘b’ being a float
variable cannot hold anything except a float value.Thus while storing the value the expression always takes the type of the variable into which its
value is being stored.
Consider the complex expression in the given program fragment:
float a, b, c;
int s;
s=a*b*c/100+32/4-3*1.1;
Here, in the assignment statement some operands are integers whereas others are floats. As we
know during evaluation of the expression the integers would be promoted to floats and the
result of the expression would be a float. But when this float value is assigned to ‘s’ it is again
demoted to an integer and then stored in ‘s’.
E.g. ‘k’ is an integer variable and ‘a’ is a real variable.
Arithmetic
Instruction
Result Arithmetic
Instruction
Result
k=2/9 0 a=2/9 0.0
k=2.0/9 0 a=2.0/9 0.2222
k=2/9.0 0 a=2/9.0 0.2222
k=2.0/9.0 0 a=2.0/9.0 0.2222
k=9/2 4 a=9/2 4.0
k=9.0/2 4 a=9.0/2 4.5
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 20/143
20
k=9/2.0 4 a=9/2.0 4.5
k=9.0/2.0 4 a=9.0/2.0 4.5
Hierarchy of Operations
1st priority *, /, %
2nd priority +, -
3rd priority =
The priority or precedence in which the operations in an arithmetic statement are performed is called
as Hierarchy of operations.
The usage of operators in general is as follows:
In case of a tie between operations of same priority preference is given to the operator,
which occurs first. For example, consider the statement,
z = a*b+c/d;
Here, a*b will be performed before c/d even though * and / has same or equal priority. This is
because * appears prior to the / operator.
Also, if there are more than one set of parentheses, the operations within the innermost
parentheses will be performed first, followed by the operations within the second innermost pair
and so on.
Always, a pair of parentheses should be used. Imbalance of the right and left parentheses is a
common error.
Q.1 Determine the hierarchy of operations and evaluate the following expression:
i = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8
Stepwise evaluation of this expression is shown below:i = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8
i = 6 / 4 + 4 / 4 + 8 – 2 + 5 / 8 Operation : *
i = 1 + 4 / 4 + 8 – 2 + 5 / 8 Operation : /
i = 1 + 1 + 8 – 2 + 5 / 8 Operation : /
i = 1 + 1 + 8 – 2 + 0 Operation : /
i = 2 + 8 – 2 + 0 Operation : +
i = 10 – 2 + 0 Operation : +
i = 8 + 0 Operation : -
i = 8 Operation : +
Q.2 Determine the hierarchy of operations and evaluate the following expression:
k = 3 / 2 * 4 + 3 / 8 + 3
Stepwise evaluation of this expression is shown below:
k = 3 / 2 * 4 + 3 / 8 + 3
k = 1 * 4 + 3 / 8 + 3 Operation : /
k = 4 + 3 / 8 + 3 Operation : *
k = 4 + 0 + 3 Operation : /
k = 4 + 3 Operation : +
k = 7 Operation : +
1) ab – cd = a * b – c * d
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 21/143
21
2) (m + d) (x + y) = (m * d) * (x + y)
3) 2x2 + 5x + 15 = 2 * xe2 + 5 * x + 15
4) x + y + z = ( x + y + z) / (b + c)
b + c
5) 3xy - y
m + 2 3(m+2) =(3* x*y)/(m+2) – (y/3* (m+2))
Q.1 WAP to calculate the area of triangle.
Q.2 WAP to calculate the area of square.
Q.3 WAP to calculate the area and circumference of a circle.
Q.4 WAP to calculate the area of a triangle when three sides of a triangle are given.Q.5 WAP to interchange two integer variables.
With using 3rd variable.
Without using 3rd variable.
Q.6 WAP to convert Fahrenheit into Celsius.
Q.7 WAP to convert Pound into kilograms.
Q.8 WAP to calculate area and volume of a sphere.
Q.9 WAP to convert Kilometers into meters.
Q.10 WAP to convert Byte into bits, kilobytes, megabytes.
Q.11 WAP to calculate the sum of digits of three-digit number entered by user.
Q.12 WAP to calculate the sum of 1st and last digit of four-digit number.
Q.13 WAP to find the reverse of three-digit number.
stdio.h
getchar() gets() printf()
putchar() puts() scanf()
(For single (multiple (multiple
character character characteri/o) i/o including i/o but in
space) formatted
manner
without
space)
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 22/143
22
**************************************************** ************************
//WAP to print a single character using getchar() and putchar()
#include<stdio.h>
#include<conio.h>void main()
{
char a;
clrscr();
a=getchar();
putchar(a);
getch();
}
**********************************************************************
//WAP to print a string without space using printf() and scanf()
#include<stdio.h>
#include<conio.h>
void main()
{
char username[20];
clrscr();
printf("\nEnter your name:");
scanf("%s",&username);
printf("\nUsername=%s",username);
getch();
}
*********************************************************************************
//WAP to print a string including space using gets() and puts
#include<stdio.h>
#include<conio.h>
void main()
{
char username[20];
clrscr();
printf("\nEnter your name:");
gets(username);
printf("Username=");
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 23/143
23
puts(username);
getch();
}
*****************************************************************************
//WAP to print the name of the student using gets() and puts(), print
//the marks of maths, science nad english and also print the total and
//average of the student.
#include<stdio.h>#include<conio.h>
void main()
{
int maths, sci, eng;
float total, avg;
char sname[20];
clrscr();
printf("\nEnter the name of a student:");
gets(sname);
printf("\nEnter the marks of maths, science and english:");
scanf("%d %d %d",&maths,&sci,&eng);
total=maths+sci+eng;avg=total/3;
clrscr();
printf("********************Student Details***********************");
printf("\nThe name of the student is:");
puts(sname);
printf("The marks of Maths is:%d",maths);
printf("\nThe marks of Science is:%d",sci);
printf("\nThe marks of English is:%d",eng);
printf("\nThe total marks of the student is:%f",total);
printf("\nThe average of the student is:%f",avg);
printf("\n**********************************************************");
getch();
}
***********************************************************************
//WAP which prints the employee no, employee name and salary and using it
//calculate its da, hra and total salary.
#include<stdio.h>
#include<conio.h>
void main()
{
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 24/143
24
int eno;
float salary,da,hra,ts;
char ename[20];
clrscr();
printf("\nEnter the name of the employee:");
gets(ename);
printf("\nEnter the Employee id:");
scanf("%d",&eno);
printf("\nEnter the salary of the employee:");
scanf("%f",&salary);
da=0.35*salary;
hra=0.11*salary;
ts=da+hra+salary;
clrscr();
printf("******************Employee Details***********************");
printf("\nThe name of the employee is:");
puts(ename);
printf("The employee id is:%d",eno);
printf("\nThe salary of the employee is:%f",salary);
printf("\nDA:%f",da);
printf("\nHRA:%f",hra); printf("\nTotal Salary of the employee is:%f",ts);
printf("\n*********************************************************");
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 25/143
25
Operators in CThere are 8 types of operators in C and they are:
Arithmetic Operators
Relational Operators
Logical Operators
Conditional Operators
Assignment Operators
Increment and Decrement Operators
Bitwise Operators
Special type Operators.
Arithmetic Operators
Arithmetic Operators are +, -, *, /, %.
OP1 OP2 RESULT
int Int int
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 26/143
26
int float float
float int float
float float float
Relational Operators
Relational Operators are> (greater than)
< (less than)
>= (greater than equal to)
<= (less than equal to)
= = (Equal to)
!= (Not Equal to)
Assignment Operator (=)
Syntax: Vop=Exp
Where V: Variable,
Op: Arithmetic Operator (+, -, *, /)
=: Assignment Operator
Exp: Any expression
E.g. 1) a=a+2;
Or
a+=2
2) b=b+(89+c)
Or
b+=89+c
3) d=d%8+c
Or
d%=8+c
4) d=d/8%cOr
d/=8%c
Conditional Operator
It consist of ?(Question mark) and :(colon)
Syntax: Exp1 ? Exp2 : Exp3
True False
E.g. a<b ? printf(“T”) : printf(“F”).
Logical Operators
1) Logical AND (&&)
2) Logical OR ( || )
3) Logical NOT ( ! )
Logical AND
Expression1(Exp1) Expression2(Exp2) Result
T T T
T F F
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 27/143
27
F F F
Logical OR
Expression1(Exp1) Expression2(Exp2) Result
T T T
T F F
F F F
Logical NOT
Expression Result
T F
F T
Increment and Decrement Operators
+ + : Increment Operator
- - : Decrement Operator
Pre Increment:
E.g. m=5
y=++m
Post Increment:
E.g. m=5
y=m++
The Increment or Decrement Operator, increases or decreases the value by 1 only.
In Pre-Increment first the value will be incremented and then it will be assigned to variable.
Therefore, y=6
m=6
In E.g. m=5
y=++m
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 28/143
28
the value of m is incremented first and then it will get assigned to the variable y and hence the
output will be y=6, m=6
Post Increment Operator
m=5;
y=m++;
Here the values of m will get assigned first to variable y and then it will be incremented by 1.
Therefore, output is y=5, m=6
Similarly for Pre Decrement
E.g. m=5;y=--m;
will give the output
y=4
m=4
and for Post Decrement
E.g. m=5;
y=m--;
will give the output
y=5
m=4
Note: In this Operator, increment or decrement is by 1 only.
Bitwise Operator& - Bitwise AND
| - Bitwise OR
^ - Bitwise X-OR
>> - Bitwise Right Shift
<< - Bitwise Left Shift
Special Operator
& - address of
sizeof();
. - Dot operator
, - comma operator etc.
Decision Control Structure
Programming Techniques in C
Sequential Programming
Conditional Programming
Looping
Sequential Programming
Sequence Control Structure is the one in which the various steps are executed sequentially, i.e. in the same
order in which they appear in the program. By default the instructions in a program are executed
sequentially.
Conditional Programming Many times, it may be required that a set of instructions to be executed in one
condition and an entirely different set of instructions to be executed in another condition. This kind of
condition is used in C programs using a decision control instruction.
Decision control instruction can be implemented in C using:
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 29/143
29
1) If statement.
2) If-else statement.
3) If-else-if statement.
4) Switch-case statement.
For checking the conditions in C program, ‘if’ and ‘else’ statement is used.
Syntax:
a) If(condition)
Statement;
b) If(condition)
{
statement 1;
statement 2;
statement 3;
}
if(condition)
statement;
else
statement;
if(condition)
{statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}
If the condition in ‘if’ statement is true then the ‘C’ statements in ‘if’ block are executed and if the condition
in ‘if’ statement is false then the ‘C’ statements in ‘else’ block are executed ignoring the ‘C’ statements in ‘if’
block.
TrueFalse
START
INPUT
if a>b
B is greater A is greater
STOP
False True
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 30/143
30
#include<stdio.h>
#include<conio.h>
void main()
{
int maths,sci,eng;
float total,avg;
char sname[20];
clrscr();
printf("\nEnter the name of the student:");
gets(sname);
printf("\nEnter the marks of maths, science and english:");
scanf("%d %d %d",&maths,&sci,&eng);
total=maths+sci+eng;
avg=total/3;
printf("\nStudent name is:");
puts(sname);
if(avg<35)
printf("\nResult is Fail");
else if(avg>=35 && avg<45)
printf("\nResult is Third division");
else if(avg>=45 && avg<60) printf("\nResult is Second division");
else if(avg>=60 && avg<75)
printf("\nResult is first division");
else if(avg>=75 && avg<101)
printf("\nResult is Distinction");
getch();
}
**********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,great;
clrscr();
printf("\nEnter any two numbers:");
scanf("%d %d",&a,&b); //89 78
great=a; //89
if(a<b)
great=b; //89
printf("\nThe greatest number is %d",great);
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 31/143
31
If-else-statement:It is used to carry out a logical test and then take one of the two possible actions, depending
on the outcome of the test(true or false).
Syntax: if(expression)
statement;
else
statement;
If the ‘if’ expression evaluates to true, the statement or block following the ‘if’ is executed,
otherwise statement block follows the else part.
void main(){
int a,b;
clrscr();
printf(“ \ nEnter any two numbers:”);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“ \ nA is greatest”);
else
printf(“ \ nB is greatest”);
getch();
}
Nested ifs
If(exp1)
{
If(exp2)
Statement 1;
If(exp3)
Statement 2;
Else
Statement 3;
}
Else
Statement 4;
OR
If(condition)
{
If(condition)
{
_______
_______
}
Else
{_______
________
}
}
Else
{
If(condition)
{
______
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 32/143
32
_______
}
Else
{
_____
_____
}
}
Example of Nested if’s
**********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
x=y=0;
clrscr();
printf("\nEnter choice(1-3):");
scanf("%d",&x);
if(x==1){
printf("\nEnter value for y(1-5):");
scanf("%d",&y);
if(y<=5)
printf("\nThe value of y is %d",y);
else
printf("\nThe value of y exceeds 5");
}
else
printf("\nChoice entered was not one");
getch();
}***********************************************************************
If-else-if Statement:
Syntax: if(expression)
statement;
else
if(expression)
statement;
else
if(expression)statement;
else
statement;
The conditions in this case are evaluated top to bottom. As soon as a true expression is found, the statement
associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the
final else is executed.
#include<stdio.h>
#include<conio.h>
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 33/143
33
void main()
{
int x;
x=0;
clrscr();
printf("\nEnter choice(1-3):");
scanf("%d",&x);
if(x==1)
printf("\nChoice is 1");
else if(x==2)
printf("\nChoice is 2");
else if(x==3)
printf("\nChoice is 3");
else
printf("\nInvalid Choice");
getch();
}
***********************************************************************
Switch StatementThe switch statement causes a particular group of statements to be chosen from several available groups. The
selection is based upon the current value of an expression that is included within the switch statement.
E.g. switch(expression)
statement;
//WAP to check whether the entered number is even or odd.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 34/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 35/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 36/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 37/143
37
#include<conio.h>
void main()
{
int a,x,b,y,m,c,d,n,t;
clrscr();
printf("\nEnter the input:");
scanf("%d %d %d %d %d %d",&m,&n,&a,&b,&c,&d);
t=a*d-c*b;
if(t!=0)
{
x=m*d-n*b/t;
y=n*a-m*c/t;
printf("\nThe values for x and y are %d %d",x,y);
}
if(t==0)
printf("\nInfinite Result");
getch();
}
***********************************************************************
//WAP to find the largest number in 3 entered number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,n3;
clrscr();
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&n1,&n2,&n3);
if(n1>n2)
{
if(n1>n3)
{ printf("\nLargest number is n1");
}
else
printf("\nn3 is largest");
}
else
{
if(n2>n3)
printf("\nn2 is largest");
else
printf("\nn3 is largest");
}
getch();}
***********************************************************************
//WAP which reads a marks of 5 subjects entered by student and check whether
//the student has passed or fail. If passed calculate the percentage marks
//of student and also print the division of the student.
#include<stdio.h>
#include<conio.h>
void main()
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 38/143
38
{
int m1,m2,m3,m4,m5,per;
clrscr();
printf("\nEnter the marks of 5 subjects:");
scanf("%d %d %d %d %d",&m1,&m2,&m3,&m4,&m5);
if(m1>=40 && m2>=40 && m3>=40 && m4>=40 && m5>=40)
{
printf("\nStudent is passed");
per=(m1+m2+m3+m4+m5)/5;
if(per>=75)
printf("\nCongrats, U have got distinction");
if(per>=60 && per<=74)
printf("\nFirst division");
if(per>=50 && per<=59)
printf("\nSecond division");
if(per>=40 && per<=49)
printf("\nThird division");
}
else
printf("\nSorry, U are fail");
getch();}
**********************************************************************
//WAP which reads a 4 digit number and check whether it is in the form
//AABB, if found check whether it is a perfect square.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,orin,d1,d2,d3,d4,a;
clrscr(); printf("\nEnter a 4 digit number:");
scanf("%d",&num);
orin=num;
d1=num%10;
num=num/10;
d2=num%10;
num=num/10;
d3=num%10;
num=num/10;
d4=num;
if(d1==d2 && d3==d4 && d2!=d3)
{
printf("\nNumber is in the form AABB");
a=sqrt(orin);
if(a*a==orin)
{
printf("\nNumber is a perfect square");
}
else
printf("\nNumber is not a perfect square");
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 39/143
39
else
printf("\nNumber is not in the form AABB");
getch();
}
***********************************************************************
//WAP to accept 2 integers and divide bigger by smaller number.
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,x;
clrscr();
printf("\nEnter the values of a and b:");
scanf("%f %f",&a,&b);
if((a>b) && (b!=0))
{
x=a/b;
printf("\n%f",x);
}else
if((b>a) && (a!=0))
{
x=b/a;
printf("\n%f",x);
}
getch();
}
***********************************************************************
//WAP to find whether the entered year is a leap year or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("\nEnter the year:");
scanf("%d",&year);
if((year%4==0 && year%100!=0) || (year%400==0))
{
printf("\nThe year is a leap year");
}
else
printf("\nThe year is not a leap year");
getch();
}
***********************************************************************
//WAP for function of calculator which performs addition, subtraction,
//multiplication and division.
#include<stdio.h>
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 40/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 41/143
41
scanf("%d",&age);
if(age<1)
printf("\nMinor Category");
else if(age>=1 && age<18)
printf("\nMedium Category");
else if(age>=18 && age<45)
printf("\nMajor Category");
else if(age>=45 && age<70)
printf("\nHighest Category");
else
printf("\nWrong Age");
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 42/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 43/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 44/143
44
getch();
}
***********************************************************************
Switch-case Statements
In switch case statements the switch statement causes a particular group of statements to be chosenfrom several available groups.
Syntax:
switch(choice)
{
case 1: statement 1;
break;
case 2: statement 2;
break;
case 3: statement 3;
break;
default: statement;
}
Start
Case 1
Case 2
Case 3
Stop
Statement 3
Statement 1
Statement 2
Yes
YesNo
No
No
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 45/143
45
//WAP for addition,subtraction,multiplication,division and modular division
//using switch case.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
clrscr();
printf("\nMENU\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.MOD");
printf("\nEnter your choice:");
scanf("%d",&d);
printf("\nEnter any two numbers:");
scanf("%d %d",&a,&b);
switch(d)
{
case 1: c=a+b;
printf("\nThe result for addition is:%d",c); break;
case 2: c=a-b;
printf("\nThe result for subtraction is:%d",c);
break;
case 3: c=a*b;
printf("\nThe result for multiplication is:%d",c);
break;
case 4: c=a/b;
printf("\nThe result for division is:%d",c);
break;
case 5: c=a%b;
printf("\nThe result for modular division is:%d",c); break;
default:printf("\nInvalid Choice");
}
getch();
}
***********************************************************************
//WAP which prints the season according to the month entered
//using switch case
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("\nEnter month number:");
scanf("%d",&n);
switch(n)
{
case 12:
case 1:
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 46/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 47/143
47
case 1:
printf(“I am in case 1\ n”);
case 2:
printf(“I am in case 2 \ n”);
case 3:
printf(“I am in case 3 \ n”);
default:
printf(“I am in default \ n”);
}getch();
}
Output of the program:
I am in case 2
I am in case 3
I am in default
But the expected output of the above program was “I am in case 2”. This output can be achieved by
getting out of the control structure then and there by using a break statement. Note that there is no need
for a break statement after the default, since the control comes to the end anyway. It is as follows:
main(){
int i=2;
clrscr();
switch(i)
{
case 1:
printf(“I am in case 1 \ n”);
break;
case 2:
printf(“I am in case 2 \ n”);
break;
case 3:
printf(“I am in case 3\ n”);
break;
default:
printf(“I am in default \ n”);
}
getch();
}
Output:
I am in case 2
Usage of Switch
It is not necessary that only cases arranged in ascending order, 1, 2, 3 and default can be used. Cases can
be written in any order we want.
E.g.
main()
{
int i=22;
clrscr();
switch(i)
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 48/143
48
{
case 121:
printf(“I am in case 121 \ n”);
break;
case 7:
printf(“I am in case 7 \ n”);
break;
case 22:
printf(“I am in case 22 \n”);break;
default:
printf(“I am in default \ n”);
}
getch();
}
Output:
I am in case 22
It is also allowed to use character values in case and switch.
E.g.
main(){
char c=’x’;
clrscr();
switch(c)
{
case ‘v’:
printf(“I am in case v \ n”);
break;
case ‘a’:
printf(“I am in case a \ n”);
break;
case ‘x’:
printf(“I am in case x \ n”);
break;
default:
printf(“I am in default \ n”);
}
getch();
}
Integer and character constants can be mixed in different cases of a switch.
E.g.
main(){
char c=3;
clrscr();
switch(c)
{
case ‘v’:
printf(“I am in case v \ n”);
break;
case 3:
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 49/143
49
printf(“I am in case 3 \ n”);
break;
case 12:
printf(“I am in case 12 \ n”);
break;
default:
printf(“I am in default \ n”);
}
getch();}
Sometimes there may not be any statement in some of the cases in switch, but still they
might turn out to be useful.
E.g.
//WAP to print the colours of the rainbow according to the alphabets entered
//(uppercase or lowercase) using switch case.
#include<stdio.h>
#include<conio.h>
void main()
{
char choice;clrscr();
printf("\nSelect rainbow colour VIBGYOR:");
scanf("%c",&choice);
switch(choice)
{
case 'v':
case 'V': printf("\nViolet");
break;
case 'i':
case 'I': printf("\nIndigo");
break;
case 'b':case 'B': printf("\nBlue");
break;
case 'g':
case 'G': printf("\nGreen");
break;
case 'y':
case 'Y': printf("\nYellow");
break;
case 'o':
case 'O': printf("\nOrange");
break;
case 'r':
case 'R': printf("\nRed");
break;
default: printf("\nWrong Colour Entered");
}
getch();
}
****************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 50/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 51/143
51
//WAP to calculate a simple interest for 3 sets of p,n, and r using//whileloop and draw its flowchart representation.
#include<stdio.h>
#include<conio.h>
void main()
{
int p,n,count;
float r,si;
clrscr();
count=1;
while(count<=3)
{
printf("\nEnter values of p,n and r:");scanf("%d %d %f",&p,&n,&r);
si=p*n*r/100;
printf("\nSimple Interest=Rs.%f",si);
count=count+1;
}
getch();
}
START
initialize
test
body of loop
increment
STOP
False
True
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 52/143
52
Rules for representation of while loop.
The statements within the while loop would keep on getting executed till the condition being
tested remains true. When the condition becomes false, the control passes to the first
statement that follows the body of the while loop.
The condition being tested may use relational or logical operators as shown in the following
examples: while(i<=10)
while(i<=10 && j<=15)
while(j>10 && (b<15 || c<20))
The statement within the loop may be a single line or a block of statements. In the first case
the parentheses are optional. For E.g.
while(i<=10)
i=i+1;
is same as
while(i<=10){
i=i+1;
}
There are variety of operators which are frequently used with while. Consider a program
wherein numbers from 1 to 10 are to be printed on the screen. The program for performing
this task can be written using while in the following different ways:
1) main()
{
START
count=1
iscount<=3
INPUT
si=p*n*r/100
PRINT si
count=count+1
STOP
NO
YES
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 53/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 54/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 55/143
55
}
//WAP to find the sum of all the even numbers from 1 to 100.
#include<stdio.h>
#include<conio.h>
void main()
{int i=2,s=0;
clrscr();
while(i<=100)
{
s=s+i;
i=i+2;
}
printf("The sum of even numbers from 1 to 100 is %d",s);
getch();
}
***********************************************************************
//WAP to print the numbers from 1 to 30 which is divisible by 3.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
while(i<=30)
{
i++;
if(i%3==0)
printf("%d\n",i);
}
getch();
}
**********************************************************************
//WAP to print even numbers from 1 to 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
i++;
if(i%2==0)
printf("%d\n",i);
}
getch();
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 56/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 57/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 58/143
58
//WAP to check whether an entered number is armstrong or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,d,sum=0,orin;
clrscr();
printf("\nEnter any number:");
scanf("%d",&num);
orin=num;
while(num!=0)
{
d=num%10;
sum=sum+d*d*d;
num=num/10;
}
if(sum==orin)
printf("\nNumber is armstrong");
else printf("\nNumber is not armstrong");
getch();
}
**********************************************************************
//WAP which counts the number of digits in a number entered by user.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,d,count=0;
clrscr(); printf("\nEnter any number:");
scanf("%d",&num);
while(num!=0)
{
count=count+1; //count++;
num=num/10;
}
printf("\n%d",count);
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 59/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 60/143
60
//WAP to print numbers from 1 to 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i=1;
clrscr();
do
{
printf("%d\n",i);
i++;
}while(i<=10);
getch();
}
***********************************************************************
//WAP to print the numbers divisible by 3 from 1 to 30.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i=1;
clrscr();
do
{
i++;
if(i%3==0) printf("%d\n",i);
}while(i<=30);
getch();
}
********************************************************************
//WAP to print even numbers from 1 to 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i=1;
clrscr();
do
{
i++;
if(i%2==0)
printf("%d\n",i);
}while(i<=10);
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 61/143
61
getch();
}
**********************************************************************
//WAP to print the odd numbers from 10 to 20.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
i=10;
clrscr();
do
{
i++;
if(i%2==1)
printf("%d\n",i);
}while(i<20);
getch();
}**********************************************************************
FOR LOOPThe FOR statement includes an expression that specifies an initial value for an Index, another
expression that determines whether or not to continue the loop (conditional test) and a third
expression that allows the index to be modified at the end of each pass.
Syntax:
for(initialization; condition; updation)
{
________________
________
}
The WHILE and FOR loop are same in terms of execution. They vary only in terms of their
representation as the execution of both the loops are same, all the programs written as “while”
loop can be successfully be written by FOR loop
Flowchart representation of FOR loop.
C-statements
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 62/143
62
//WAP to calculate the simple interest using FOR loop and also give the
//flowchart representationof a program.
/*Calculation of simple interest for 3 sets of p,n and r*/
#include<stdio.h>
#include<conio.h>
void main()
{
int p,n,count;
float r,si;
clrscr();
for(count=1;count<=3;count=count+1)
{
printf("\nEnter values of p,n and r:");
scanf("%d %d %f",&p,&n,&r);
si=p*n*r/100;
printf("\nSimple Interest=Rs.%f\n",si);
}
getch();
}
START
initialize
Body of loop
increment
START
True
False
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 63/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 64/143
64
Q.1 WAP to print numbers from 1 to 10 in different ways using FOR loop.
a) main()
{
int i;
for(i=1;i<=10;i=i+1)
printf(“%d \ n”,i);
}
b) main()
{
int i;
for(i=1;i<=10;)
{
printf(“%d \ n”,i);
i=i+1;
}
}
c) main()
{int i=1;
for(;i<=10;i=i+1)
printf(“%d \ n”,i);
}
d) main()
{
int i=1;
for(;i<=10;)
{
printf(“%d \ n”,i);
i=i+1;
}
}
e) main()
{
int i;
for(i=0;i++<10;)
printf(“%d \ n”,i);
}
f) main(){
int i;
for(i=0;++i<10;)
printf(“%d \ n”,i);
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 65/143
65
//WAP to check the number is divisible by 3. If yes, print from 1 to 30.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=30;i++)
{
if(i%3==0)
printf("%d\n",i);
}
getch();
}
***********************************************************************
//WAP to print all odd numbers from 10 to 20.
#include<stdio.h>
#include<conio.h>void main()
{
int i;
clrscr();
for(i=10;i<=20;i++)
{
if(i%2==1)
printf("%d\n",i);
}
getch();
}
**********************************************************************
Nesting of Loops
The way ‘if’ statements can be nested, similarly while loop and for loop can also be nested. A ‘For’
loop is said to be nested when it occurs within another ‘FOR’. The code will be similar to
for(i=1;i<max1;i++)
{
________
________
for(j=0;j<max2;j++)
{
_________
_________
}
_________
_________
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 66/143
66
/*WAP to print numbers 1 to 5, four times i.e the output should be
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=5;j++)
{
printf("%d ",j);
}
printf("\n");}
getch();
}
*********************************************************************
/*WAP to print the output as
A B C D E F
A B C D E F
A B C D E F
A B C D E F
A B C D E F
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=65;j<=70;j++)
{
printf("%c ",j);
}
printf("\n");
}
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 67/143
67
/*WAP to print the output as
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
} printf("\n");
}
getch();
}
********************************************************************
/*WAP to print the output as
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
printf("\n");
}
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 68/143
68
/*WAP to print output as
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
} printf("\n");
}
getch();
}
*********************************************************************
/*WAP to print output as
*
* *
* * *
* * * *
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 69/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 70/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 71/143
71
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("\nEnter any number:");
scanf("%d",&num);
for(i=2;i<=num;i++)
{
if(num%i==0)
{
printf("\nNumber %d is prime",num);
break;
}
else if(num%i==1)
{
printf("\nNumber %d is not prime",num);
break;
}}
if(num==1)
printf("\nNumber %d is not prime",num);
getch();
}
3) goto statement: This is an unstructured programming instruction which transfers program
control to the statement whose prefix is label. General format is: goto
label;
goto statement allows jump in and out of blocks violating rules of a structured programming.
The label is an identifier which must be preceded by a semicolon to mark the end of
the goto statement.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a;
float sqr;
stop:
printf("\nEnter only positive numbers");
clrscr(); printf("\nEnter any number:");
scanf("%d",&a);
if(a<0)
goto stop;
else
{
sqr=sqrt(a);
printf("\nSquare root of a no=%f",sqr);
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 72/143
72
getch();}
***********************************************************************
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a;
float sqr;
clrscr();
printf("\nEnter any number:");
scanf("%d",&a);
if(a<0)
goto stop;
else
{
sqr=sqrt(a);
printf("\nSquare root of a no=%f",sqr);
}
stop: printf("\nEnter positive numbers only");getch();
}
4) continue statement:
The continue statement causes the next iteration of the enclosing loop to
begin. When this statement is encountered in the program, the remaining statement
in the body of the loop are skipped and the control is passed to the re-initialization
step. For ‘for’ loop continue causes the increment of the portion of loop and then the
conditional test to execute whereas for, while and do-while loops, program control
passes to the conditional tests. When the keyword continue is encountered inside
any C loop, control automatically passes to the beginning of the loop. A continue is
usually associated with an if. Note that when the value of i equals that of j, the
continue statement takes the control to the for loop(inner) bypassing rest of the
statements pending execution in the for loop.(inner). Usually continue is associated
with ‘if’ statement. It allows to take control beginning of the loop.
Void main()
{
int i;
for(i=1;i<=50;i++)
{
if(i%2==0)
continue;
printf(“%d”,i);}
getch();
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 73/143
73
Above program prints odd number from 1 to 50.
Void main()
{
int i,j;
for(i=1;i<=2;i++)
{for(j=1;j<=2;j++)
{
if(i==j)
continue;
printf(“ \n%d %d\ n”,i,j);
}
}
getch();
}
Output:
1 2
2 1
Exit( ) function
This is a standard e-library function which is said to break out of the program and not just out of a loop.
An exit() is generally used to check if a mandatory condition for a program is satisfied or not. The
general form of exit() is
exit(int return code);
Zero is generally used as a return code to indicate normal program termination.
Odd loop
The loop which is controlled by user is known as odd loop i.e. every execution of the loop is decided by
user.
While(1) loop
This is a loop used for creating a infinite loop because here 1 is considered as a “true” value. So to
terminate this loop exit(); function is used. This is a function which takes the control out of the program.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 74/143
74
Q. Write a difference between break and exit().
Break Exit()
The syntax of break is break; The syntax of exit is exit();
Break is a statement Exit is a function.
It takes the control out of the loop. It takes the control out of the program.
Eg: main()
{int i=1;
for( ; ; )
{
printf(“%d”,i);
i++;
break;
}
printf(“ \ n abc”);
getch();
}
Eg: main()
{int i=1;
for( ; ; )
{
printf(“%d”,i);
i++;
exit();
}
printf(“ \ n abc”);
getch();
}
Output:
1
abc
Output:
1
Note:
The statement while(1) puts the entire logic in an indefinite loop. This is necessary since
the menu must keep reappearing on the screen once an item is selected and the
appropriate action taken.
Exit() is a standard library function. When it gets executed the program execution is
immediately terminated. Note that a break would not have worked here because it
would have taken the control only outside the switch and not outside the while.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 75/143
75
//WAP for addition,subtraction,multiplication,division and modular division
//using switch case.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d;
clrscr();
while(1)
{
printf("\nMENU\n1.ADD\n2.SUB\n3.MUL\n4.DIV\n5.MOD\n6.exit");
printf("\nEnter your choice:");
scanf("%d",&d);
if(d==6)
goto e;
else if(d>6)
goto r;
printf("\nEnter any two numbers:");
scanf("%d %d",&a,&b);
switch(d){
case 1: c=a+b;
printf("\nThe result for addition is:%d",c);
break;
case 2: c=a-b;
printf("\nThe result for subtraction is:%d",c);
break;
case 3: c=a*b;
printf("\nThe result for multiplication is:%d",c);
break;
case 4: c=a/b;
printf("\nThe result for division is:%d",c); break;
case 5: c=a%b;
printf("\nThe result for modular division is:%d",c);
break;
e: case 6: exit();
break;
r: default:printf("\nInvalid Choice");
}
}
getch();
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 76/143
76
Functions
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,s;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d %d",&n1,&n2);
s=add(n1,n2);
printf("%d",s);
getch();
}add(int x,int y)
{
int res;
res=x+y;
return(res);
}
Note: Return returns a single value and also passes
the control from called function to calling function.
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
int sum=0;
clrscr();
printf("\nEnter any two numbers:");
scanf("%d %d",&x,&y);
sum=adder(x,y);
printf("\nAddition of x & y is %d",sum);
getch();
}
adder(int a,int b)
{
int total;
total=a+b;
return(total);
}
**********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 77/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 78/143
78
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z,m;
clrscr();
printf("\nEnter any three numbers:");
scanf("%d %d %d",&x,&y,&z);
m=max(x,y,z);
printf("%d",m);
getch();
}
max(int a,int b,int c)
{
int mx; mx=a;
if(b>mx)
mx=b;
if(c>mx)
mx=c;
return(mx);
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
#include<math.h>qroot(float,float,float);
void main()
{
float a,b,c;
clrscr();
printf("\nEnter the values of a,b and c:");
scanf("%f %f %f",&a,&b,&c);
qroot(a,b,c);
getch();
}
qroot(float a,float b,float c)
{
float t,x1,x2;
t=b*b-4*a*c;
if(t<0)
{
printf("\nRoots are imaginary");
}
if(t>0)
{
printf("\nRoots are real and distinct");
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 79/143
79
x1=-b+sqrt(t)/(2*a);
x2=-b-sqrt(t)/(2*a);
printf("%f %f",x1,x2);
}
if(t==0)
{
printf("\nRoots are real and equal");
x1=-b/(2*a);
x2=x1;
printf("%f %f",x1,x2);
}
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
x=20;
y=10;clrscr();
printf("\nValue assign in x=%d and in y=%d",x,y);
swap(&x,&y);
printf("\nAfter swapping value x=%d and y=%d",x,y);
getch();
}
swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;*y=temp;
printf("\nOn swapping the values of x=%d and y=%d",*x,*y);
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
x=20;
y=10;
clrscr();
printf("\nValue assign in x=%d and in y=%d",x,y);
swap(x,y);
printf("\nAfter swapping value x=%d and y=%d",x,y);
getch();
}
swap(int x,int y)
{
int temp;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 80/143
80
temp=x;
x=y;
y=temp;
printf("\nValue of x and y in swap function is x=%d and y=%d",x,y);
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
square(float);
void main()
{
float a=2.5,sq;
clrscr();
sq=square(a);
printf("%f",sq);
getch();
}
square(float n)
{
float s;s=n*n;
return(s);
}
**********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
float a=2.5,sq,square(float);
clrscr();
sq=square(a); printf("%f",sq);
getch();
}
float square(float n)
{
float s;
s=n*n;
return(s);
}
***********************************************************************
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 81/143
81
Functions
A function is a self-contained block of statements that perform a coherent task of some kind. Every C
program can be thought of as a collection of these functions.Functions breaks large computing tasks into smaller ones. The specified tasks is repeated each time the
program calls the function.
When a function is called, the program execution is transferred to the first statement in the called
function.
General form of a function:
function(arg1, arg2, arg3)
type arg1, arg2, arg3;
{
Statement 1;
Statement 2;
Statement 3;
Statement 4;
}
The function which calls the other function is called as Calling Function whereas the function which is being
called is called as
Called Function.
The function name followed with pair of brackets and a semicolon is known as Calling Function whereas
function name followed with pair of brackets without a semicolon is known as Called Function.Eg:
void main()
{
message();
printf(“ \ nC++ primer plus”);
getch();
}
message()
{
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 82/143
82
printf(“ \nC++ cout object”);
}
Output of the program
C++ cout object
C++ Primer Plus
Here, through main() we are calling the function message(). Thus, main() becomes the “Calling Function”,
whereas message() becomes the “Called Function”.
If the arguments are present, before beginning with the statements in the functions it is necessary to declare
the type of the arguments through type declaration statements.
Calling More than One Function
Eg:
void main()
{
printf(“ \ nPointers”);c1( );
c2( );
c3( );
}
c1( )
{
printf(“ \ nPointers 1”);
}
c2( )
{
printf(“ \ nPointers 2”);
}
c3( )
{
printf(“ \ nPointers 3”);
}
Output:
Pointers
Pointers1
Pointers2
Pointers3
Conclusion:
Any C program contains atleast one function.
If a program contains only one function, it must be main().
In a C program if there are more than one functions present, then one (& only one) of these functions
must be main(), because program execution always begins with main().
There is no limit on the number of functions that might be present in a C program.
Each function in a program is called in the sequence specified by the function calls in main().
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 83/143
83
After each function has done its task, control returns to main(). When main() runs out of function
calls, the program ends.
Eg:
void main()
{
printf(“ \ nPointers”);
c1( );printf(“ \ nPointers 1”);
getch();
}
c1( )
{
printf(“ \ nPointers 2”);
c2( );
printf(“ \ nPointers 3”);
}
c2( )
{
printf(“ \ nPointers 4”);
c3( );
}
c3( )
{
printf(“ \ n Pointers 5”);
}
Output of the program:
Pointers
Pointers 2Pointers 4
Pointers 5
Pointers 3
Pointers 1
There are 2 types of functions available in C language.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 84/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 85/143
85
sum=calsum(a,b,c);
In the calsum() function these values get collected in three variables x, y and z:
calsum(x,y,z)
int x, y, z;
The variables a, b and c are called ‘actual arguments’,
whereas the variables x, y and z are called ‘formal arguments’. Any number of arguments can be
passed to a function being called. However, the type, order and number of the actual and formal
arguments must always be same.
Instead of using different variable names x, y, z; the same variable names a, b and c can alsobe used. But the compiler would still treat them as different variables since they are in different
functions.
a) There are two methods of declaring the formal arguments
The method used in the program for the statements:
calsum(x, y, z)
int x, y, z;
is known as Kernighan and Ritchie (or just K & R) method.
Another method is:
calsum(int x, int y, int z)
b) Mostly in programs when the closing brace( } ) of the
called function is encountered the control returns to the calling function. No separate return
statement is required to send back the control. This will work, if the called function is not going
to return any meaningful value to the calling function. In the above program, as the sum of x, y
and z is to be returned, therefore it is necessary, to use the return statement.
The return statement serves two purposes:
1) On executing the return statement it immediately
transfers the control back to the calling program.
2) It returns the value present in the parentheses afterreturn, to the calling program. In the above program the value of sum of 3 numbers is being
returned.
3) There is no restriction on the number of return
statements that may be present in a function. Also, the return statement need not always be
present at the end of the called function.
E.g.
fun( )
{
char ch;
clrscr();
printf(“ \n Enter any alphabet:”);
scanf(“%c”,&ch);
if(ch>=65 && ch<=90)
return(ch);
else
return(ch+32);
getch();
}
In this function different return statements will be executed depending on whether ch is capital
or not.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 86/143
86
c) Whenever the control returns from a function some value
is definitely returned. If a meaningful value is returned then it should be accepted in the calling
program by equating the called to some variable.
sum=calsum(a, b, c);
d) The valid return statements are as follows:
return(a);
return(23);return(12.34);
return;
In the last statement a garbage value is returned to the calling function since we are not
returning any specific value. Note that in this case the parentheses after return are dropped.
e) If it is required that a called function should not return any value, then the keyword void is
written as below:
void display( )
{
printf(“ \n xyz - - ”);
printf(“ \n pqr - - ”);
getch( );
}
f) A function can return only one value at a time. Thus, the given statements are invalid.
return(a,b);
return(x,12);
g) If the value of a formal argument is changed in the called function, the corresponding change
does not take place in the calling function.
E.g.
main( )
{
int a=30;
clrscr();
fun(a);
printf(“ \ n %d”,a);
getch();
}
fun(int b)
{
b=60;
printf(“ \ n %d”,b);
}
Output
60
30
Thus, even though the value of b is changed in fun( ), the value of a in main( ) remains
unchanged.
Function Declaration and Prototypes
In some programming situations it may happen that a called function should not return any
value. This is made possible by making use of the keyword void.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 87/143
87
void main()
{
void gospel();
gospel();
}
void gospel()
{
printf(“ \ n xyz”);
printf(“ \ n pqr”);printf(“ \ n abc”);
}
Here, the gospel() function has been defined to return void; means it would return nothing.
Therefore, it would just flash the three messages and return the control back to the main
function.
Call by Value and Call by Reference
Whenever a function is called and something is passed to it, always values (of variables) are
passed for the variables to the called function. Such function calls are called “Call by value”.
This means that on calling a function we are passing values of variables to it.
Example of call by value is as shown below:
sum=calsum(a,b,c);
Also, it is known that variables are stored somewhere in memory. So, instead of the value of the
variable, the location number(also called address) of the variable can also be passed to the
function which is called as “Call by reference”.
Consider the function with arguments and no return value.
//fun_swap.c
Q.7 WAP which uses function with arguments and returning value i.e., by using call by value. //fun_adde.c
Q.8 WAP which uses function with address as arguments and return value.
//fun_rswp.c
Recursion
A function is called “recursive” if a statement within the body of a function calls the same function.
Recursive function can be effectively used in application in which the solution to a program can be
expressed in terms of successively applying the same solution to subsets of program. Recursion
means a function call to itself.
Q.9 WAP which computes the factorial value of an integer.
Without using recursive function. //precur.c
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 88/143
88
Using recursive function. //prec1.c
Factorial of number 5 using recursion:
rec(5) returns (5 times rec(4),
which returns (4 times rec(3),
which returns (3 times rec(2),
which returns (2 times rec(1),
which returns (1))))).
#include<stdio.h>
#include<conio.h>
rec(int);
main()
{
int a, fact;
clrscr();
printf("\nEnter any number");
scanf("%d", &a);
fact= rec(a);
printf("factorial value = %d", fact);
getch();
}
rec(x)
int x;
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
factorial(int);
main()
{
int a, fact;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 89/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 90/143
90
*******************************************************************/
//stclass3.c#include<stdio.h>
#include<conio.h>
void main()
{
auto int i=1;
clrscr();
{ auto int i=2;
{
auto int i=3;
printf("\n%d ",i);
}
printf("%d ",i);
}
printf("%d ",i);
getch();}
/**************************OUTPUT***********************************
3 2 1
********************************************************************///stclass4.c
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for(i=1;i<=10;i++)
printf("\n%d",i);
getch();
}
********************************************************************
//stclass5.c
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
increment()
{
auto int i=1;
printf("%d\n",i);
i=i+1;
}
/****************************OUTPUT***********************
1
1
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 91/143
91
1
**********************************************************/
//stclass6.c
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
increment();
increment();
increment();
getch();
}
increment()
{
static int i=1;
printf("%d\n",i);
i=i+1;
}
/*******************************OUTPUT*************************
1//Stclass7.c
#include<stdio.h>
#include<conio.h>
int i;
void main()
{
clrscr();
printf("\ni=%d",i);
increment();
increment();
decrement();
decrement();getch();
}
increment()
{
i=i+1;
printf("\nOn incrementing i=%d",i);
}
decrement()
{
i=i-1;
printf("\nOn decrementing i=%d",i);
}
/************************OUTPUT*********************************
i=0
On incrementing i=1
On incrementing i=2
On decrementing i=1
On decrementing i=0
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 92/143
92
****************************************************************/
//stclass8.c
#include<stdio.h>
#include<conio.h>
int x=21;
void main()
{
extern int x;
clrscr();
printf("\n%d",x);
getch();
}
*****************************************************************
//stclass9.c
#include<stdio.h>
#include<conio.h>
int x=10;
void main()
{
int x=20;
clrscr();
printf("\n%d",x);
display();
getch();}
display()
{
printf("\n%d",x);
}
/*****************************OUTPUT*************************
20
10
*************************************************************/
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 93/143
93
Storage Classes in C
From C compiler’s point of view, a variable name identifies some physical location within the computer
where the string of bits representing the variable’s value is stored. There are basically two kinds of locations
in a computer where such a value may be kept: Memory and CPU registers. It is the variable’s storage class
which determines in which of these two locations the value is stored. Moreover, a variable’s storage class
represents that Where the variable would be stored?
What will be the initial value of the variable, if the initial value is not specifically assigned? (i.e. the
default initial value)
What is the scope of the variable i.e. in which functions the value of the variable would be available.
What is the life of the variable i.e. how long would the variable exist.
There are four storage classes in C.
Automatic storage class
Register storage class
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 94/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 95/143
95
These declarations are wrong because the CPU registers in a microcomputer are usually 16 bit registers and
therefore cannot hold a float value or a double value, which require 4 and 8 bytes respectively for storing a
value. For the above declarations error messages are not displayed, only the compiler treats the variables to
be of automatic storage class.
Static Storage Class:
Storage : Memory
Default initial value : zero
Scope : Local to the block in which the variable is defined.
Life : Value of the variable persists between different function calls.
Consider the comparison of automatic storage class and static storage class using the given program.
//stclass5.c
//stclass6.c
Like auto variables, static variables are also local to the block in which they are declared. The
difference between them is that static variables don’t disappear when the function is no longer active.
Their values persist. If the control comes back to the same function again the static variables have
the same values they had last time around.
External Storage Class
Storage: Memory
Default initial value: zero Scope: Global
Life: As long as the program’s execution doesn’t come to an end.
External variables are declared outside all functions, yet are available to all functions that use them.
E.g: stclass7.c
i is available to the functions increment() and decrement() since i has been declared outside all functions.
The function that uses an external variable should declare that variable external i.e., the keyword extern,
as shown below:
//stclass8.c
The use of extern inside a function is optional as long as it is declared outside and above that function in
the same source code file.
Consider the given program:
//stclass9.c
Here, the local variable gets preference over the global variable hence for the printf(), present in main()
output is 20. When display() is called and control reaches the printf(), the value of the global x i.e., 10 is
printed.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 96/143
96
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 97/143
97
Pointers
A Pointer is a variable that represents the location (address) of a variable, within the computer memory.
Also, Pointers are special type of variables which stores the address of some another variable.
Consider the declaration,
int i=3;
This declaration indicates the C compiler to:
Reserve space in memory to hold the integer value.
Associate the name i with this memory location.
Store the value 3 at this location.
i’s location in memory is represented by following memory map.
i
value at location
65524 location number (address)
From the above description, it is seen that the compiler has selected memory location 65524 as the place to
store value 3. The location number 65524 is not a number to be relied upon, because some other time the
compiler may choose a different location for storing value 3. The important point is i’s address in memory is
65524.
The following program can print address number:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("\nAddress of i=%u", &i);
printf("\nValue of i=%d", i);
getch();
}
/****************************OUTPUT********************************
Address of i=65524 Value of i=3
*******************************************************************/
3
location name
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 98/143
98
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("\nAddress of i=%u", &i);
printf("\nValue of i=%d",i);
printf("\nValue of i=%d",*(&i));
getch();
}
/*******************************OUTPUT********************************
Address of i=65524
Value of i=3
Value of i=3
**********************************************************************/#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("\nAddress of i=%u", &i);
printf("\nValue of i=%d", i);
getch();
}
/****************************OUTPUT********************************
Address of i=65524 Value of i=3
*******************************************************************/
& is C’s ‘address of’ operator.
The address is printed out using %u which is a format specifier for printing an unsigned integer and
since 65524 represents an address, there is no question of sign being associated with it.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value
stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.
E.g.
hv
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 99/143
99
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("\nAddress of i=%u", &i);
printf("\nValue of i=%d",i);
printf("\nValue of i=%d",*(&i));
getch();
}
/*******************************OUTPUT********************************
Address of i=65524
Value of i=3
Value of i=3
**********************************************************************/
The expression &i gives the address of the variable i. This address can be collected in a variable, by j=&i;
j is a variable which contains the address of other variable. (i in this case)
i j
65524 65522
i’s value is 3 and
j’s value is i’s address.
Since j is a variable which contains the address of i, it is declared as,
int *j;
This declaration means that j will be used to store the address of an integer value. Also, * stands for
‘value at address’. Thus int *j also means that the value at the address contained in j is an integer.
3 65524
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 100/143
100
************************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
j=&i;
clrscr();
printf("\nAddress of i=%u",&i);
printf("\nAddress of i=%u",j);
printf("\nAddress of j=%u",&j);
printf("\nValue of j=%u",j);
printf("\nValue of i=%d",i);
printf("\nValue of i=%d",*(&i));
printf("\nValue of i=%d",*j);
getch();}
/********************************OUTPUT*******************************
Address of i=65524
Address of i=65524
Address of j=65522
Value of j=65524
Value of i=3
Value of i=3
Value of i=3
**********************************************************************/
Consider the declarations,
int *alpha;
char *ch;
float *s;
Here alpha, ch and s are declared as pointer variables i.e., variables capable of holding addresses.
Addresses are always going to be whole numbers, therefore pointers always contain whole numbers.
*s means s is going to contain the address of a floating point value. Similarly char *ch
Is going to contain the address of a char value or in other words, the value at address stored in ch is
going to be a character.
Pointer is a variable which contains address of another variable. This variable itself might be
another pointer. Thus pointer may contain, another pointer’s address. This concept is explained in
the example given below:
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 101/143
101
***********************************************************************
#include<stdio.h>
#include<conio.h>
main()
{
int i=3, *j, **k;
j=&i;
k=&j;
clrscr();
printf("\nAddress of i=%u", &i); //65524
printf("\nAddress of i=%u", j); //65524
printf("\nAddress of i=%u", *k); //65524
printf("\nAddress of j=%u", &j); // 65522
printf("\nAddress of j=%u", k); //65522
printf("\nAddress of k=%u", &k); //65520
printf("\nValue of j=%u", &j); //65522
printf("\nValue of j=%u", &k); //65520 printf("\nValue of j=%u", j); //65524
printf("\nValue of k=%u", k); //65522
printf("\nValue of i=%d", i); //3
printf("\nValue of i=%d", *(&i)); //3
printf("\nValue of i=%d",*j); //3
printf("\nValue of i=%d",**k); //3
getch();
}
***********************************************************************
i j k
65524 65522 65520
Variables j and k are declared as:
int i, *j, **k;
Here i is an ordinary int, j is a pointer to an int (also called an integer pointer) whereas k is a pointer
to an integer pointer.
Consider an example,
i j k
6328 9123 5926
l m
2222
2223 5555
3 65524 65522
259 91236328
22225926
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 102/143
102
************************************************
#include<stdio.h>
#include<conio.h>
main()
{
int i=3, ****m = & l;
int *j = &i,**k=&j, ***l= &k;
clrscr();
printf("\n%u", &i); //65524
printf("\n%d", *(&i)); //3
printf("\n%d", **k); //3
printf("\n%u", **m); //5133
printf("\n%u", ***(&l)); //61
printf("\n%u", *(&j)); //12803
printf("\n%d", ****m); //3
printf("\n%u", **(&m)); //767
printf("\n%u", ***(&m)); //5133getch();
}
**********************************************************************
&i=6328
*(&i)=*6328=259
**k=**9123=*6328=259
**m=**2222=*5926=9123
***(&l)=***2222=**5926=*9123=6328
*(&j)=*9123=6328
****m=****2222=***5926=**9123=*6328=259
**&m=**5555=*2222=5926***&m=***5555=**2222=*5926=912
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("\nEnter a and b:");
scanf("%d %d",&a,&b);
swap(&a,&b);
printf("\nThe result after swapping is:%d %d",a,b);
getch();
}
swap(int *a1, int *b1)
{
int c;
c=*a1;
*a1=*b1;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 103/143
103
*b1=c;
}
************************************************
#include<stdio.h>
#include<conio.h>
areacir(float ,float *, float *);
main()
{
float r, area,cir;
clrscr();
printf("\nEnter radius");
scanf("%f",&r);
areacir(r,&area,&cir);
printf("\nThe Area:%f, The circumference:%f",area,cir);
getch();
}
areacir(float r1, float *a, float *c)
{
*a= 3.142*r1*r1;
*c=2*3.142*r1;}
***********************************************
#include<stdio.h>
#include<conio.h>
sum(int,int,int,int *, float *);
main()
{
int a,b, c, s;
float avg;
clrscr();
printf("\nEnter the values of a,b,c");
scanf("%d%d%d", &a,&b,&c);sum(a,b,c, &s, &avg);
printf("the sum :%d, the avg :%f", s,avg);
getch();
}
sum(int a1,int a2, int a3, int *s1, float *a)
{
*s1=a1+a2+a3;
*a=*s1/3.0;
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 104/143
104
Arrays
An array is defined as a set of homogenous data item.Sometimes it can be required to assign different
values to the variables store only one value at a time that is last value so because of this drawback
arrays are used to store more than one value at the same memory location. Array is a collection of
similar elements where similar elements can be all integers or all characters or all floats. It is a
collection of similar datatypes arranged in a contigeous memory location.
Syntax:Datatype Name of the array [Dimension of the array]
int A [5];
float X [10];
The variable having only one subscript is a single subscripted variable or also known as one dimensional
array.
Example:
Suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a
case we have two options to store there marks in memory.1. Construct 100 variables to store percentage marks obtained by 100 different student i.e., each
variable containing one student’s marks.
2. Construct one variable (called array or subscripted variable) capable of storing or holding all
hundred values.
Definition of array in other words
“An array is a collective name given to a group of similar quantities that could be percentage marks of
100 students or salaries of 300 employee usually array of character is called a string”
Defining Arrays
a[0] a[1] a[2] a[3] a[4]
int a[10]
200 a[0]
202 a[1]
204 a[2]
int a[5];
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 105/143
105
206 a[3]
208 a[4]
210 a[5]
212 a[6]
214 a[7]
216 a[8]
218 a[9]
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i;
clrscr();
for(i=0;i<=9;i++)
{
printf("\nEnter the element:");
scanf("%d",&a[i]);
}for(i=0;i<=9;i++)
{
printf("\n%d",a[i]);
}
getch();
}
/**************************OUTPUT*********************************
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Enter the element:5
Enter the element:6
Enter the element:7
Enter the element:8
Enter the element:9
Enter the element:10
1
2
3
4
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 106/143
106
5
6
7
8
9
10
********************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
float avg,sum=0;
int i;
int marks[30]; /*array declaration*/
clrscr();
for(i=0;i<=29;i++)
{ printf("\nEnter marks:");
scanf("%d",&marks[i]); /*store data in array*/
}
for(i=0;i<=29;i++)
sum=sum+marks[i]; /*read data from an array*/
avg=sum/30;
printf("\nAverage marks=%f",avg);
getch();
}
***********************************************************************
#include<stdio.h>
#include<conio.h>void main()
{
int number[10];
int great,i;
clrscr();
printf("\nEnter any ten numbers:");
for(i=0;i<10;i++)
{
scanf("%d",&number[i]);
}
great=number[0];
for(i=1;i<10;i++)
{
if(great<number[i])
great=number[i];
}
printf("\nThe greatest number is %d",great);
getch();
}
/*******************************OUTPUT*********************************
Enter any ten numbers:90
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 107/143
107
89
78
67
56
98
45
64
34
23
The greatest number is 98
***********************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,pcount=0,ncount=0;
int zcount=0,a[20];
clrscr();
for(i=0;i<=19;i++)
{ printf("\nEnter the element:");
scanf("%d",&a[i]);
}
for(i=0;i<=19;i++)
{
if(a[i]<0)
ncount++;
if(a[i]>0)
pcount++;
if(a[i]==0)
zcount++;
} printf("%d %d %d",ncount,pcount,zcount);
getch();
}
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
float x[20],ele;
int i,c=0;
clrscr();
printf("\nEnter the 20 elements:");
for(i=0;i<=19;i++)
{
scanf("%f",&x[i]);
}
printf("\nEnter the element for count:");
scanf("%f",&ele);
for(i=0;i<=19;i++)
{
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 108/143
108
if(ele==x[i])
{
c++;
}
}
printf("\n%d",c);
getch();
}
*************************************************
Boundary Checking
In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with
a subscript exceeding the array size will simply in be placed memory outside the array; probably on top of
other data, or on the program itself. This will lead to unpredictable results, their will be no error message
that array size has been exceeded.
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main(){
int num[40],i;
clrscr();
for(i=0;i<=100;i++)
num[i]=i;
getch();
}
******************************************************
Passing Array Elements to a Function
Array elements can be passed to a function by calling the function by value, or by reference. In the call by
value we pass values of array elements to the function, whereas in the call by reference we pass addresses of
array elements to the function.
******************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[]={55,65,75,56,78,78,90};
clrscr();
for(i=0;i<=6;i++)
display(marks[i]);
getch();
}
display(int m)
{
printf("%d ",m);
}
/****************************OUTPUT*********************************
55 65 75 56 78 78 90
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 109/143
109
********************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[]={55,65,75,56,78,78,90};
clrscr();
for(i=0;i<=6;i++)
display(&marks[i]);
getch();}
display(int *n)
{
printf("%d ",*n);
}
/*****************************OUTPUT***********************************
55 65 75 56 78 78 90
***********************************************************************/
******************************************************
Pointers and Arrays
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
printf("\nValue of i=%d",i);
printf("\nValue of j=%f",j);
printf("\nValue of k=%c",k);
x=&i;
y=&j;
z=&k;
printf("\nOriginal address in x=%u",x);
printf("\nOriginal address in y=%u",y);
printf("\nOriginal address in z=%u",z);
x++;
y++;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 110/143
110
z++;
printf("\nNew address in x=%u",x);
printf("\nNew address in y=%u",y);
printf("\nNew address in z=%u",z);
getch();
}
/*****************************OUTPUT*********************************
Value of i=3
Value of j=1.500000
Value of k=c
Original address in x=65524
Original address in y=65520
Original address in z=65519
New address in x=65526
New address in y=65524
New address in z=65520
*********************************************************************/
Rules for Initialization
int mark[5]={88,90,67};
it will be stored asint mark[5]={88,90,67,0,0};
For character initialization
char name[6]=”Sneha”;
char name[6]={‘S’,’N’,’E’,’H’,’A’, \0};
The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus, the
following operations can be performed on a pointer:
a) Addition of a number to a pointer.
E.g.: int i=4,*j,*k;
j=&i;
j=j+1;
j=j+9;
k=j+3;
b) Subtraction of a number from a pointer.
E.g.: int i=4, *j,*k;
j=&i;
j=j-2;
j=j-5;
k=j-6;
c) Subtraction of one pointer from another.
One pointer variable can be subtracted from another provided both variables point to elements of thesame array. The resulting value indicates the number of bytes separating the corresponding array
elements.
E.g.:
main()
{
int arr[]={10,20,30,45,67,56,74};
int *i,*j;
i=&arr[1];
j=&arr[5];
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 111/143
111
printf(“%d %d”,j-i,*j-*i);
}
Here i and j have been declared as integer pointers holding addresses of first and fifth element of the
array respectively.
Suppose the array begins at location 4002, then the elements arr[1] and arr[5] would be present at
locations 4004 and 4012 respectively, since each integer in the array occupies two bytes in memory. The
expression j-i would print a value 4 and not 8. This is because j and i are pointing to locations which are 4
integers apart. The result of the expression *j-*i is 36 since *j and *i return the values present ataddresses contained in the pointers j and i.
Comparison of two pointer variables.
Pointer variables can be compared provided both variables point to objects of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array. The
comparison can test for either equality or inequality. Moreover a pointer variable can be compared with
zero (usually expressed as NULL).
E.g.:
main()
{
int arr[]={10,20,36,72,45,36};int *j,*k;
j=&arr[4];
k=(arr+4);
if(j==k)
printf(“ \ nThe two pointers point to the same location”);
else
printf(“ \ nThe two pointers do not point to the same location”);
}
Correlation between two facts.
a) Array elements are always stored in contiguous memory locations.
b) A pointer when incremented always points to an immediately next location of its type.
Consider an array num[]={24,34,12,44,56,17}
The following figure shows how this array is located in memory.
24 34 12 44 56 17
4001 4003 4005 4007 4009 4011
#include<stdio.h>
#include<conio.h>
void main()
{
int num[]={24,34,12,44,56,17};
int i;
clrscr();
for(i=0;i<=5;i++)
{
printf("\nElement no:%d",i);
printf(" Address:%u",&num[i]);
}
getch();
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 112/143
112
}
/*************************OUTPUT**********************************
Element no:0 Address:65514
Element no:1 Address:65516
Element no:2 Address:65518
Element no:3 Address:65520
Element no:4 Address:65522
Element no:5 Address:65524
******************************************************************/
Note that the array elements are stored in contiguous memory locations, each element occupying two bytes,
since it is an integer array.
Each address will be 2 bytes greater than its immediate predecessor.
********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int num[]={24,34,12,44,56,17};int i;
clrscr();
for(i=0;i<=5;i++)
{
printf("\nAddress:%u",&num[i]);
printf(" Element:%d",num[i]);
}
getch();
}
/****************************OUTPUT**********************************
Address:65514 Element:24
Address:65516 Element:34 Address:65518 Element:12
Address:65520 Element:44
Address:65522 Element:56
Address:65524 Element:17
*********************************************************************/
***************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int num[]={24,34,12,44,56,17};
int i,*j;
clrscr();
j=&num[0]; /*assign address of zeroeth element */
for(i=0;i<=5;i++)
{
printf("\nAddress:%u",j);
printf(" Element:%d",*j);
j++; /*increment pointer to point to next location*/
}
getch();
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 113/143
113
}
/*****************************OUTPUT*******************************
Address:65514 Element:24
Address:65516 Element:34
Address:65518 Element:12
Address:65520 Element:44
Address:65522 Element:56
Address:65524 Element:17
********************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int num[]={24,34,12,44,56,17};
clrscr();
display(&num[0],6);
getch();
}
display(int *j,int n){
int i;
for(i=0;i<=n-1;i++)
{
printf("\nElement:%d",*j);
j++; /*increment pointer to point to next location*/
}
}
/***************************OUTPUT*****************************
Element:24
Element:34
Element:12Element:44
Element:56
Element:17
***************************************************************/
***********************************************************************
Note that the address of the zeroth element(many a times called the base address) can also be passed by just
passing the name of the array. Thus, the following two function calls are same:
display(&num[0],6);
display(num,6);
Consider the following array.
24 34 12 44 56 17
4001 4003 4005 4007 4009 4011
The above array is declared in C as:
int num[]={24,34,12,44,56,17};
On mentioning the name of the array we get its base address. Thus, by *num, we can refer to the zeroth
element of the array, that is, 24. i.e. *num and *(num+0) both refer to 24.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 114/143
114
Similarly, *(num+1) refer to the first element of the array i.e. 34. For num[i], the C compiler internally
converts it to *(num+i). All the following notations are same:
num[i]
*(num+i)
*(i+num)
i[num]
******************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int num[]={24,34,12,44,56,17};
int i;
clrscr();
for(i=0;i<=5;i++)
{ printf("\nAddress:%u",&num[i]);
printf(" Element:%d %d",num[i],*(num+i));
printf(" %d %d",*(i+num),i[num]);
}
getch();
}
/********************************OUTPUT*********************************
Address:65514 Element:24 24 24 24
Address:65516 Element:34 34 34 34
Address:65518 Element:12 12 12 12
Address:65520 Element:44 44 44 44 Address:65522 Element:56 56 56 56
Address:65524 Element:17 17 17 17
***********************************************************************
More than one dimension
Multidimensional Arrays
Two Dimensional Arrays
The two dimensional array is also called a matrix.
int student[4][2] ;
Col 0 col 1
rows columns
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 115/143
115
ro
r1
r2
r3
Total No of elements =total No. Of Rows *
Total No. Of Columns = 4 * 2 =8
***********************************************************************
#include<stdio.h>#include<conio.h>
void main()
{
int stud[4][2];
int i,j;
clrscr();
for(i=0;i<=3;i++)
{
printf("\nEnter rollno and marks:");
scanf("%d %d",&stud[i][0],&stud[i][1]);
}
for(i=0;i<=3;i++) printf("\n%d %d",stud[i][0],stud[i][1]);
getch();
}
/******************************OUTPUT**************************
Enter rollno and marks:01 89
Enter rollno and marks:02 78
Enter rollno and marks:03 67
Enter rollno and marks:04 65
1 89
2 78
3 67
4 65
*****************************************************************/
1
2
3 4
5 6
7 8
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 116/143
116
col.no 0 col.no 1
row no. 0
row no. 1
row no. 2
row no. 3
Initializing a 2-Dimensional Array
int stud[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78}
};
OR
int stud[4][2]={1234,56,1212,33,1434,80,1312,78};
It is important to note that while initializing an array it is necessary to mention the second (column)
dimension, whereas the first dimension (row) is optional. Thus the declarations,
int arr[2][3]={12,34,23,45,56,45};
int arr[ ][3]={12,34,23,45,56,45};
are valid.
whereas,
int arr[2][ ]={12,34,23,45,56,45};
int arr[ ][ ]={12,34,23,45,56,45};
are invalid.
Memory Map of a 2-Dimensional Array
The arrangement shown in Fig. a is only conceptually true. This is because memory doesn’t contain rows and
columns, In memory whether it is a one-dimensional or a two-dimensional array, the array elements arestored in one continuous chain. The arrangement of array elements of a 2-dimensional array in memory is
shown below:
s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]
1234 56 1212 33 1434 80 1312 78
5002 5004 5006 5008 5010 5012 5014 5016
printf(“Marks of 3rd student=%d”,stud[2][1]);
1234 56
1212 33
1434 80
1312 78Fig. a.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 117/143
117
will refer to the 3rd student.
Pointers & 2-Dimensional Arrays
2-D array is an array of arrays.
#include<stdio.h>
#include<conio.h>void main()
{
int s[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78},
};
int i,j;
clrscr();
for(i=0;i<=3;i++)
printf("\nAddress of %dth 1-D array=%u",i,s[i]);
getch();
}
/**************************OUTPUT************************************
Address of 0th 1-D array=65510
Address of 1th 1-D array=65514
Address of 2th 1-D array=65518
Address of 3th 1-D array=65522
*********************************************************************/
Here, 5 is an integer array. So each element of this array occupies 2 bytes. There are 2 elements in each row,so each row takes 4 bytes.
The following expressions refer to the same element.
s[2][1]
*(s[2]+1)
*(*(s+2)+1)
*************************************************
#include<stdio.h>
#include<conio.h>
void main()
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 118/143
118
{
int s[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78},
};
int i,j;
clrscr();
for(i=0;i<=3;i++)
{
printf("\n");
for(j=0;j<=1;j++)
printf("%d ",*(*(s+i)+j));
}
getch();
}
/******************************OUTPUT********************************
1234 56
1212 331434 80
1312 78
*********************************************************************/
Three Dimensional Array
Initializing a 3 dimensional array
int arr[3][4][2]={
{
{2,4},
{7,8},
{3,4},
{5,6}
},
{
{7,6},
{3,4},
{5,3},
{2,3}
},
{
{8,9},
{7,2},
{3,4},
{5,1}
2 4 4 4
7 8 3 1
3 4 3
5 6
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 119/143
119
};
};
A 3-dimensional array can be thought of as an array of arrays of arrays.
2nd 2-D Array
1st 2-D Array
0th 2-D Array
In memory the same array elements are stored as
2 4 7 8 3 4 5 6 7 6 3 4 5 3 2 3 8 9 7 2 3 4 5 1
Following expressions refer to the same element in the 3-D array.
arr[2][3][1]
*(*(*(arr+2)+3)+1).
Array of Pointers
The way there can be
an array of int’s or an
array of float’s,
similarly there can be an array of pointers. Since a pointer variable always contains an address, an array of
pointers would be nothing but a collection of addresses.
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
int *arr[4];
int i=31,j=5,k=19,l=71,m;
clrscr();
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
for(m=0;m<=3;m++)
printf("%d ",*(arr[m]));getch();
}
/*************************OUTPUT*********************************
31 5 19 71
***************************************************/
8 9
31 195 71
0th
2-D Array 1st 2-D Array 2nd 2-D Array
i j k l
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 120/143
120
4008 5116 6010 7118
arr[0] arr[1] arr[2] arr[3]
4008 5116 6010 7118
7602 7604 7606 7608
An array of pointers can even contain the addresses of other arrays.
main()
{
int a[]={0,1,2,3,4};
int *p[]={a,a+1,a+2,a+3,a+4};
printf(“ \ n%u %u %d”,p,*p,*(*p));
}
Printing of string
#include<stdio.h>
#include<conio.h>
void main()
{
char name[]="Klinsman";
int i=0;
clrscr();
while(i<=7)
{
printf("%c",name[i]);
i++;
}
getch();
}
/***************************OUTPUT******************************
Klinsman
****************************************************************/
Here we have initialized a character array, & then printed out the elements of the array within a while loop.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 121/143
121
String Functions
A string constant is a one dimensional array of characters terminated by a null(‘ \ 0’). For E.g.:
char name[]={‘H’,’A’,’E’,’S’,’L’,’E’,’R’,’ \ 0’};
Each character in the array occupies one byte of memory and the last character is always ‘ \ 0’.
The terminating null(‘ \ 0’) is important, because it is the only way the functions that work with a string can
know where the string ends. In fact, a string not terminated by a ‘ \ 0’ is not really a string, but merely a
collection of characters.
H A E S L E R \0
4001 4002 4003 4004 4005 4006 4007 4008
The above string can also be initialized as:
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 122/143
122
char name[]=”HAESLER”;
Here C inserts the null character automatically so; in this declaration ‘ \ 0’ is not necessary.
Each character array always ends with a ‘ \ 0’ so program can be written without using the final value (7) in
while loop.
***********************************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
char name[]="Klinsman";
int i=0;
clrscr();
while(name[i]!='\0')
{
printf("%c",name[i]);
i++;
}
getch();
}
/****************************OUTPUT**********************************
Klinsman
*********************************************************************/
Pointer to access the array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
char name[]="Klinsman";
char *ptr;
clrscr();
ptr=name; /*store base address of string*/
while(*ptr!='\0')
{
printf("%c",*ptr);
ptr++;
}
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 123/143
123
getch();
}
******************************************************
A large set of useful string handling library functions are provided to every C compiler. From this, the most
commonly used string functions are strlen(), strcpy(), strcat() and strcmp().
1) Strlen():
This function counts the number of characters present in a string. It is used to find length of string i.e. it returns number of character.
***************************************************
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char arr[]="Nagpur";
int len1,len2;
clrscr();
len1=strlen(arr);
len2=strlen("Humpty Dumpty"); printf("\nString=%s length=%d",arr,len1);
printf("\nString=%s length=%d","Humpty Dumpty",len2);
getch();
}
/****************************OUTPUT************************************
String=Nagpur length=6
String=Humpty Dumpty length=13
***********************************************************************/
Using function xstrlen() i.e. by removing the standard library function strlen(), the same program
can be written as:
******************************************************
#include<stdio.h>
#include<conio.h>#include<string.h>
void main()
{
char arr[]="Nagpur";
int len1,len2;
clrscr();
len1=xstrlen(arr);
len2=xstrlen("Humpty Dumpty");
printf("\nString=%s length=%d",arr,len1);
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 124/143
124
printf("\nString=%s length=%d","Humpty Dumpty",len2);
getch();
}
xstrlen(char *s)
{
int length=0;
while(*s!='\0')
{
length++;
s++;
}
return(length);
}
/*******************************OUTPUT*******************************
String=Nagpur length=6
String=Humpty Dumpty length=13
*********************************************************************/
Here, the function xstrlen keep counting characters till the pointer S doesn’t point to ‘ \ 0’.
2) Strcpy(): This function copies the contents of one string into another. The base addresses of
the source & target strings should be supplied to this function. If the target string has value then it
will be overwritten.
*****************************************************
#include<stdio.h>
#include<conio.h>#include<string.h>
void main()
{
char source[]="Nagpur";
char target[20];
clrscr();
strcpy(target,source);
printf("\nSource String=%s",source);
printf("\nTarget String=%s",target);
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 125/143
125
getch();
}
/***************************OUTPUT************************************
Source String=Nagpur
Target String=Nagpur
**********************************************************************/
******************************************************
//Program using function xstrcpy().
#include<stdio.h>
#include<conio.h>
void main()
{
char source[]="Nagpur";
char target[20];
clrscr();
xstrcpy(target,source);
printf("\nSource String=%s",source);
printf("\nTarget String=%s",target);
getch();
}xstrcpy(char *t,char *s)
{
while(*s!='\0')
{
*t=*s;
s++;
t++;
}
*t='\0';
}
/*******************************OUTPUT*********************************Source String=Nagpur
Target String=Nagpur
***********************************************************************/
3) Strcat(): This function concatenates the source string at the end of the target string.
******************************************************
#include<stdio.h>
#include<conio.h>#include<string.h>
void main()
{
char source[]="Bombay";
char target[30]="Nagpur";
clrscr();
strcat(target,source);
printf("\nSource String=%s",source);
printf("\nTarget String=%s",target);
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 126/143
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 127/143
127
/******************************OUTPUT*********************************
Enter first string:Kanchan
String in uppercase:KANCHAN
String in lowercase:kanchan
***********************************************************************
//Program to enter a string and count no.of times 'a' occurs in a string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int n,i,count=0;
char a[20];
clrscr();
printf("\nEnter a string:");
gets(a);
n=strlen(a);
for(i=0;i<n;i++)if(a[i]=='a')
count++;
printf("\nNo. of times 'a' occurs=%d",count);
getch();
}
/**************************OUTPUT*******************************
Enter a string:Kanchan
No. of times 'a' occurs=2
***********************************************************************
/*Enter the string in uppercase and convert it into lowercase without
using any string function.*/
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50];
int i;
clrscr();
printf("\nEnter a string in uppercase:");
gets(a);
while(a[i]!='\0')
{
if(a[i]>='A' && a[i]<='Z')
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 128/143
128
{ a[i]+=32;
i++; }
}
printf("\nString in lowercase is \n%s",a);
getch();
}
Two Dimensional Array of Characters
#include<stdio.h>
#include<conio.h>
#define FOUND 1
#define NOTFOUND 0
void main()
{
char masterlist[6][10]={
"reena",
"akshay",
"girish",
"mandeep",
"srinivas","shikha"
};
int i,flag,a;
char yourname[10];
clrscr();
printf("\nEnter your name:");
scanf("%s",&yourname);
flag=NOTFOUND;
for(i=0;i<=5;i++)
{
a=strcmp(&masterlist[i][0],yourname);
if(a==0){
printf("Welcome you can enter the palace");
flag=FOUND;
break;
}
}
if(flag==NOTFOUND)
printf("Sorry, you are a trespasser");
getch();
}
/*****************************OUTPUT*******************************
Enter your name:dinesh
Sorry, you are a trespasser
Enter your name:mandeep
Welcome you can enter the palace
*******************************************************************/
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 129/143
129
1001
1011
1021
1031
1041
1051
1060(last location)
Here, 1001, 1011, 1021 etc are the base addresses of successive names, some of the names do not
occupy all the bytes reserved for them. For E.g., even though 10 bytes are reserved for storing the
name “reena”, it occupies only 6 bytes. Thus, 4 bytes go waste. Similarly, for each na me there is
some amount of wastage. In fact, more the number of names, more would be the wastage. This is
avoided by “array pointers”.
Array of Pointers to Strings
Array of pointers is to make a more efficient use of available memory, to obtain greater ease in
manipulation of the strings.
******************************************************
#include<stdio.h>
#include<conio.h>
void main()
{char names[][10]={
"reena",
"akshay",
"girish",
"mandeep",
"srinivas",
"shikha"
};
int i;
r e e n a \0
a k s h a y \0
g i r i s h \0
m a n d e e p \0
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 130/143
130
char t;
clrscr();
printf("\nOriginal:%s %s",&names[2][0],&names[3][0]);
for(i=0;i<=9;i++)
{
t=names[2][i];
names[2][i]=names[3][i];
names[3][i]=t;
}
printf("\nNew:%s %s",&names[2][0],&names[3][0]);
getch();
}
/*****************************OUTPUT*************************************
Original:girish mandeep
New:mandeep girish
*************************************************************************/
In the above program, 10 exchanges are needed to interchange two names as exchange is
corresponding characters of the two names. This can be reduced by using an array of pointers tostrings.
******************************************************
#include<stdio.h>
#include<conio.h>
void main()
{
char *names[]={
"reena",
"akshay",
"girish",
"mandeep",
"srinivas",
"shikha"
};
char *temp;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 131/143
131
clrscr();
printf("\nOriginal:%s %s",names[2],names[3]);
temp=names[2];
names[2]=names[3];
names[3]=temp;
printf("\nNew:%s %s",names[2],names[3]);
getch();
}
/**************************OUTPUT*****************************
Original:girish mandeep
New:mandeep girish
**************************************************************/
Here, exchange of addresses (of the names) stored in the
array of pointers takes place instead of names themselves.
Structures
Structure can be defined as a data structure whose individual elements differ in types. Thus, a single
structure might contain integer elements, floating points & characters, pointer, array and other
structure can be included as elements within a structure. In other words, a structure is a collection
of one or more variables, possibly of different data types grouped together under a single name for
convenient handling.
Syntax: struct name
{
member 1
member 2
};
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 132/143
132
e.g. struct student
{
char name[20];
int rollno;
float marks;
}student1, student2;
If data about 3 books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices & still another for
storing number of pages. Use a structure variable.
A structure contains a number of data types grouped together. These data types may or may not be of the
same type.
Declaration of the structure type and the structure variables.
E.g.
struct book
{char name;
float price;
int pages;
};
struct book b1,b2,b3;
is same as
struct book
{
char name;
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 133/143
133
float price;
int pages;
}b1,b2,b3;
OR
struct
{
char name;
float price;
int pages;}b1,b2,b3;
Like primary variables and arrays, structure variables can also be initialized where they are declared.
struct book
{
char name[10];
float price;
int pages;
};
struct book b1={“Basic”,130.00,550};
struct book b2={“Physics”,150.80,800};
Structure Elements are stored as below:
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b1={'B',130.00,550};
clrscr();
printf("\nAddress of name=%u",&b1.name);
printf("\nAddress of price=%u",&b1.price);
printf("\nAddress of pages=%u",&b1.pages);
printf("\nName=%c Price=%f Pages=%d",b1.name,b1.price,b1.pages);
getch();
}
***********************************************************************
Structure elements are stored in memory as:
b1.name b1.price b1.pages
Array of Structures
Like an ordinary integer variable, float variable we can have array of structure
#include<stdio.h>
‘B’ 130.00 550
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 134/143
134
#include<conio.h>
#include<string.h>
void main()
{
struct employee
{
char name[10];
int age;
float salary;
};
struct employee e[3];
int i
clrscr();
printf(“\nenter name\tage and salary of employee”);
for(i=0;i<3;i++)
scanf(“%s %d %f”,&e[i].name,&e[i].age,&e[i].salary);
printf(“\nthe details of employee are”);
for(i=0;i<3;i++)
{
printf(“\nname=%s age=%d”,e[i].nam e,e[i].age);
printf(“\nsalary=%f”,e[i].salary);}
getch();
}
/****************************OUTPUT***********************************
Enter name age and salary of employee
Sanjay 30 12000.26
Nikhil 31 13000.55
Nitesh 28 14000.22
the details of employee are
Name=Sanjay age =30 salary =12000.259999
Name=Nikhil age =31 salary =13000.549999 Name=Nitesh age =28 salary =14000.219999
**********************************************************************/
Additional features of Structures
a) The values of a structure variable can be assigned to another structure variable of the same type
using the assignment operator.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
struct employee
{
char name[10];
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 135/143
135
int age;
float salary;
};
struct employee e1={"Sanjay",30,20000.50};
struct employee e2,e3;
clrscr();
strcpy(e2.name,e1.name);
e2.age=e1.age;
e2.salary=e1.salary;
e3=e2;
printf("\n%s %d %f",e1.name,e1.age,e1.salary);
printf("\n%s %d %f",e2.name,e2.age,e2.salary);
printf("\n%s %d %f",e3.name,e3.age,e3.salary);
getch();
}
/****************************OUTPUT***********************************
Sanjay 30 20000.500000
Sanjay 30 20000.500000
Sanjay 30 20000.500000
**********************************************************************/
b) One structure can be nested within another structure. Using this, complex data types can be created.
#include<stdio.h>
#include<conio.h>
void main()
{
struct address
{
char phone[15];
char city[25];int pin;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e={"Akshay","531046","Nagpur",10};
clrscr();
printf("\nName=%s Phone=%s",e.name,e.a.phone);
printf("\nCity=%s Pin=%d",e.a.city,e.a.pin);
getch();
}
/****************************OUTPUT*******************************
Name=Akshay Phone=531046
City=Nagpur Pin=10
******************************************************************/
c) A structure variable can also be passed to a function like an ordinary variable.
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 136/143
136
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[25];
char author[25];
int callno;
};
struct book b1={"Let Us C","YPK",101};
clrscr();
display(b1.name,b1.author,b1.callno);
getch();
}
display(char *s,char *t,int n)
{
printf("\n%s\t%s\t%d",s,t,n);
}
/*****************************OUTPUT******************************
Let Us C YPK 101
******************************************************************/
Here, instead of passing individual elements entire structure can be passed at a time.
#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];int callno;
};
void main()
{
struct book b1={"Let Us C","YPK",101};
clrscr();
display(b1);
getch();
}
display(struct book b)
{
printf("\n%s\t%s\t%d",b.name,b.author,b.callno);
}
/************************OUTPUT*********************************
Let Us C YPK 101
****************************************************************/
Pointers pointing to struct are called as “Structure pointers”.
#include<stdio.h>
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 137/143
137
#include<conio.h>
void main()
{
struct book
{
char name[25];
char author[25];
int callno;
};
struct book b1={"Let Us C","YPK",101};
struct book *ptr;
clrscr();
ptr=&b1;
printf("\n%s %s %d",b1.name,b1.author,b1.callno);
printf("\n%s %s %d",ptr->name,ptr->author,ptr->callno);
getch();
}
/**************************OUTPUT******************************
Let Us C YPK 101
Let Us C YPK 101
***************************************************************/
b1.name b1.author b1.callno
Let Us C YPK 101
4001 4026 4051
ptr
4001
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 138/143
138
/*Passing address of a structure variable*/
#include<stdio.h>
#include<conio.h>
struct book
{
char name[25];
char author[25];
int callno;
};
void main()
{
struct book b1={"Let Us C","YPK",101};
clrscr();
display(&b1);getch();
}
display(struct book *b)
{
printf("\n%s %s %d",b->name,b->author,b->callno);
}
/*************************OUTPUT*******************************
Let Us C YPK 101
***************************************************************/
Unions
Both structures and unions are used to group a number of different variables together, But while a structure
allows to treat a number of different variables stored at different places in memory, a union allows to treat
the same space in memory as a number of different variables.
#include<stdio.h>
#include<conio.h>
void main()
{
union a
{
int i;
char ch[2];
};
union a key;
clrscr();
key.i=512;
printf("\nkey.i=%d",key.i);
printf("\nkey.ch[0]=%d",key.ch[0]);
printf("\nkey.ch[1]=%d",key.ch[1]);
getch();
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 139/143
139
}
/**************************OUTPUT*******************************
key.i=512
key.ch[0]=0
key.ch[1]=2
****************************************************************/
Consider
struct a
{
int i;
char ch[2];
};
struct a key;
The data type would occupy 4 bytes in memory, 2 for key.i and 1 each for key.ch[0] and key.ch[1] as shown:
key.i key.ch[0] key.ch[1]
1002 1003 1004 1005
Consider
union a
{
int i;
char ch[2];
};
union a key;
This data type in memory is represented as shown:
Key.i
key.ch[0] key.ch[1]
The union occupies only 2 bytes in memory.
o/p
key.i=512
key.ch[0]=0
key.ch[1]=2512 is an integer, a 2 byte number. It’s binary equivalent will be 0000 0010 0000 0000.
When stored in memory.
key.i
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
high byte low byte
key.ch[0] key.ch[1]
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 140/143
140
When a two byte number is stored in memory, the low byte is stored before the high byte. It means 512 would
be stored in memory as:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
Therefore, the value of key.ch[0] is printed as 0 and value of key.ch[1] is printed as 2. We can’t assign
different values to the different union elements at the same time.
#include<stdio.h>
#include<conio.h>
void main()
{
union a
{
int i;
char ch[2];
};
union a key;
clrscr();key.i=512;
printf("\nkey.i=%d",key.i);
printf("\nkey.ch[0]=%d",key.ch[0]);
printf("\nkey.ch[1]=%d",key.ch[1]);
key.ch[0]=50;
printf("\nkey.i=%d",key.i);
printf("\nkey.ch[0]=%d",key.ch[0]);
printf("\nkey.ch[1]=%d",key.ch[1]);
getch();
}
/*****************************OUTPUT************************************
key.i=512
key.ch[0]=0
key.ch[1]=2
key.i=562
key.ch[0]=50
key.ch[1]=2
*************************************************************************/
Union of StructuresUnion can be nested in another union or a structure in a union.
#include<stdio.h>
#include<conio.h>
void main()
{
struct a
{
int i;
char c[2];
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 141/143
141
};
struct b
{
int j;
char d[2];
};
union z
{
struct a key;
struct b data;
};
union z strange;
strange.key.i=512;
strange.data.d[0]=0;
strange.data.d[1]=32;
clrscr();
printf("\n%d",strange.key.i);
printf("\n%d",strange.data.j);
printf("\n%d",strange.key.c[0]);
printf("\n%d",strange.data.d[0]);
printf("\n%d",strange.key.c[1]); printf("\n%d",strange.data.d[1]);
getch();
}
/****************************OUTPUT*********************************
512
512
0
0
32
32
********************************************************************/
File Handling
File handling is about How new lines (\n) are stored.
How end of file is indicated.
How numbers are stored in the file.
Mode in which a file should be opened for input is determined by the above characteristics of a file.
File I/O in high level, unformatted, text mode is as follows:
Given program reads a file and count, how many characters, spaces, tabs and new lines are present in the
file.
/*Count characters, spaces, tabs and newlines in a file*/
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 142/143
142
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int nol=0, not=0, nob=0, noc=0;
fp=fopen("struct7.c","r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==' ')
nob++;
if(ch=='\n')
nol++;
if(ch=='\t')
not++;}
fclose(fp);
printf("\nNumber of characters=%d",noc);
printf("\nNumber of blanks=%d",nob);
printf("\nNumber of tabs=%d",not);
printf("\nNumber of lines=%d",nol);
getch();
}
/*****************************OUTPUT**********************************
Number of characters=4313
Number of blanks=3840 Number of tabs=14
Number of lines=71
**********************************************************************/
Before we can write information to a file on a disk or read it, we must open the file. The link between the
program and the operating system is a structure called FILE which has been defined in the header file
“stdio.h” declaration before opening the file is FILE *fp;
fopen() will open a file “struct7.c” in “read” mode.
Reading from a file.
ch=fgetc(fp);
Trouble in Opening a file
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“PR1.c”,”r”);
if(fp==NULL)
{
puts(“Cannot open file”);
7/29/2019 C Language Super Notes 2
http://slidepdf.com/reader/full/c-language-super-notes-2 143/143
exit();
}
}
Closing the file
fclose(fp);
A File-Copy Program
Function fgetc() reads the characters from a file, fputc() writes the characters to a file. Given program takes
the contents of a text file and copy them into another text file, character by character.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs,*ft;
char ch;
clrscr();
fs=fopen("struct7.c","r");
if(fs==NULL)
{
puts("Cannot open source file");exit();
}
ft=fopen("nagpur.c","w");
if(ft==NULL)
{
puts("Cannot open target file");
fclose(fs);
exit();
}
while(1)