cs3251-notes-unit-1
cs3251-notes-unit-1
Cs3251-notes-unit 1
The core concept of OOP is to separate concerns into entities which are coded as
objects. Each entity will group a given set of information (properties) and actions
(methods) that can be performed by the entity.
1.2.Applications of C Language:
o Development of video games
o Applications using graphical user interfaces
o Databases and computer operating systems
o Browsers on the internet
o Computational and graphical methods
o Banking
o Cloud computing and distributed systems
o Compilers
o Embedded systems are systems that are integrated into a larger system.
o Integrated software libraries for enterprises
o Server applications on a large scale
o Compilers of code
Top 10 applications developed in C
1. Adobe Systems
2. Google
3. Mozilla
4. Mysql
5. Winamp media player
1.3.1Structure of C program :
The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the
below-mentioned outline in order to successfully compile and execute. Debugging is
easier in a well-structured C program.
Sections of the C Program: There are 6 basic sections responsible for the proper
execution of a program. Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and
the creation date and time of the program. It is specified at the start of the program in
the form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
Or
/* description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and
this will not interfere with the given code. Basically, it gives an overview to the reader of
the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other’s improved code into our code. A copy of
these multiple files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
#include<conio.h>
3. Definition
Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of
the program. Preprocessor directives start with the ‘#’ symbol. The #define
preprocessor is used to create a constant throughout the program. Whenever this name
is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
#define pi=3.14;
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used
anywhere in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is
written in this section. Operations like declaration and execution are performed inside
the curly braces of the main program. The return type of the main() function can be int
as well as void too. void() main tells the compiler that the program will not return any
value. The int main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
Example program:
// Documentation
/**
* file: sum.c
* description: program to find sum.
*/
#include <stdio.h> // Link
#define X 20 // Definition
int sum(int y); // Global Declaration
int main(void) // Main() Function
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
int sum(int y) // Subprogram
{
return y + X;
}
Output
Sum: 75
1.3.2 Data Types in C:
.Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc.
Each data type requires different amounts of memory and has some specific
operations which can be performed over it.
The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.
The data types in C can be classified as follows:
1. Primitive Data Types --- Primitive data types are the most basic data types
that are used for representing simple values such as integers, float, characters,
etc.
2. User Defined Data Types --- The user-defined data types are defined by the
user himself.
3. Derived Types--- The data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types.
Primitive Data Types : 1. Integer Data Type
The integer datatype in C is used to store the integer numbers(any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can be stored in int data type in C.
Range: -2,147,483,648 to 2,147,483,647
Size: 4 bytes
Format Specifier: %d
Syntax of Integer
We use int keyword to declare the integer variable: int var_name;
Example: int a;
The integer data type can also be used as
unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
long int: Larger version of the int datatype so can store values greater than int.
unsigned short int: Similar in relationship with short int as unsigned int with int.
EX: // C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
return 0;
}
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Character Data Type:
Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
Example of char
// C program to print Integer data types.
#include <stdio.h>
void main()
{
char a = 'a';
char c;
printf("Value of a: %c\n", a);
}
Output
Value of a: a
Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used
to store decimal and exponential values. It is used to store decimal numbers (numbers
with floating point values) with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Example of Float
#include <stdio.h>
int main()
{
float a = 9.0f;
printf("%f\n", a);
return 0;
}
Output
9.000000
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits
after or before a decimal point.
In C, Literals are the constant values that are assigned to the variables. Literals represent
fixed values that cannot be modified. Literals contain memory but they do not have
references as variables. Generally, both terms, constants, and literals are used
interchangeably.
For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a
constant integer literal.
Types of C Literals
There are 4 types of literal in C:
Integer Literal
Float Literal
Character Literal
String Literal 1. Integer Literals
Integer literals are used to represent and store the integer values only. Integer literals
are expressed in two types i.e.
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
For Example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal.
Hence the value 16.
There are basically represented into 4 types:
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Example:
56, 78
B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.
int: No suffix is required because integer constant is by default assigned as an int
2. Floating-Point Literals
These are used to represent and store real numbers. The real number has an integer
part, real part, fractional part, and exponential part. The floating-point literals can be
stored either in decimal form or exponential form. While representing the floating-
point decimals one must keep two things in mind to produce valid literal:
In the decimal form, one must include the integer part, or fractional part, or both,
otherwise, it will lead to an error.
In the exponential form, one must include both the significand and exponent part,
otherwise, it will lead to an error.
A few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215e-10L
10.5E-3
3. Character Literals
This refers to the literal that is used to store a single character within a single quote.
To store multiple characters, one needs to use a character array. Storing more than
one character within a single quote will throw a warning and display just the last
character of the literal. It gives rise to the following two representations:
char type: This is used to store normal character literal or narrow-character
literals.
Example:
char chr = 'G';
CONSTANTS IN C:
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program. The type of constant can be an integer constant, a
floating pointer constant, a string constant, or a character constant. In C language, the
const keyword is used to define the constants.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the
list of the types of constants
Integer Constant
Character Constant
Floating Point Constant
Double Precision Floating Point Constant
Array Constant
Structure Constant
Difference Between Constants and Literals
Constant :
Constants are variables that cannot be modified once declared.
Constants are defined by using the const keyword in C. They store literal
values in themselves.
These keywords have specific purposes within the C programming language and cannot
be used as identifiers for variables, functions, or any other user-defined names.
Operators: Precedence and Associativity
In C language, operators are symbols that represent operations to be performed on one
or more operands. They are the basic components of the C programming. In this article,
we will learn about at all the built-in operators in C with examples.
What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we can
say that the operators are the symbols that perform operations on operands.
Precedence:
If there is more than one operator in an expression, which operation we need to
perform first is specified by precedence.
Associativity:
If more than one operator has the same precedence which operation we need to
perform is specified by associativity.
Example:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
'C' operators can be classified into 8 categories.
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
Arithmetic operators:
'C' provides all the basic arithmetic operators.
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division
Unary minus example: -2, 2*-1
Note: Modulo division operator (%) is used only for integral values and cannot be
used on floating point data.
*, /, %----------highest precedence
+,----------------lowest precedence
Operator Meaning
< is less than
<= is less than or equal
> is greater than
>= is greater than or equal
== is equal to
!= is not equal to
Form:
Where ae-1 and ae-2 are arithmetic expressions, which may be simple constants,
variables, or combination of them.
The logical operators && and || are used when we want to test more than one condition
and make decisions.
The logical expression:
An expression which combines 2 or more relational expressions is termed as a logical or
compound relational expression.
Example program:
#inclu
de<std
io.h>
main()
{
int marks,a,b;
printf("enter
marks\n");
scanf("%d",&
marks);
printf("enter 2 int
values\n");
scanf("%d
%d",&a,&b);
printf("marks>=90 && marks<=100: %d\
n",marks>=90 && marks<=100);
printf("a>=b || b>=a=%d\n",a>=b ||
b>=a); printf("!a=%d\n",!a);
}
Local NOT------------highest precedence, Associativity from Right-> Left
Logical AND----------------next highest precedence, Associativity from Left -> Right
Logical OR----------------lowest precedence, Associativity from Left -> Right
Assignment operators:
Assignment operators are used to assign the result of an expression to a variable.
Assignment operator is '='.
Example:
a=10;
Left hand side must be a variable; Right hand side may be a variable/constant
or combination of these two.
'C' has a set of 'shorthand' assignment operators of the form
v op=exp;
Example program:
#include<stdio.h>
main()
{
int a,n;
printf("enter a,n values\n");
scanf("%d%d",&a,&n);
a += 100;
printf("a=%d\n",a);
a -= 20;
printf("a=%d\n",a);
a *= (n+1); printf("a=
%d\n",a);
a /= (n+1); printf("a=
%d\n",a); a %= n;
printf("a=%d\n",a);
}
Increment and Decrement operators:
'C' has two very useful operators not generally found in other languages.
These are increment and decrement operators:
++ and --
The operator ++ adds 1 to the operand.
The operator -- subtracts 1 from the operand.
Both are unary operators.
We use the increment and decrement statements in for and while loops extensively.
Statement with
Meaning
Operator
Example Program:
#include<stdio.h>
main()
{
int a,n;
printf("enter a value\n");
scanf("%d",&a);
n=a++; printf("a=%d\tn=%d\
n",a,n); n=++a; printf("a=%d\
tn=%d\n",a,n); n=a--;
printf("a=%d\tn=%d\n",a,n);
n=--a; printf("a=%d\tn=%d\
n",a,n);
}
Output:
enter a value
4
a=5 n=4
a=6 n=6
a=5 n=6
a=4 n=4
Conditional operator:
Output 1:
enter n value
4
4 is even number
Output 2:
enter n value
5
5 is odd number
Example:
#include<stdio.h>
main()
{
float a,b,c,d;
printf("enter a,b,c,d values\n"); scanf("%f%f%f
%f",&a,&b,&c,&d);
(c-d!=0)?printf("%f",(a+b)/(c-d)):printf("c-d is 0");
}
Output 1:
entera,b,c,d values 3
4
5
2
2.333333
Output 2:
entera,b,c,d values 3
4
5
5
c-d is 0
Bitwise operators:
For manipulation of data at bit level, a special operators known as bitwise operators are
introduced.
These operators are used for testing the bits or shifting them right or left.
Bitwise operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
~ One’s Complement
Truth table for Bitwise AND, Bitwise OR and Bitwise Exclusive OR:
Example 1:
x=9
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=1001
y=0111
z= 0001
Next convert the binary number to decimal number to get final result z = 9 &
7=1
Example2:
x=4
y=14
x=0100
y=1110
z=0100 = 4
z = 4 & 14=4
Bitwise OR (|):
Example 1:
x=8
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=1000
y=0111
z=1111
Next convert the binary number to decimal number to get final result z = 8|
7=15
Example2:
x=4
y=14
x=0100
y=1110
z=1110 = 14
z = 4 | 14=4
Example 1:
x=5
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=101
y=111
z=010
Next convert the binary number to decimal number to get final result z = 5 ^
7=2
Example2:
x=4
y=14
x=0100
y=1110
z=1010 = 10
z = 4 ^ 14=4
Example 1:
Find complement of 5 (~5)
Step1:
Convert decimal 5 into binary and take 8 bits.
0000 0101
First perform bits complement means change 1’s as 0’s and 0’s as 1’s (1’s complement).
1111 1010
MSB LSB
Step2:
If the MSB bit of result of bits complement is 1, then the final result contains –ve sign. Always
negative numbers in the system are represented using 2’s complement form.
Finding 2’s complement means 1’s complement + 1. 0000
0101---------------------------1’s complement
+1 (in binary addition 1+1 = 10 means 1 as carry and 0 as sum)
Note:
(In binary addition 1+1 = 10 means 1 as carry and 0 as sum, 1+0=1, 0+0=0)
Example 2:
Find complement of -5 (~-5)
Step1:
Always negative numbers in the system are represented using 2’s complement form. First take +5
in binary form, find 2’s complement of that number.
0000 0101
1111 1010
+1
Step2:
Perform bits complement (1’s complement) on step1 result. 0000
0100-----------------------4
If the MSB bit of the result contains 0, then the resulting number have the + sign. (~-
5)=+4
Where v is the integer expression (value) that is to be shifted and n is the number of bit positions
to be shifted.
Left shift:
Left shift means given number multiply by 2 per each shift.
Example:
6<<1 or x=6, x<<1
00000 110
87654321
00001110
87654321
This is the final bit result. Convert binary to decimal and it is equal to decimal 12. 6 << 1 =
12
Special operators:
C supports some special operators of interest such as:
i. Comma operator (,)
ii. sizeof operator
iii. pointer operators (&, *)
iv. member selection operators (., ->)
v. function call symbol ()
vi. array subscript operator []
Comma operator:
This can be used to link the related expressions together.
Comma liked lists of expressions are evaluated from left to right. And the value of right
most expression is the value of the combined expression.
Comma operator has the lowest precedence of all operators, the parenthesis are
necessary.
Example:
Expressions:
Arithmetic expressions:
An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language.
Examples:
Algebraic expression C expression
a×b–c a*b-c
(m + n)(x + y) (m+n)*(x+y)
ab a*b/c
c
3x2+2x+1 3*x*x+2*x+1
x x/y+c
+c
y
Evaluation of expressions:
Expressions are evaluated using an assignment statement.
Where variable is any valid 'C' variable name.
variable = expression
Example:
a=9, b=12, c=3
x=a–b/3+c*2–1
x = 9 – 12 / 3 + 3 * 2 – 1
Finally x = 10
Type conversion:
char
shortint
int
longint
float
double
long double
Conversion of small data type to big is broadening. Conversion of big data type to small is narrowing.
(small and big in terms of number of bytes)
Conversions are of two types:
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion:
Computer considers one operator at a time, involving 2 operands.
If the operands are of different types, the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds.
The result is of the ‘higher’ type.
The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it.
The following rules are followed:
i. float to int causes truncation of the fractional part.
ii. double to float causes rounding of digits.
iii. longint to int causes dropping of the excess higher order bits.
Example:
#include<stdio.h>
main()
{
int a;
floatb,c;
printf("enter a,b values\n");
scanf("%d%f",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output: entera,b
values 4
5
c=0.800000
Explicit type conversion or casting a value:
For example,
#include<stdio.h>
main()
{
int a,b;
float c;
printf("enter a,b values\n");
scanf("%d%d",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values 4
5
c=0.000000
Consider the statement c=a/b;
Here a, b are integer data type, so integer division is performed. The result of this division
is 0. So, the decimal part of the division would be lost and the result is not correct.
This problem can be solved by converting locally one of the variables to the floating point.
c=(float)a/b;
The operator (float) converts the 'a' to floating point for the purpose of evaluation of
the expression.
Then automatically conversion is done and then the division is performed in floating point
mode.
This process of such a local conversion is known as casting a value.
Form is
(type name) expression
Where type name is one of the valid ‘C’ data types and the expression may be a constant,
variable or an expression.
Usage of type conversion:
Example Action
x = (int) 4.78 4.78 is converted to integer by
truncation and result would be 4
a=(int)13.4/4 Evaluated as 13/4 and the result
would be 3
d=(double)12/5 Division is done in floating point
mode and result would be 2.400000
* Multiplication
/ Division Left to Right 3
% Modulo division (modulus)
+ Addition Left to Right 4
- Subtraction
<< Left Shift Left to Right 5
>> Right Shift
the width of the field, the number of decimal places printed and the justification. Format specification
determines how the variables to be output should be displaed on the screen, is provided in the control string.
Example Program:
#include <stdio.h>
int main() {
char name[20];
int age;
printf("Enter your name: ");
scanf("%s", name);
return 0;
}
Output:
Enter your name: Avi
Enter your age: 22
Your name is Avi and your age is 22
Explanation:
We first declare the variables name and age in the above example. After that, the user is prompted for their
name and age using the printf() function. We utilize the scanf() function to read user input and assign it to the
appropriate variables. To format the input, we finally employ the printf() function once more.
3. getchar()The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads one
character at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
Syntax:
Variable-name = getchar();
4. gets()gets() function reads a group of characters or strings from the keyboard by the user
and these characters get stored in a character array. This function allows us to write space-
separated texts or strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number];
gets(str);
5. puts()I n C programming puts() function is used to display a group of characters or
strings which is already stored in a character array. This function is declared in
stdio.h(header file).
Syntax:
puts(identifier_name );
6. putch() This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name); .
7.putchar() It is used to display one character at a time on the monitor.
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) {
printf("10 is greater than 15");
}
Output: I am Not in if
As the condition present in the if statement is false. So, the block
below the if statement is not executed.
2. if-else in C
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t.
We can use the else statement with the if statement to execute a block of code when the
condition is false.
The if-else statement consists of two blocks, one for false expression and one for true
expression.
Syntax of if else in C:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example Program:
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15) {
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
Flowchart of Nested if-else Example of Nested if-else:
#include <stdio.h>
void main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
}
Output : i is smaller than 15
i is smaller than 12 too
4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed. if-else-if ladder is similar to the switch statement
Syntax of if-else-if Ladder Flowchart of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example Program:
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
Output : i is 20
5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the conditional
code based on the value of the variable specified in the switch statement. The switch block consists of cases to
be executed based on the value of the switch variable.
Syntax of switch Flowchart of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
EXAMPLE PROGRAM:
#include <stdio.h>
void main()
{ int var = 2;
switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}
}
Output:
Case 2 is executed
JUMP STATEMENTS IN C:
These statements are used in C for the unconditional flow of control throughout the functions in a program.
They support four types of jump statements:
break
continue
goto
return
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is encountered from
within a loop, the loop iterations stop there, and control returns from the loop immediately to the first
statement after the loop.
Syntax of break:
break;
Basically, break statements are used in situations when we are not sure about the actual number of iterations
for the loop or we want to terminate the loop based on some condition.
Syntax of continue
continue;
C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump from one
point to another within a function.
D) return
The return in C returns the flow of the execution to the function from where it is called. This statement does
not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the
program stops immediately and returns the control from where it was called. The return statement may or
may not return anything for a void function, but for a non-void function, a return value must be returned.
LOOP STATEMENTS IN C:
Loops in programming are used to repeat a block of code until the specified condition is met. A loop
statement allows programmers to execute a statement or group of statements multiple times without
repetition of code.
There are mainly two types of loops in C Programming:
Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the
main body of the loop. For Loop and While Loop is Entry-controlled loops.
Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop
body. The loop body will execute at least once, irrespective of whether the condition is true or false.
do-while Loop is Exit Controlled loop.
for Loop:
for loop in C programming is a repetition control structure that allows programmers to write a loop that will
be executed a specific number of times. for loop enables programmers to perform n number of steps together
in a single line.
Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
FLOW CHART: EXAMPLE
PROGRAM:
#include <stdio.h>
void main()
{
int i = 0;
for (i = 1; i <= 5; i++)
{
printf( "Hello World\n");
}
}
OUTPUT:
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If
the test condition will become false then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;
FLOWCHART: EXAMPLE
PROGRAM:
#include <stdio.h>
void main()
{
int i = 2;
while(i < 5)
{
printf( "Hello World\n");
i++;
}
}
OUTPUT: Hello World
Hello World
Hello World
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition
which is tested at the end of the body. In the do-while loop, the loop body will execute at least once
irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
Example Program:
#include <stdio.h>
int main()
{
int i = 2;
do
{
printf( "Hello World\n");
i++;
} while (i < 1);
}
Output:
Hello World
Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body will be
executed once..
PREPROCESSOR DIRECTIVES IN C :
Preprocessors are programs that process the source code before compilation. Several steps are involved
between writing a program and executing a program in C. Let us have a look at these steps before we actually
start learning about Preprocessors.
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source code
before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates
that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed. We can place
these preprocessor directives anywhere in our program.
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in detail.
1. Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is encountered by
the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to
define a macro.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program. The
#include preprocessor directive is used to include the header files in the C program.
There are two types of files that can be included by the user in the program:
Standard Header Files
The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc. These files
must be included to work with these functions. Different functions are declared in different header files.
For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string
operations are in the ‘string’ file.
Syntax
#include <file_name>
where file_name is the name of the header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look
for the file in the standard directory.
User-defined Header Files
When a program becomes very large, it is a good practice to divide it into smaller files and include them
whenever needed. These types of files are user-defined header files.
Syntax
#include "filename"
3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of the
program or to skip the compilation of some specific part of the program based on some conditions. There are
the following preprocessor directives that are used to insert conditional code:
#if Directive
#ifdef Directive
#ifndef Directive
#else Directive
#elif Directive
#endif Directive
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:
#undef Directive
#pragma Directive
1. #undef Directive
The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT”
statement will evaluate as false.
2. #pragma Directive
This directive is a special purpose directive and is used to turn on or off some features. These types of
directives are compiler-specific, i.e., they vary from compiler to compiler.
Syntax
#pragma directive
COMPILATION PROCESS:
The compilation is a process of converting the source code into object code. It is done with the help
of the compiler. The compiler checks the source code for the syntactical or structural errors, and if
the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or machine
code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the directive
and replace this directive with the content of the 'stdio.h' file.
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code. Or we can say that the C compiler converts the pre-processed code into
assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is
'.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the
object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-compiled,
and the object code of these library files is stored with '.lib' (or '.a') extension. The main working of
the linker is to combine the object code of library files with the object code of our program.
Sometimes the situation arises when our program refers to the functions defined in other files; then
linker plays a very important role in this. It links the object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object code of our program with the
object code of the library files and other files. The output of the linker is the executable file. The
name of the executable file is the same as the source file but differs only in their extensions. In DOS,
the extension of the executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'.
For example, if we are using printf() function in a program, then the linker adds its associated code
in an output file.
hello.c
#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}
In the above flow diagram, the following steps are taken to execute a program:
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the
preprocessor converts the source code into expanded source code. The
extension of the expanded source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler
converts this expanded source code into assembly code. The extension of the
assembly code would be hello.s.
o This assembly code is then sent to the assembler, which converts the
assembly code into object code.
o After the creation of an object code, the linker creates the executable file.
The loader will then load the executable file for the execution.
STORAGE CLASSES IN C:
In the C programming language, storage classes define the scope, visibility, and
lifetime of variables. There are four primary storage classes in C:
1.Automatic Storage Class (auto):
Variables declared inside a function without any storage class specifier are
by default of auto storage class.
They are created when the function is called and destroyed when the
function exits.
Their scope is limited to the block in which they are defined.
2. Static Storage Class (static):
Variables declared with the static keyword inside a function retain their
value between function calls.
They are initialized only once at the beginning of the program execution and
retain their value until the program terminates.
Their scope is limited to the block in which they are defined, but they have
file scope if declared outside any function.
3.Register Storage Class (register):
Variables declared with the register keyword are stored in CPU registers instead of RAM,
allowing faster access.
The compiler decides whether to store the variable in a register based on factors such as
availability and usage pattern.
Their scope is limited to the block in which they are defined.
4.External Storage Class (extern):
Variables declared with the extern keyword have global visibility across multiple files.
They are defined outside of any function or block and can be accessed by any function within
the same program or in other files if properly declared.
They are not allocated storage space when declared with extern, but rather refer to the
memory space allocated for the variable elsewhere in the program.
Additionally, there is a fifth storage class in C, known as Thread Storage Class (thread_local),
which specifies that the declared variable has a separate instance for each thread. It was
introduced in C11 to support multithreading environments.