Unit 1
Unit 1
History of C language:
Monolithic programs have only one program module. It does not support the
concept of subroutines.
The global data can be accessed and modified from any part of the program
Ex: BASIC
Drawbacks:
Used only for very small and simple applications where reusability is not a
concern
Difficult to debug
program sure is large
ii) Procedural Programming
A program is divided into subroutines that can access global data.
To avoid repetition of code, subroutine can be called when needed.
Ex: C, Pascal
Advantages:
Modularization makes it easier to write, debug and understand the program
Supports reusability.
Individual procedures are easy to change as well as understand
Disadvantages:
Not data centred
Main focus is on functions.
iv) Object oriented programming:
It treats data as a critical element in the program development and restricts its
flow freely around the system.
It is a data and task based.
2. Web Browsers
Google file system and Google chromium browser were developed using C/C++. Not
only this, the Google Open Source community has a large number of projects being
handled using C/C++. Since Mozilla Firefox and Thunderbird were open-source
email client projects, they were written in C/C++.
3. Microcontrollers
C language is used in system programming which replaces the need of assembly
language. The compiler of C directly converts into machine language.
4.Scientific systems
C language is used in building and creating many scientific systems. It is the parent
language for advanced languages.
5. Assemblers
Assemblers executing machine-level hardware-specific systems are created
using C language.
6. Text Editors
No language create better text editor other than C language
7. Print spoolers
The software program which is responsible for sending the jobs to the printer once the
command is given is created with the help of the C programming language.
8. Network Drivers
The network drivers responsible for accessing the internet and running the WIFI and
other kinds of drivers are all written in C language
9. Modern Programs
Various modern programs whose major requirement is to consume less memory and
need hardware communication are written in the C programming language.
10. Databases
There are many databases that are required to store a huge amount of data in them and
thus are written in C language. MySQL, again being an open source project, used in
Database Management Systems was written in C/C++.
12. Utilities
Various and program system-specific utilities are written in C language.
The documentation section consists of a set of comment lines giving the name of
program, the author and other details.
Preprocessor directives:
It contains special instructions that indicate how to prepare the program for
compilation.
Preprocessor commands like 'include' tells the compiler that some information
needed from the specified header file.
Example: #include<stdio.h>
The variables are declared outside the main() function and are visible through
program are called global variables.
Every 'C' program must have one main() function, where the execution begins.
Statement section:
Execution of a program begins with opening brace ‘{’and ends with closing ‘}’.
The closing brace of the main function is the logical end of the program.
All the statements in the program ends with a semicolon(;) except conditional
and control statements.
Example:
#include<stdio.h> //header file
int main() //execution begins
{
printf ("Welcome"); //statement
return 0; //return value to the function
}
1.4 C Programming : Data Types
Data type determines the set of values that a data item can take and the operations
that can be performed on the item.
TYPES DATA TYPES
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Userdefined Data Type enum
Syntax:
storageclasstype datatype var1,var2….varn;
Example:
#include<stdio.h>
{
auto int a=10;
printf(“a=%d”,a);
{
int b=20;
printf(“b=%d”,b);
}
printf(“Here b is not visible\n”);
printf(“a=%d”,a);
}
OUTPUT:
a=10
b=20
Here b is not visible
a=10
1.5 Operators:
Operator
An operator is a symbol that is used to perform specific mathematical or logical
manipulations.
For e.g, a=2+3
Here = , + are the operators
Operands
An operand specifies an entity on which an operation is to be performed. It can be a
variable name, a constant, a function call.
Eg: a=2+3
Here a, 2, 3 are operands
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator
Classification based on Number of Operands
Types:
1. Unary Operator: A unary operator operates on only one operand. Some of
the unary operators are,
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator
Unary Minus:
An operand is proceeded by a minus sign, the unary operator negates its value.
Ex:
int a,b=10;
a=-b;
printf(“%d”,a);
Output: -10
Increment operator and Decrement operator
++ and -- are increment and decrement operator.
Pre increment or Pre decrement: First the value is either incremented or
decremented before performing the operation.
Post increment or Post decrement: First do the operation then incremented or
decrement the value.
Operator Meaning Example A=5
++a Pre increment printf(“A=%d”,++a) A=6
--a Pre decrement printf(“A=%d”,--a) A=5
a++ Post increment printf(“A=%d”,a++) A=5
a-- Post decrement printf(“A=%d”,a--) A=6
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary
operator.
2) Relational operators:
4.Logical operators:
Logical operators are used to perform more than one condition at a time and
combine the results of two or more conditions.
Logical operators are used to logically relate the sub-expressions. There are 3
logical operators in C, they are
If the relation is true, it returns value 1 and if the relation is false, it returns value
0.
Operator Meaning of
Operator Example A=9,B=5,C=2 Description
E.g.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
%= sum = sum%10
sum%=10
&= sum = sum&10
sum&=10
^= sum^=10 sum = sum^10
Syntax: variable=expression(or)value;
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
7.Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
It is used to seperate the statement elements such as variables, constants or
expression etc.
E.g. int a=2,b=3,x=0;
b) sizeof Operator
It is unary operator,that returns the size of its operand in bytes.
It is a compile time operator.
Example : sizeof(char) will give us 1.
sizeof(a), where a is integer, will return 2.
c) Conditional Operator
It is the only ternary operator available in C.
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C.
Syntax :
(Condition?true_value:false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c
will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax : &operand
E.g. &a will give address of a.
1.6. Precedence and Associativity
Precedence of operators
The precedence rule is used to determine the order of application of operators in
evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same
precedence in the sub expression.
An operator can be left-to-right associative or right-to-left associative.
Category Operators Associativity Precedence
1.7 Expressions in C
An expression is a combination of variables, constants and operators. Every
expression is evaluated to a value.
i.e., every expression results in some value of certain type that is assigned to a
variable.
Some examples of C expressions are given below.
Streams
Text stream: Sequence of characters is divided into lines with each line being
terminated with a new line character(\n).
Binary stream: Contains data values using their memory representation.
Input and Output streams in C:
printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()
The variable must be separated by commas, and need not be preceded with &
sign.
The control string and the variables must match in their order.
The control string must be in quotations.
Print special messages wherever required in output.
1.8.2 Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
Eg:
char c;
c=getchar();
2. putchar() This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Eg.
char c=”C”;
putchar(c);
3. getch() and getche() : getch() accepts only a single character from keyboard. The
character entered through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
4. putch(): putch displays any alphanumeric characters to the standard output device.
It displays only one character at a time.
Syntax
putch(variable_name);
b) String I/O
1.gets() – This function is used for accepting any string through standard input
(keyboard) until enter key is pressed.
Syntax:
gets(variable_name);
2. puts() – This function prints the string or character array.
Syntax
puts(variable_name);
Syntax: variable=expression:
Example:
Programmers can take decisions in their program with the help of control statements.
The types of control statements are,
Flow of control: The order in which the program statements are executed is known as
flow of control. By default, statements in a c program are executed in a sequential
order
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to
another based on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Program control is transferred from one point to
another without checking any condition
Eg) goto, break, continue, return
Test
if (test expression)
expres
Statement; F
Statement
Syntax:
if (test expression)
Test
Statement T;
expres
else sion
Statement F;
Statement Statement
F
Syntax:
if(outer test condition)
{
if(inner test condition)
{
True statement 1;
}
else
{
False statement 2;
}
else
{
False statement (3);
}
}
FLOWCHART:
Test
expre1
Test
exp 2
Stmtblock1
Stmtblock2 Stmtblock3
Stmt Y
Example:
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter 3 numbers…”);
scanf(“%d%d%d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“a is the greatest”);
}
else
{
printf(“c is the greatest”);
}
}
else
{
if(b>c)
{
printf(“b is the greatest”);
}
else
{
printf(“c is the greatest”);
}
}
}
Execution:
Input:
Enter 3 numbers…56,89,23
Output:
b is the greatest
v) Switch statement
• It is a multi way branch statement.
• It provides an easy & organized way to select among multiple operations
depending upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets
executed.
4. If no match occurs, then all the statements after the default statement get executed.
• Switch ,case, break and default are keywords
• Break statement is used to exit from the current case structure
Flowchart
case :
constant 1 statement break
Syntax
switch(expression)
{ case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;
… case value n:
program statement;
program statement;
……
break;
default: program statement;
program statement;
Example:
#include<stdio.h>
void main(){
int n;
printf(“Enter any number (1 to 7)”);
scanf(“%d”, &n);
switch(n)
{
case 1:
printf(“Today is Monday”);
break;
case 2:
printf(“Today is Tuesday”);
break;
case 3:
printf(“Today is Wednesday”);
break;
case 4:
printf(“Today is Thursday”);
break;
case 5:
printf(“Today is Friday”);
break;
case 6:
printf(“Today is Saturday”);
break;
case 7:
printf(“Today is Sunday”);
break;
default:
printf(“Wrong number entered”);
}}}
Execution:
Input:
Enter any number (1 to 7): 5
Output:
Today is Friday
b)Unconditional branching statements
i)The goto Statement
This statement does not require any condition. Here program control is transferred to
another part of the program without testing any condition.
Syntax:
goto label;
continue;
Example:
#include<stdio.h>
void main()
{
int i;
for(i=1; i<=10; i++)
{
printf(“hello\t”);
if(i==5)
continue;
}
printf(“\nYou came out of loop”);
}
Execution:
Output:
hello hello hello hello hello hello hello hello hello
You came out of loop
iv)return statement:
A return statement terminates the execution of a function and returns the control to
the calling function.
Syntax:
return; (or) return expression;
Difference between break and continue statement:
break continue
break statement takes the control to the continue statement takes the control to
outside of the loop. the beginning of the loop.
It is used in switch statements. It is used in loop statements.
Always associated with if condition in This is also associated with if condition.
loops.
Initialization
Condition
4.Nested loops
• If the body of a loop contains another iteration statement, then we say that the
loops are nested.
• Loops within a loop are known as nested loop.
• In nested for loops two or more for statements are included in the body of the
loop.
• The numbers of iterations in this type of structure will be equal to the number
of iterations in the outer loop multiplied by the number of iterations in the
inner loop.
Syntax
for(condition)
{
for(condition)
{
Statements;
}
Statements;
}
Example:
#include<stdio.h>
void main()
{
int i,j;
for(i=1; i<=3; i++)
{
printf(“\n”);
for(j=1; j<=3; j++)
printf(“%d\t”, i);
}}
Execution:
Output:
1 2 3
1 2 3
1 2 3
Difference between while and do while loop
S.No while loop do while loop
1. while loop is an entry do while loop is an exit
controlled loop. controlled loop.
2. Since condition is Since condition is
checked first, the looping checked later, the looping
statements may or may statements will execute
not executed. atleast once.
Preprocessor
Directives
Assembly source
Sample.s It is a program that
code
converts assembly source
code to object code.
Assembler
Executable
Sample.exe Executable code is loaded
code
in CPU and executed by
loader program.
Loader
Execution
Example:
Simple C program to explain define and undefine statements.
#include<stdio.h>
#define PI 3.1415
void main()
{
printf(“%f”, PI);
}
Output: 3.141500
#include<stdio.h>
#define PI 3.1415
#undef PI
void main()
{
printf(“%f”, PI);
}
Output: error:’PI’ undeclared
1.14 Compilation Process: Compiling a C program is a multi-stage process. At an
overview level, the process can be split into four seperate stages: Preprocessing,
compilation, assembly, and linking.
Example:
#include<stdio.h>
int
main(void)
{
puts(“Hello , World!”);
return 0;
}
Preprocessing
The first stage of compilation is called preprocessing.
In this stage, lines starting with a # character are interpreted by the preprocessor
as preprocessor commands.
These commands form a simple macro language with its own syntax and
sematics.
This language is is used to reduce repetition in source code by providing
functionality to inline files, define macros and to conditionally omit code.
Compilation
The second stage of compilation is confusingly enough called compilation. In
this stage, the preprocessed code is translated to assembly instructions specific to
the target processor architecture. These form an intermediate human readable
language.
The existence of this step allows for Ccode to contain inline assembly
instructions and for different assemblers to be used.
Some compilers also supports the use of an integrated assembler, in which the
compilation stage generates machine code directly, avoiding the overhead of
generating the intermediate assembly instructions and invoking the assembler.
Assembler
During the assembly stage, an assembler is used to translate the assembly
instructions to machine code, or object code. The output consists of actual
instructions to be run by the target processor.
Linking
The object code generated in the assembly stage is composed of machine
instructions that the processor understands but some pieces of the program are
out of order or missing.
To produce an executable program, the existing pieces have to be rearranged and
the missing ones filled in. This process is called linking.