C+lecture+notes+full 1+
C+lecture+notes+full 1+
UNIT-I
INTRODUCTION TO COMPUTERS
COMPUTER SYSTEMS
+,-,*,/ (Arithmetic
Operators) &&, || ( Logical
Operators)
CU: Every Operation such as storing , computing and retrieving the data should be
governed by the control unit.
MU: The Memory unit is used for storing the
data. The Memory unit is classified into two
types.
They are 1) Primary Memory
2) Secondary Memory
Primary memory: The following are the types of memoruies which are treated as
primary ROM: It represents Read Only Memory that stores data and instructions even
when the computer is turned off. The Contents in the ROM can‘t be modified once if
they are written . It is used to store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions when the
computer is turned on. The contents in the RAM can be modified any no. of times by
instructions. It is used to store the programs under execution.
Cache memory: It is used to store the data and instructions referred by processor.
Secondary Memory: The following are the different kinds of memories
Magnetic Storage: The Magnetic Storage devices store information that can be read,
erased and rewritten a number of times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes
Optical Storage: The optical storage devices that use laser beams to read and write
stored data. Example:CD(Compact Disk),DVD(Digital Versatile Disk)
COMPUTER SOFTWARE
System Software
Application software
In 1971, Marcian E. Hoff, working for INTEL combined the basic elements of the
central processing unit into the microprocessor. If we are using a personal computer
then all the computer hardware components are tied together. This kind of computing is
used to satisfy the needs of a single user, who uses the computer for the personal
tasks.
Ex: Personal Computer
Time-Sharing Environment
Client/Server Environment
COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must use a computer
language. Over the years computer languages have evolved from machine languages
to natural languages. The following is the summary of computer languages
1940‘s -- Machine Languages
1950‘s -- Symbolic Languages
1960‘s -- High Level
Languages
Machine Language
3) No translation is needed.
Disadvantages:
1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error
Example Additon of two numbers
2 0010
+ 3 0011
5 0101
In the early 1950‘s Admiral Grace Hopper, a mathematician and naval officer,
developed the concept of a special computer program that would convert programs into
machine language. These early programming languages simply mirrored the machine
languages using symbols or mnemonics to represent the various language instructions.
These languages were known as symbolic languages. Because a computer does not
understand symbolic language it must be translated into the machine language. A
special program called an Assembler translates symbolic code into the machine
language. Hence they are called as Assembly language.
Advantages:
1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
5) Less efficient
Example:
2 PUSH 2,A
3 PUSH 3,B
+ ADD A,B
5 PRINT C
High-Level Languages
Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
Language Translators
These are the programs which are used for converting the programs in one
language into machine language instructions, so that they can be excuted by the
computer.
1)Compiler:
It is a program which is used to convert the high level language
programs into machine language
2) Assembler:
It is a program which is used to convert the assembly level
language programs into machine language
3) Interpreter: It is a program, it takes one statement of a high level language
program, translates it into machine language instruction and then
immediately executes the resulting machine language instruction and
so on.
Comparison between a Compiler and Interpreter
COMPILER INTERPRETER
A Compiler is used to compile an An interpreter is used to translate each
entire program and an executable line of the program code immediately as
program is it is entered
generated through the object program
The executable program is stored in a The executable program is generated in
RAM
disk for future use or to run it in another
and the interpreter is required for each
computer
run of the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.
The procedure for turning a program written in C into machine Language. The process
is presented in a straightforward, linear fashion but you shuld recognize that these steps
are repeated many times during development to correct errors and make improvements
to the code.
The following are the four steps in this process
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules
4) Executing the program
Sl. No. Phase Name of Code Tools File Extension
1 TextEditor Source Code C .C
Compilers
Edit,
Notepad Etc..,
2 Compiler Object Code C Compiler .OBJ
3 Linker Executable C Compiler .EXE
Code
4 Runner Executable C Compiler .EXE
Code
The code in a source file stored on the disk must be translated into machine
language. This is the job of the compiler. The Compiler is a computer program that
translates the source code written in a high-level language into the corresponding object
code of the low-level language. This translation process is called compilation. The entire
high level program is converted into the executable machine code file. The Compiler
which executes C programs is called as C Compiler. Example Turbo C, Borland C, GC
etc.,
The C Compiler is actually two separate programs:
T h e
Preprocessor
The Translator
The Preprocessor reads the source code and prepares it for the translator. While
preparing the code, it scans for special instructions known as preprocessor commands.
These commands tell the preprocessor to look for special code libraries. The result of
preprocessing is called the translation unit.
After the preprocessor has prepared the code for compilation, the translator does
the actual work of converting the program into machine language. The translator reads
the translation unit and writes the resulting object module to a file that can then be
combined with other precompiled units to form the final program. An object module is
the code in the machine language.
Linking Programs
The Linker assembles all functions, the program‘s functions and system‘s
functions into one executable program.
Executing Programs
ALGORITHM
Algorithm is a finite sequence of instructions, each of which has a clear meaning and
can be performed with a finite amount of effort in a finite length of time. No matter what
the input values may be, an algorithm terminates after executing a finite number of
instructions.
We represent an algorithm using a pseudo language that is a combination of the
constructs of a programming language together with informal English statements.
The ordered set of instructions required to solve a problem is known as an
algorithm. The characteristics of a good algorithm are:
Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend
on the input and the result of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.
Example
FLOWCHART
Different symbols are used for different states in flowchart, For example: Input/Output
and decision making has different symbols. The table below describes all the symbols
that are used in making flowchart
INTRODUCTION TO C LANGUAGE
The language was formalized in 1988 by the American National Standard Institue
(ANSI).
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software have been implemented using C
Why to use C?
C was initially used for system development work, in particular the programs that make-
up the operating system. C was adoped as a system development language because it
produces code that runs nearly as fast as code written in assembly language. Some
examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Data Bases
Language Interpreters
Utilities C
Program File
All the C programs are writen into text files with extension ".c" for example hello.c. You
can use "vi" editor to write your C program into a file.
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX
operating system for which it was developed - since the system and most of the
programs that run it are written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin
Richards. The influence of BCPL on C proceeded indirectly through the language B,
which was written by Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a
DEC PDP-
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C
Programming Language by Kernighan & Ritchie caused a revolution in the computing
world.
In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or "ANSI C", was completed late 1988.
The assembler creates object code. On a UNIX system you may see files with a
.o suffix (.OBJ on MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files
the link editor combines these functions (with main()) to create an executable file.
C TOKENS
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The
keywords cannot be used as variable names.
The list of C keywords is given below:
volatile while
C IDENTIFIERS
Identifiers are used as the general terminology for the names of variables, functions
and arrays. These are user defined names consisting of arbitrarily long sequence of
letters and digits with either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c
identifiers: They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is
allowed. It should not be a keyword.
It must not contain white space.
C CONSTANTS
A C constant refers to the data items that do not change their value during the
program execution. Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least
one digit and may contain either + or – sign. A number with no sign is assumed to be
positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with
0 is said to be octal integer constants.
Example of valid octal integer
constants 010, 0424, 0, 0540
Hexadecimal Integer Constants
The numbers having fractional parts are called real or floating point constants.
These may be represented in one of the two forms called fractional form or the
exponent form and may also have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal
notation 0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The letter e separating the mantissa and the exponent can also be written in
uppercase i.e. E And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
Character Constants
It should be noted that character constants have numerical values known as ASCII
values, for example, the value of A‘ is 65 which is its ASCII value.
Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character constants. Non graphic
characters are those characters that cannot be typed directly from keyboard, for
example, tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single
character.
STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
hello
abc
hello911
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls
and function parameters.
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
VARIABLES
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on the basic types explained in
the previous chapter, there will be the following basic variable types
Type Description
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows
Here, type must be a valid C data type including char, w_char, int, float, double, bool,
or any user-defined object; and variable_list may consist of one or more identifier
names separated by commas. Some valid declarations are shown here
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
ARITHMETIC OPERATORS IN C
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs.
Arithmeti
S.no c Operation Example
Operator
s
+ Addition A+B 2 –
4 / Division A/B 5
int a=40,b=20,
add,sub,mul,div,mod; add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod =
a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n",
mul); printf("Division of a, b is : %d\n",
div); printf("Modulus of a, b is : %d\n",
mod);
}
Operators Example Explanation
Simple
assignme 10 is
nt assigned to
operator = sum = 10
variable sum
This is same
-= sum -= as sum = sum
10 – 10
This is same
/+ sum /= as sum =
10 sum / 10
This is same
sum as sum =
%= 10 sum % 10
%=
This is same
as sum =
sum & 10
&= sum&=10
int Total=0,i;
for(i=0;i<10;i++
)
{
x is greater
1 > x>y than y
x is greater
3 >= x >= y than or equal
to y
x is less than
4 <= x <= y or equal to y
5 == x == y x is equal to y
x is not equal
6 != x != y to y
int main()
int
m=40,n=20; if
(m == n)
{
else
}
S.no Operators Name Example Description
It returns
true when
logica both
l AND conditions
1 && (x>5)&&(y<5) are true
It returns
true when
at-least one
of the
logica condition is
2 || l OR (x>=10)||(y>=10) true
It reverses
the state of
the operand
((x>5) &&
(y<5))
If ((x>5)
&& (y<5)) is
true, logical
NOT
operator
logica makes it
3 ! l NOT !((x>5)&&(y<5)) false
#include
<stdio.h> int
main()
{
int
m=40,n=20;
int
o=20,p=30;
if (m>n && m !=0)
if (o>p || p!=20)
else
}
&& operator – if clause becomes true only when both conditions (m>n and m! =0) is
true. Else, it becomes false.
|| Operator – if clause becomes true when any one of the condition (o>p || p!=20) is
true. It becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is
inverted by ! operator.
So, ! (m>n and m! =0) returns false (0).
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Right Shift
All bit wise operations for x and y are given
below. x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120
(decimal) x << 1 = 01010000 (binary) =
80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So,
all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift : In left shift operation x << 1 , 1 means that the bits
will be left shifted by one place. If we use it as x << 2 , then, it means that the bits will
be left shifted by 2 places.
int main()
int m = 40,n =
80,AND_opr,OR_opr,XOR_opr,NOT_opr ; AND_opr
= (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr =
(m^n);
printf("AND_opr value = %d\n",AND_opr
); printf("OR_opr value = %d\n",OR_opr
); printf("NOT_opr value =
%d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr
); printf("left_shift value = %d\n", m <<
1); printf("right_shift value = %d\n", m >>
1);
}
#include
<stdio.h> int
main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
C – Increment/decrement
Operators PREVNEXT
Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
Syntax:
Increment operator: ++var_name ;( or)
var_name++; Decrement operator: – -
var_name; (or) var_name – -;
Example:
Increment operator : ++ i ;i
++ ; Decrement operator : – – i ;
i––;
EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C
In this program, value of i is incremented one by one from 1 up to 9 using i++ operator
and output is displayed as 1 2 3 4 5 6 7 8 9.
//Example for increment operators
#include
<stdio.h> int
main()
{
int i=1;
while(i<10
)
{
printf("%d ",i);
i++;
}
}
OUTPUT:
int i=20;
while(i>10
)
{
printf("%d
",i); i--;
}
20 19 18 17 16 15 14 13 12 11
Value of i is
incremented after
i++ assigning it to variable
2 Post–incremen i.
t
Value of i is
decremented before
— –i assigning it to variable
3 Pre decrement i.
Value of i is
decremented after
i– — assigning it to variable
4 Post_decreme i.
nt
int i=0;
while(++i < 5
)
{
printf("%d ",i);
}
return 0;
}
#include
<stdio.h> int
main()
{
int i=0;
while(i++ < 5
)
{
printf("%d ",i);
return 0;
}
#include
<stdio.h> int
main()
{
int i=10;
while(--i > 5
)
{
printf("%d ",i);
return 0;
OUTPUT:
9876
#include
<stdio.h> int
main()
{
int i=10;
while(i-- > 5
)
{
printf("%d ",i);
return 0;
Example : * a where, *
is pointer to the variable a.
2 *
int *ptr,
q; q = 50;
/* address of q is assigned to
ptr */ ptr = &q;
/* display q's value using ptr
variable */ printf("%d", *ptr);
return 0;
OUTPUT:
50
#include
<stdio.h>
#include
<limits.h> int
main()
{
int a;
char
b;
float c;
double d;
printf("Storage size for int data type:%d
\n",sizeof(a)); printf("Storage size for char data
type:%d \n",sizeof(b)); printf("Storage size for float
data type:%d \n",sizeof(c)); printf("Storage size for
double data type:%d\n",sizeof(d)); return 0;
}
EXPRESSIONS
The evaluation procedure of an arithmetic expression includes two left to right passes
through the entire expression. In the first pass, the high priority operators are applied
as they are encountered and in the second pass, low priority operations are applied as
they are encountered. Suppose, we have an arithmetic expression as:
x = 9 – 12 / 3 + 3 *2 - 1
This expression is evaluated in two left to right passes as:
First Pass
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are
evaluated first from left to right. The expression is now evaluated in three passes as:
First Pass
Second Pass
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis
inside parenthesis). In such case, the expression inside the innermost set of
parentheses is evaluated
first and then the outer parentheses are
evaluated. For example, we have an
expression as:
x = 9 – ((12 / 3) + 3 * 2) – 1
The expression is now evaluated as:
First Pass:
Second Pass
Note: The number of evaluation steps is equal to the number of operators in the arithmetic
expression.
When variables and constants of different types are combined in an expression then
they are converted to same data type. The process of converting one predefined type
into another is called type conversion.
Type conversion in c can be classified into the following two types:
Implicit Type Conversion
Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.
Else, if one of the operand is long int, and the other is unsigned int, then
if a long int can represent all values of an unsigned int, the unsigned int is converted to
long int. otherwise, both operands are converted to unsigned long int.
Else, if either operand is long int then other will be converted to long int.
Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on
left side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double
to float causes rounding of digits and the conversion of long int to int causes dropping
of excess higher order bits.
The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion.
The explicit type conversion is also known as type
casting. Type casting in c is done in the following
form: (data_type)expression;
where, data_type is any valid c data type, and expression may be constant,
variable or expression.
For example, x=(int)a+b*d;
The following rules have to be followed while converting the expression from one
type to another to avoid the loss of information:
All integer types to be converted to
float. All float types to be converted
to double.
All character types to be converted to integer.
FORMATTED INPUT AND OUTPUT
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.
Syntax:
printf (format, data1, data2,… );
In this syntax format is the format specification string. This string contains, for each
variable to be output, a specification beginning with the symbol % followed by a
character called the conversion character.
Example:
printf (%c, data1);
The character specified after % is called a conversion character because it allows one
data type to be converted to another type and printed.
See the following table conversion character and their meanings.
Conversio Meaning
n
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL,
character is reached.
f The data is output as float or double with a default Precision 6.
Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example
printf (%c\n,data1);
The format specification string may also have text.
Example
printf (Character is:%c\n, data1);
The text "Character is:" is printed out along with the value of data1.
Example with
program
#include<stdio.h>
#include<conio.h>
Main()
{
Char alphabh="A";
int number1= 55;
float
number2=22.34;
printf(char= %c\n,alphabh);
printf(int= %d\n,number1);
printf(float= %f\n,number2);
getch();
clrscr();
retrun
0;
}
Output Here…
char =A
int= 55
flaot=22.34000
0
What is the output of the statement?
A digit: Specifying the minimum width in which the data is to be output, if the data
has a larger number of characters then the specified width occupied by the
output is larger. If the data consists of fewer characters then the specified width,
it is padded to the right or to the left (if minus sign is not specified) with blanks. If
the digit is prefixed with a zero, the padding is done with zeros instead of blanks.
A period: Separating the width from the next digit.
#include<stdio.h
>
#include<conio.h
> main()
{
Int num=65;
printf(Value of num is : %d\n:, num);
Output
Here… char
=A
int= 55
flaot=22.340000
Formatted
Input
The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
Syntax
scanf (format, num1, num2,……);
The function scnaf() reads and converts characters from the standards input
depending on the format specification string and stores the input in memory
locations represented by the other arguments (num1, num2,….).
For Example:
scanf( %c %d,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No
respectively. This is how data names are specified in a scnaf() function. In case of
string type data names, the data name is not preceded by the character &.
Example with program
Write a function to accept and display the element number and the weight of a
proton. The element number is an integer and weight is fractional.
Solve here:
#include<stdio.h
>
#include<conio.h
> main()
{
Int
e_num;
Float
e_wt;
DECISION STATEMENTS
If statement:
Syntax :
if(expression
)
statement1;
Explanation
:
Expression is Boolean Expression
It may have true or false value
Meaning of If Statement :
It Checks whether the given Expression is Boolean or not !!
If Expression is True Then it executes the statement otherwise jumps to
next_instruction
Sample Program
Code : void main()
{
int
a=5,b=6,c;
c=a+b;
if (c==11)
printf("Execute me 1");
printf("Execute me 2");
}
Output :
Execute me 1
If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}
Note :
More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when Code after if
statement occupies multiple lines.
if(conditional)
Statement No
1
Statement No 2
Statement No 3
In the above example only Statement 1 is a part of if Statement.
1. Code will be executed if condition statement is True.
2. Non-Zero Number Inside if means “TRUE Condition”
if(100)
printf("True Condition");
if-else Statement :
We can use if-else statement in c programming so that we can check any condition and
depending on the outcome of the condition we can follow appropriate path. We have
true path as well as false path.
Syntax :
if(expression)
{
statement
1;
statement
2;
}
else
{
statement
1;
statement
2;
}
next_stateme
nt;
Explanation :
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is
True. if(num == 20)
{
printf("True Block");
}
Consider Following
Example – int num = 20;
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is
True. if(num == 20)
{
printf("True Block");
}
Switch statement
Why we should use Switch Case?
case
value2 :
body2
break;
case
value3 :
body3
break;
default :
default-
body
break;
}
next-
statement;
Flow Diagram
:
*Steps are Shown in Circles.
How it works?
Switch case checks the value of expression/variable against the list of case
values and when the match is found , the block of statement associated with
that case is executed
Expression should be Integer Expression / Character
Break statement takes control out of the case.
Break Statement is Optional.
#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll
)
{
case 1:
printf ( " I am Pankaj ");
break;
case 2:
printf ( " I am Nikhil
"); break;
case 3:
printf ( " I am John
"); break;
default :
printf ( "No student
found"); break;
}
}
As explained earlier –
3 is assigned to integer variable roll
incrementation;
}
Note :
For Single Line of Code – Opening and Closing braces are not
needed. while(1) is used for Infinite Loop
Initialization , Incrementation and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then
and then only code is executed ]
Do while:
Do-While Loop Syntax
: initialization;
do
{
incrementation;
}while(condition);
Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to
execute at least once ]
For statement:
if(condition)
{
}
}
If we have block of code that is to be executed multiple times then we can use curly
braces to wrap multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{
}
this is bodyless for loop. It is used to increment value of i.This verity of for loop is not
used generally.
At the end of above for loop value of i will be 5.
if(breaking
condition) break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it will
cause overflow of stack.
Form Comment
JUMP STATEMENTS:
Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.
Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes
execution to jump to the top of the loop block
do-while
Goto statement:
goto label;
label :
Whenever goto keyword encountered then it causes the program to continue on the
line , so long as it is in the scope .
Types of Goto
Forward
Backward
ARRAYS:
What is an array?
Types of Array
1. Static Array
2. Dynamic Array.
Static Array
This above array is called two dimensional array because it will store all the elements
in column and in row form
NOTE: In above example of two dimensional array, we have 4 rows and 5
columns. NOTE: In above example of two dimensional array, we have total
of 20 elements.
3. Multi Dimensional Array.
This array does not exist in c and c++.
Dynamic Array.
int
ar[5];
int i;
for(i=0;i<5;i++)
{
}
STRINGS
What is String?
· A string is a collection of characters.
· A string is also called as an array of characters.
· A String must access by %s access specifier in c and c++.
· A string is always terminated with \0 (Null) character.
· Example of string: Gaurav
· A string always recognized in double quotes.
· A string also consider space as a character.
· Example: Gaurav Arora
· The above string contains 12 characters.
· Example: Char ar[20]
char
str1[20];
char
str2[20];
printf(Enter First Name);
scanf(%s,&str1);
printf(Enter last Name);
scanf(%s,&str2);
puts(str1);
puts(str2);
}
String Functions in C:
1. strlen().
This string function is basically used for the purpose of computing the ength of string.
2. strupr().
This string function is basically used for the purpose of converting the case
sensitiveness of the string i.e. it converts string case sensitiveness into uppercase.
3. strlwr ().
This string function is basically used for the purpose of converting the case
sensitiveness of the string i.e it converts string case sensitiveness into lowercase.
Example: char str = gaurav
strlwr(str);
printf(The Lowercase of the string is :%s ,str);
4. strcmp ().
This string function is basically used for the purpose of comparing two
string. This string function compares two strings character by
characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Case 2: if first string < than second string then, result will be
false. Case 3: if first string = = to second string then, result
will be zero.
Example:
5. strcat().
This string function is used for the purpose of concatenating two strings ie.(merging two
or more strings)
Example:
6. strcpy()
This string function is basically used for the purpose of copying one string into
another string. char str1= Gaurav;
char str2[20];
str2 =
strcpy(str2,str1);
printf(%s,str2);
6. strrev()
This string function is basically used for the purpose of reversing the
string. char str1= Gaurav;
char str2[20];
str2=
strrev(str2,str1);
printf(%s,str2);
#
include<stdio.h>
#
include<conio.h>
#include<string.h
>
void main()
{
char str[20];
char
str1[20]; int
opt,len;
printf(\n MAIN MENU);
case 2: strrev(str);
A function is itself a block of code which can solve simple or complex task/calculations.
Types of function:
1. Built in functions(Library
functions) a.) Inputting Functions.
b.) Outputting functions.
2. User defined
functions. a.) fact();
b.) sum();
Parts of a function:
1. Function declaration/Prototype/Syntax.
2. Function Calling.
3. Function Definition.
1.)Function Declaration:
Syntax: <return type > <function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.
<statement-
2>
return(<vlaue
>)
}
Example: program based upon function:
int cube(int);
printf("Enter a
no.");
scanf("%d",&n);
c=cube(n);
printf("cube of a no. is=%d",c);
}
int cube(int n)
{
c=n*n*n;
return(c)
;
}
int n,f=1;
int
fact(int)
printf("Enter a
no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int
n) int f=1;
{
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
}
Recursion
Firstly, what is nested function?
int fact(int)
printf("Enter a
no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int
n) int f=1;
{
if(n=0)
return(f)
; else
return(n*fact(n-1));
}
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.
a.) Actual
Parameters. b.)
Formal Parameters.
These are the parameters which are used in main() function for function
calling. Syntax: <variable name>=<function name><actual argument>
Example: f=fact(n);
1.) Call by
reference. 2.) Call
by value.
int
a,b;
a=10;
b=20;
void swap(int,int)
i n t
t ;
t=x;
x=y;
y=t;
}
STORAGE CLASSES
Every Variable in a program has memory associated with it.
Term Definition
Scope of Variable tells compile about the visibility of Variable in the block. Variable
may have Block Scope, Local Scope and External Scope. A scope is the context
within a computer program in which a variable name or other identifier is valid and can
be used, or within which a declaration has effect.
C. Default Initial Value of the Variable
D. Lifetime of variable
Lifetime of the = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be
destroyed only when the control comes out of the main .i.e end of the program.
Different Storage
Classes: Auto
Storage Class Static
Storage Class Extern
Storage Class
Register Storage
Class
Storage Memory
Scope Local / Block Scope
Life time Exists as long as Control remains
in the block
Default Garbage
initial Value
Example
void main()
{
auto mum = 20 ;
{
auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
Num : 60
Num : 20
Note :
Two variables are declared in different blocks , so they are treated as different
variables External ( extern ) storage class in C Programming
Global Variables are declared outside the function and are accessible to all
functions in the program
Generally , External variables are declared again in the function using
keyword extern In order to Explicit declaration of variable use extern‘ keyword
extern int num1 ; // Explicit Declaration
Features :
Storage Memory
Example
int num = 75 ;
void display();
void main()
{
extern int num ;
printf("nNum :
%d",num); display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
Output :
Num : 75
Num : 75
Note :
Declaration within the function indicates that the function uses external variable
Functions belonging to same source code , does not require declaration (no need to
write extern) If variable is defined outside the source code , then declaration using
extern keyword is required
Static Storage Class
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one
copy of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration
*/ void func(void);
variable */ main() {
while(count--)
{ func();
}
return 0;
}
/* function definition
*/ void func( void ) {
When the above code is compiled and executed, it produces the following
result i is 6 and count is 4
i is 7 and count is
3 i is 8 and count
is 2 i is 9 and
count is 1 i is 10
and count is 0
Register Storage Class
int main()
{
int num1,num2;
register int sum;
return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes –
In the above program we have declared two variables num1,num2. These two
variables are stored in RAM.
Another variable is declared which is stored in register variable.Register variables are
stored in the register of the microprocessor.Thus memory access will be faster than
other variables.
If we try to declare more register variables then it can treat variables asAuto storage
variables as memory of microprocessor is fixed and limited.
Why we need Register Variable ?
Whenever we declare any variable inside C Program then memory will be randomly
allocated at particular memory location.
We have to keep track of that memory location. We need to access value at that
memory location using ampersand operator/Address Operator i.e (&).
If we store same variable in the register memory then we can access that
memory location directly without using the Address operator.
Register variable will be accessed faster than the normal variable thus increasing the
operation and program execution. Generally we use register variable as Counter.
Note : It is not applicable for arrays, structures or pointers.
Summary of register Storage class
Keyword register
Preprocessor directives
This macro
defines constant
value and can be
1 Macro #define any of the basic
data types.
The source code
of the file
file_name is
Header #include included in the
file main program at
<file_name>
2 the specified
inclusion
place
Set of commands
are included or
excluded in source
#ifdef,
Conditiona program before
#endif, #if,
l #else, #ifndef compilation with
3 compilatio respect to the
n
condition
#undef is used to
undefine a defined
macro variable.
#Pragma is used to
call a function before
and after main
Other function in a C
4 directives #undef, #pragma program
A program in C language involves into different processes. Below diagram will help you
to understand all the processes that a C program comes across.
#include
<stdio.h>
#define height
100
#define number
3.14 #define letter
'A'
#define letter_sequence
"ABC" #define
backslash_char '\?'
void main()
{
printf("value of height : %d \n", height
); printf("value of number : %f \n",
number ); printf("value of letter : %c
\n", letter );
printf("value of letter_sequence : %s \n",
letter_sequence); printf("value of backslash_char :
%c \n", backslash_char);
}
OUTPUT
:
EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:
A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
#include
<stdio.h>
#define RAJU
100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added
in " \ "this C file\n");
#else
printf("RAJU is not
defined\n"); #endif
return 0;
}
OUTPUT:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, If
clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include
<stdio.h>
#define RAJU
100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going
to " \ "define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program);
#endif
return 0;
}
OUTPUT
:
#include
<stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since
" \ "a \= 100\n");
#else
printf("This line will be added in this C file since
" \ "a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
EXAMPLE PROGRAM FOR UNDEF IN C:
#pragma startup
function1 #pragma exit
function2
int main( )
{
printf ( "\n Now we are in main function"
) ; return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end
of " \ "main function" ) ;"
}
OUTPUT:
Let us consider it‘s Corresponding address be 65624 and the Value stored in variable
„i is 5 The address of the variable „i is stored in another integer variable whose name
is „j and which is having corresponding address 65522
thus we can say
that – j = &i;
i.e
j = Address of i
Here j is not ordinary variable , It is special variable and called pointer variable as it
stores the address of the another ordinary variable. We can summarize it like –
i 5 65524
j 65524 65522
B. C Pointer Basic
Example: #include
<stdio.h>
int main()
{
int *ptr, i;
i = 11;
return 0;
}
See Output and Download »
You will get value of i = 11 in the above program.
C. Pointer Declaration Tips :
1. Pointer is declared with preceding * :
pointer variable name and asterisk can contain whitespace because whitespace is
ignored by compiler.
int *ptr;
int *
ptr; int *ptr;
All the above syntax are legal and valid. We can insert any number of spaces or
blanks inside declaration. We can also split the declaration on multiple lines.
D. Key points for Pointer :
Unline ordinary variables pointer is special type of variable which stores the address of
ordinary variable.
Pointer can only store the whole or integer number because address of any type of
variable is considered as integer.
It is good to initialize the pointer immediately after
declaration & symbol is used to get address of variable
* symbol is used to get value from the address given by pointer.
E. Pointer Summary :
Since Pointer is also a kind of variable , thus pointer itself will be stored at different
memory location.
2 Types of Variables :
Simple Variable that stores a value such as integer,float,character
int main()
{
int a = 3;
int *ptr;
ptr = &a;
return(0);
}
Explanation of Example :
Value of n is : 10
Value of &n is :
1002
Consider the above example, where we have used to print the address of the
variable using ampersand operator.
In order to print the variable we simply use name of variable while to print the
address of the variable we use ampersand along with %u
printf("\nValue of &n is :
%u",&n); Understanding
address operator Consider the
following program –
#include<stdio.h
> int main()
{
int i =
5; int
*ptr;
ptr = &i;
printf("\nAddress of i :
%u",&i); printf("\nValue of ptr is
: %u",ptr);
return(0);
}
After declaration memory map will be like
this – int i = 5;
int *ptr;
after Assigning the address of variable to pointer , i.e after the execution of this
statement – ptr = &i;
Only variables have an address associated with them, constant entity does not
have corresponding address. Similarly we cannot use address operator over
character literal – &('a')
Character a‘ is literal, so we cannot use address
operator. Address of expressions
(a+b) will evaluate addition of values present in variables and output of (a+b)is
nothing but Literal, so we cannot use Address operator
&(a+b)
When we use variable in program then Compiler keeps some memory for that
variable depending on the data type
The address given to the variable is Unique with that variable name
Explanation :
Pointer Variable is nothing but a memory address which holds another address .
In the above program i is name given for memory location for human
understanding , but compiler is unable to recognize i . Compiler knows only
address.
In the next chapter we will be learning , Memory requirement for storing pointer variable.
int n =
20; int
*ptr;
Example of Declaring Character Pointer:
char ch =
'A'; char
*cptr;
Example of Declaring Float Pointer:
float fvar =
3.14; float *fptr;
How to Initialize Pointer in C
Programming? pointer = &variable;
Above is the syntax for initializing pointer variable in C.
Initialization of Pointer can be done using following 4
Steps : Declare a Pointer Variable and Note down the
Data Type.
Declare another Variable with Same Data Type as that of Pointer
Variable. Initialize Ordinary Variable and assign some value to it.
Now Initialize pointer by assigning the address of ordinary variable to pointer variable.
return(0);
}
Explanation of Above Program :
Pointer should not be used before initialization.
ptr = &a;
printf("\nValue of ptr : %u",ptr);
return(0);
}
Output :
Value of ptr : 4001
Pointer arithematic
Incrementing Pointer:
Address Address++
= Address
++Address = Address
Pictorial Representation :
This differs from compiler to compiler as memory required to store integer vary
compiler to compiler
[box]Note to Remember : Increment and Decrement Operations on pointer should
be used when we have Continues memory (in Array).[/box]
Live Example 1 : Increment Integer
Pointer #include<stdio.h>
int main(){
int *ptr=(int
*)1000; ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1002
double *ptr=(double
*)1000; ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1004
float
var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
Output :
Explanation:
Decrementing a pointer to an integer data will cause its value to be decremented by 2
This differs from compiler to compiler as memory required to store integer vary
compiler to compiler
Pointer Program: Difference between two integer
Pointers #include<stdio.h>
int main(){
float *ptr1=(float
*)1000; float
*ptr2=(float *)2000;
printf("\nDifference : %d",ptr2-
ptr1); return 0;
}
Output :
Difference :
250
Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float
Variable. Ptr2-Ptr1 will gives us number of floating point numbers that
can be stored. ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
= 1000 / 4
= 250
Live Example 2:
#include<stdio.h
>
struct var{
char
cvar; int
ivar;
float
fvar;
};
int main(){
printf("Difference= %d",ptr2-
ptr1); return 0;
}
Output :
Difference =
142
Explanation :
ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)
= 1000 / (1+2+4)
= 1000 / 7
= 142
Adding integer value with Pointer
return 0;
}
Output :
int main(){
int *ptr=(int
*)1000; ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
Pointer - Pointer =
Integer Pointer -
Integer = Pointer
ptr1 = &num ;
ptr2 = ptr1 + 2
;
printf("%d",ptr2 -
ptr1); return(0);
}
Output :
2
ptr1 stores the address of Variable
num Value of ptr2 is incremented by
4 bytes Differencing two Pointers
Important Observations :
Suppose the Address of Variable num = 1000.
Remember the following formula while computing the difference between two
pointers – Final Result = (ptr2 - ptr1) / Size of Data Type
Step 1 : Compute Mathematical Difference (Numerical
Difference) ptr2 - ptr1 = Value of Ptr2 - Value of Ptr1
= 1004 - 1000
=4
Suppose Both pointers of float the they will be differed numerically by 8 and
Technically by 2 objects
Consider the below statement and refer the following
table – int num = ptr2 - ptr1;
and
Float 4 1
Character 1 1
ptr1 = (int
*)1000; ptr2 =
(int *)2000;
return(0);
}
Pointer Comparison of Different Data Types :
#include<stdio.h>
int main()
{
int *ptr1;
float
*ptr2;
return(0);
}
Explanation :
Two Pointers of different data types can be compared .
Integer so we can compare address of any two pointers although they are of different
data types.[/box]
Following operations on pointers :
== Equals
!= Not Equal
ptr1 = (int
*)1000; ptr2 =
ptr1/4;
return(0);
}
Output :
Pointer to pointer
Pointer to Pointer in C Programming
Declaration : Double Pointer
int **ptr2ptr;
*ptr 45
**ptr2ptr 45
ptr &n
ptr2ptr &ptr
Notes :
int main()
{
int num = 45 , *ptr , **ptr2ptr
;
ptr
= #
ptr2ptr = &ptr;
printf("%d",**ptr2ptr);
return(0);
}
Output :
45
UNIT-IV
STRUCTURES AND
UNIONS
INTRODUCTION TO STRUCTURE
As we know that Array is collection of the elements of same type , but many time we
have to store the elements of the different data types.
Suppose Student record is to be stored, then for storing the record we have to group
together all the information such as Roll, name, Percent which may be of different
data types.
Definition of Structure in C
typedef struct {
char name[64];
char
course[128]; int
age;
int year;
} student;
int year;
are some examples of members.
Structure member may be of different data type including user defined data-type also
typedef struct {
char name[64];
char
course[128];
book b1;
int year;
} student;
In C we can group some of the user defined or primitive data types together and form
another compact way of storing complicated information is called as Structure. Let us
see how to declare structure in c programming language –
Syntax of Structure in C
Programming struct tag
{
d a t a _ t y p e 1
m e m b e r 1 ;
d a t a _ t y p e 2
m e m b e r 2 ;
d a t a _ t y p e 3
m e m b e r 3 ;
};
Structure Alternate Syntax
struct <structure_name>
structure_Element
1;
structure_Element
2;
structure_Element3;
...
...
};
Memory is created, very first time when the variable is created /Instance is
created. Different Ways of Declaring Structure Variable:
Way 1 : Immediately after Structure Template
struct date
int date;
char month[20];
int year;
}today;
int date;
char month[20];
int year;
};
struct Book
int pages;
char name[20];
int year;
}book1,book2,book3;
C Structure Initialization
Let us discuss very familiar example of structure student , we can initialize structure
variable in different ways –
struct student
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after
declaration we have initialized the structure variable.
std1 = { "Pritesh",67,78.3 }
char name[20];
int roll;
float marks;
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After
declaration of variable we have initialized two variable.
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
struct student
i n t
mark1;
i n t
mark2;
i n t
mark3;
} sub1={67};
integer 0
float 0.00
char NULL
struct student
i n t
mark1;
i n t
mark2;
i n t
mark3;
};
void main()
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won‘t be allocated for the structure. i.e only
writing below declaration statement will never allocate memory
struct student
{
i n t
mark1;
i n t
mark2;
i n t
mark3;
};
struct
int length;
char *name;
}*ptr;
++ptr->length
Expression Meaning
Array elements are accessed using the Subscript variable, Similarly Structure
members are accessed using dot [.] operator.
Live Example :
#include<stdio.h
>
struct Vehicle
int wheels;
char vname[20];
char color[10];
}v1 = {4,"Nano","Red"};
int main()
printf("Vehicle No of Wheels :
%d",v1.wheels); printf("Vehicle Name:
%s",v1.vname); printf("Vehicle
: %s",v1.color);
Color
return(0);
}
Output :
Vehicle No of Wheels :
4 Vehicle
Name
: Nano
Vehicle Color :
Red Note :
Dot operator has Highest Priority than unary, arithmetic, relational, logical Operators
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{"Let us C",700,"YPK",300.00},
};
Explanation :
{"Let us C",700,"YPK",300.00}
Above set of values are used to initialize first element of the array. Similarly –
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
};
void main()
{"Let us C",700,"YPK",300.00},
};
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{"Book1",700,"YPK"},
{"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}
};
void main()
printf("\nBook Name :
%s",b1[0].bname); printf("\nBook Pages
: %d",b1[0].pages); printf("\nBook
Author : %s",b1[0].author);
printf("\nBook Price : %f",b1[0].price);
Output :
Book Name :
Book1 Book Pages
: 700 Book Author :
YPK Book Price :
0.000000
Explanation :
In this example , While initializing first element of the array we have not specified the
price of book 1.It is not mandatory to provide initialization for all the values. Suppose
we have 5 structure elements and we provide initial values for first two element then
we cannot provide initial values to remaining elements.
{"Book1",700,,90.00}
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {
{},
{"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}
};
Output :
Book Name :
Book Pages : 0
Book Author :
Book Price : 0.000000
It is clear from above output , Default values for different data types.
Integer 0
Float 0.0000
Character Blank
struct Example
int num1;
int num2;
}s[3];
//
int i;
for(i=0;i<n;i++)
//
void print(struct Example sptr[],int n)
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
//
void main()
int i;
clrscr()
;
accept(s,3);
print(s,3);
getch();
Output :
Enter num1 :
10 Enter
num2 : 20
Enter num1 :
30 Enter
num2 : 40
Enter num1 :
50 Enter
num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
Explanation :
When reference (i.e ampersand) is not specified in main , so this passing is simple pass
by value. Elements can be accessed by using dot [.] operator
Pointer Within Structure in C Programming:
Structure may contain the Pointer variable as
member. Pointers are used to store the address of
memory location. They can be de-referenced by „*
operator.
Example :
struct
Sample
{
Here num is any variable but it‘s address is stored in the Structure member ptr
(Pointer to Integer)
Similarly Starting address of the String Pritesh is stored in structure variable name(Pointer to
Character array)
Whenever we need to print the content of variable num , we are dereferancing
the pointer variable num.
printf("Content of Num : %d
",*s1.ptr); printf("Name :
%s",s1.name);
Live Example : Pointer Within
Structure #include<stdio.h>
struct Student
}s1;
int main()
return(0);
}
Output :
We have stored the address of variable roll‘ in a pointer member of structure thus we
can access value of pointer member directly using de-reference operator.
Similarly we have stored the base address of string to pointer variable name‘. In order to
de- reference a string we never use de-reference operator.
Array of Structure :
Structure is used to store the information of One particular object but if we need to
store such 100 objects then Array of Structure is used.
Example :
struct
Bookinfo
{
char[20]
bname; int
pages;
int price;
}Book[100];
Explanation :
In case if we need to store the Information of 100 books then Array of Structure is used.
b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book
and So on We can store the information of 100 books.
struct Bookinfo
char[20] bname;
int pages;
int price;
}book[3];
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of
Book
: "); gets(book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book :
"); scanf("%f",book[i].price);
}
for(i=0;i<3;i++)
printf("\nName of Book :
%s",book[i].bname); printf("\nNumber of
Pages : %d",book[i].pages); printf("\nPrice
of Book : %f",book[i].price);
}
return 0;
Book Details
Name of Book :
ABC Number of Pages :
100 Price of Book :
200 Name of
Book
: EFG Number of Pages
: 200 Price of Book :
300 Name of Book
: HIJ
Number of Pages : 300
Price of Book : 500
Union in C
Programming :
In C Programming we have came across Structures. Unions are similar
tostructure syntactically.Syntax of both is almost similar. Let us discuss some
important points one by one –
{ {
}s1; }s1;
If we look at the two examples then we can say that both structure and union are
same except Keyword.
char name[4];
int marks;
We have collected three variables of different data type under same name
together. Note #3 : All Union Members Occupy Same Memory Area
For the union maximum memory allocated will be equal to the data member with
maximum size. In the example character array name‘ have maximum size thus
maximum memory of the union will be 4 Bytes.
Suppose we are accessing one of the data member of union then we cannot
access other data member since we can access single data member of union
because each data member shares same memory. By Using Union we can Save
Lot of Valuable Space
Simple Example:
union u
char a;
int b;
union_member
1 ;
union_member
2 ;
union_member
3;
..
..
..
union_memberN;
}instance;
Note :
union stud
int roll;
char name[4];
int marks;
}s1;<
How Memory is Allocated ?
Union Members that compose a union, all share the same storage area within the
computers memory
Each member within a structure is assigned its own unique storage area
Unions are useful for application involving multiple members, where values
need not be assigned to all the members at any one time.
While accessing union, we can have access to single data member at a time. we can
access single union member using following two Operators –
In order to access the member of the union we are using the dot operator. DOT
operator is used inside printf and scanf statement to get/set value from/of union
member location.
Syntax :
variable_name.member
consider the below union, when we declare a variable of union type then we will be
accessing union members using dot operator.
union emp
int id;
char name[20];
}e1;
Syntax Explanation
Instead of maintain the union variable suppose we store union at particular address
then we can access the members of the union using pointer to the union and arrow
operator.
union emp
{
int id;
char name[20];
}*e1;
id can be Accessed by – union_variable->member
Syntax Explanation
C Programs
int id;
char name[20];
}e1;
e1.id = 10;
printf("\nID : %d",e1.id);
strcpy(e1.name,"Pritesh");
printf("\nName :
%s",e1.name); return 0;
}
Output :
ID : 10
Name : Pritesh
union emp
int id;
char name[20];
}e1;
e1.id = 10;
strcpy(e1.name,"Pritesh");
printf("\nID : %d",e1.id);
printf("\nName :
%s",e1.name); return 0;
}
Output :
ID : 1953067600
Name : Pritesh
As we already discussed in the previous article of union basics, we have seen how
memory is shared by all union fields. In the above example –
= sizeof(name)
= 20 bytes
Firstly we have utilized first two bytes out of 20 bytes for storing integer value. After
execution of statement again same memory is overridden by character array so while
printing the ID value, garbage value gets printed
union emp
int id;
char name[20];
}*e1;
e1->id = 10;
printf("\nID : %d",e1->id);
strcpy(e1->name,"Pritesh");
printf("\nName : %s",e1-
>name); return 0;
}
Output :
ID : 10
Name :
Pritesh Bit
fiels:
Suppose your C program contains a number of TRUE/FALSE variables grouped in a
structure called status, as follows
struct {
unsigned int
widthValidated; unsigned
int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual, we are going to store
either 0 or 1 in each of the variables. The C programming language offers a better way
to utilize the memory space in such situations.
If you are using such variables inside a structure then you can define the width of a
variable which tells the C compiler that you are going to use only those number of
bytes. For example, the above structure can be re-written as follows
struct {
The above structure requires 4 bytes of memory space for status variable, but only 2
bits will be used to store the values.
If you will use up to 32 variables each one with a width of 1 bit, then also the status
structure will use 4 bytes. However as soon as you have 33 variables, it will allocate the
next slot of the memory and it will start using 8 bytes. Let us check the following
example to understand the concept
#include
<stdio.h>
#include
<string.h>
} status2;
int main( ) {
When the above code is compiled and executed, it produces the following
result Memory size occupied by status1 : 8
Memory size occupied by status2 : 4
};
Elements Description
width The number of bits in the bit-field. The width must be less than or
equal to the bit width of the specified type.
The variables defined with a predefined width are called bit fields. A bit field can
hold more than a single bit; for example, if you need a variable to store a value from
0 to 7, then you can define a bit field with a width of 3 bits as follows
struct {
} Age;
The above structure definition instructs the C compiler that the age variable is going to
use only 3 bits to store the value. If you try to use more than 3 bits, then it will not allow
you to do so. Let us try the following example
#include
<stdio.h>
#include
<string.h> struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n",
sizeof(Age) ); printf( "Age.age : %d\n",
Age.age ); Age.age = 7;
printf( "Age.age : %d\n",
Age.age ); Age.age = 8;
printf( "Age.age : %d\n",
Age.age ); return 0;
}
When the above code is compiled it will compile with a warning and when executed, it
produces the following result
Sizeof( Age ) :
4 Age.age : 4
Age.age : 7
Age.age : 0
Typedef:
The C programming language provides a keyword called typedef, which you can use
to give a type, a new name. Following is an example to define a termBYTE for one-
byte numbers
After this type definition, the identifier BYTE can be used as an abbreviation
for the type unsigned char, for example..
By convention, uppercase letters are used for these definitions to remind the user
that the type name is really a symbolic abbreviation, but you can use lowercase, as
follows
You can use typedef to give a name to your user defined data types as well. For
example, you can use typedef with structure to define a new data type and then use
that data type to define structure variables directly as follows
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char
subject[100]; int
book_id;
} Book;
int main( ) {
Book
book;
strcpy( book.title, "C
Programming"); strcpy(
book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
When the above code is compiled and executed, it produces the following
result Book title : C Programming
Book author : Nuha Ali
#define is a C-directive which is also used to define the aliases for various data
types similar to typedef but with the following differences
typedef is limited to giving symbolic names to types only where as#define can be used
to define alias for values as well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #definestatements are
processed by the pre-processor.
#define FALSE
0 int main( ) {
printf( "Value of TRUE : %d\n", TRUE);
printf( "Value of FALSE : %d\n",
FALSE);
return 0;
When the above code is compiled and executed, it produces the following
result Value of TRUE : 1
Value of FALSE : 0
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer
can change the default value.
Above code defines the type of the data but, no any variable is created.
Variable of type enum can be created as:
enum
boolean{
false;
true;
};
Example of enumerated
type #include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday,
saturday}; int main(){
enum week today;
today=wednesday;
printf("%d
day",today+1); return 0;
}
Outpu
t4
day
You can write any program in C language without the help of enumerations but,
enumerations helps in writing clear codes and simplify programming.
The exact size of array is unknown untill the compile time,i.e., time when a compier
compiles code written in a programming language into a executable form. The size of
array you have declared initially can be sometimes insufficient and sometimes more
than required. Dynamic memory allocation allows a program to obtain more memory
space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated
space
Allocates space for an array elements, initializes to zero and then returns a
calloc() pointer to memory
malloc()
The name malloc stands for "memory allocation". The function malloc()reserves a
block of memory of specified size and return a pointer of type voidwhich can be
casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns
NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between
malloc() and calloc() is that, malloc() allocates single block of memory whereas
calloc() allocates multiple blocks of memory each of same size and sets all bytes to
zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of nelements. For
example: ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements
each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on
its own. The programmer must use free() explicitly to release space.
syntax of
free()
free(ptr);
This statement cause the space in memory pointer by ptr to be
deallocated. Examples of calloc() and malloc()
Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc() function.
# i n c l u d e
< s t d i o . h >
# i n c l u d e
<stdlib.h> int
main(){
int n,i,*ptr,sum=0;
printf("Sum=%d",sum
); free(ptr);
return 0;
# i n c l u d e
< s t d i o . h >
# i n c l u d e
<stdlib.h> int
main(){
int n,i,*ptr,sum=0;
printf("Sum=%d",sum
); free(ptr);
return 0;
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can
change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsiz
e);
Here, ptr is reallocated with size of
newsize. #include <stdio.h>
#include
<stdlib.h> int
main(){
int *ptr,i,n1,n2;
}
UNIT-IV
FILES
Consider example –
We have written C Program to accept person detail from user and we are going to
print these details back to the screen.
Now consider another scenario, suppose we want to print same data that we
have entered previously.
We cannot save data which was entered on the console before.
Now we are storing data entered (during first run) into text file and when we need this
data back (during 2nd run), we are going to read file.
Introduction to file handling in C
New way of dealing with data is file handling.
Stand
Standard Input Standard Output
s For
The precise definition of the .txt format is not specified, but typicallymatches the
format accepted by the system terminal or simple text editor.
Files with the .txt extension can easily be read or opened by any program that reads
text and, for that reason, are considered universal (or platform independent).
Text Format Contain Mostly English Characters
What are Binary Files
Explanation :
As shown in fig. Binary file is stored in Binary Format (in 0/1). This Binary file is difficult
to read for humans. So generally Binary file is given as input to the Binary file
Processor. Processor will convert binary file into equivalent readable file.
Some Examples of the Binary files :
Executable
Files Database
files
Before opening the file we must understand the basic concept of file in C Programming
, Types of File. If we want to display some message on the console from the file then
we must open it in read mode.
Opening and Defining FILE in C Programming
Before storing data onto the secondary storage , firstly we must specify following
things – File name
Data
Structure
Perpose /
Mode
Very first task in File handling is to open
file File name : Specifies Name of the
File
Firstly we need pointer variable which can point to file. below is the syntax fordeclaring
the file pointer.
FILE *fp;
while(1)
{
ch = fgetc(fp); // Read a Character
if(ch == EOF ) // Check for End of
File break ;
printf("%c",ch);
}
fclose(fp); // Close File after Reading
}
File Opening Mode Chart
r Reading – NULL
Create
w Writing Over write on Existing
New File
Create
a Append –
New File
Reading Create
w+ Over write on Existing
+ Writing New File
a+ Reading + New data is appended at the end of Create New
file
Appending File
Explanation :
File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode
If File is not present on the path specified then New File can be created using
Write and Append Mode.
Generally we used to open following types of file in C –
C Source File .c
Syntax :
int feof(FILE *stream);
What it does?
Macro tests if end-of-file has been reached on a stream.
feof is a macro that tests the given stream for an end-of-file indicator.
Once the indicator is set, read operations on the file return the indicatoruntil rewind is
called, or the file is closed.
The end-of-file indicator is reset with each input operation.
Ways of Detecting End of File
A ] In Text File :
Special Character EOF denotes the end of File
As soon as Character is read,End of the File can be detected
EOF is defined in stdio.h
Equivalent value of EOF is -1
Printing Value of EOF :
void main()
{
printf("%d", EOF);
}
B ] In Binary File :
argc
argv[]
where
,
argc – Number of arguments in the command line including
program name argv[] – This is carrying all the arguments
In real time application, it will happen to pass arguments to the main program itself.
These arguments are passed to the main () function while executing binary file from
command line.
For example, when we compile a program (test.c), we get executable file in the
name test. Now, we run the executable test along with 4 arguments in command
line like below.
./test this is a program
Where,
argc = 5
argv[0] = test
argv[1] = this
argv[2] = is
argv[3] = a
argv[4] = program
argv[5] = NULL
#include
<stdio.h>
#include
<stdlib.h>
int main(int argc, char *argv[]) // command line arguments
if(argc!=5)
}
printf("\n Program name : %s \n",
argv[0]); printf("1st arg : %s \n",
argv[1]); printf("2nd arg : %s \n",
argv[2]); printf("3rd arg : %s \n",
argv[3]); printf("4th arg : %s \n",
argv[4]); printf("5th arg : %s \n",
argv[5]);
return 0;
OUTPUT