New UNIT-II
New UNIT-II
UNIT-II
BASICS OF C PROGRAMMING
Programming paradigm
Programming paradigm is an approach to solve problem using some programming language.
It is a method to solve a problem using tools and techniques that are available to us following some approach.
There are lots for programming language that are known but all of them need to follow some strategy when
they are implemented and this methodology/strategy is paradigms.
Apart from varieties of programming language there are lots of paradigms to fulfill each and every demand.
HISTORY OF C LANGUAGE
All modern computer languages are started through the ALGOL language in 1960.
After, the COBOL was being used for commercial applications.
FORTRAN was developed for scientific applications.
A committee was formed to develop a new language called Combined Programming Language (CPL)
at Cambridge University.
Basic CPL was derived by BCPL. BCPL was developed by Martin Richards at Cambridge University
by 1967.
At the same time a language called ‘B’ was developed by Ken Thomson at AT & T’s Bell labs in
1970.
Then C language is developed by Dennis Ritchie in 1972 with some additional features of BCPL and
B which is very simple.
ANSI C (American National Standard Institute) has begun to work on a standardized definition of the
‘C’ language that makes it still powerful
lOMoARcPSD|188 724 01
Types of Languages
Low Level Language (Or) Machine Language
Binary language (0’s & 1’s). It is understandable by computer machine.
High Level Language
Normal English, Human Understandable Language, Machine Independent, C, C++, etc…
Middle Level Language
C Language is also called as Middle Level Language because ‘C’ stands in between Low Level Language
(nor) High Level Language (i.e) it performs task of low level languages as well as high level language.
Application of C Language
Operating Systems. The first operating system to be developed using a high-level programming language was
UNIX, which was designed in the C programming language.
Embedded Systems
The C programming language is considered an optimum choice when it comes to scripting applications and
drivers of embedded systems, as it is closely related to machine hardware.
GUI
GUI stands for Graphical User Interface. Adobe Photoshop, one of the most popularly used photo editors
since olden times, was created with the help of C. Later on, Adobe Premiere and Illustrator were also created
using C.
Google
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+
+.
MySQL
MySQL, again being an open-source project, used in Database Management Systems was written in C/C++.
Compiler Design.
Since the C programming language is relatively faster than Java or Python, as it is compiler- based, it finds
several applications in the gaming sector.
lOMoARcPSD|188 724 01
STRUCTURE OF C PROGRAM
Discuss about the structure of C program in detail.[NOV/DEC 2019]
Documentation Section
It consists of set of comment lines used to specify the name of the program, the author and other details, etc.
Comments
Comments are very helpful in identifying the program features and underlying logic of the program.
The lines begins with ‘/*’ and ending with ‘*/’ are known as comments lines.
These lines are not executable. There are two types of comment lines,
Single Comment Line eg., //ABCD….
Nested Comment Line (or) Multiple Comment Line
e.g, /*……..
……..*/
Preprocessor Section
It is used to link system library files for defining the macros and for defining the conditional inclusion.
C program depends upon some header file for function definition that is used in program.
Header file is extended with ‘.h’.
This file should be included using #.
Eg., #include<stdio.h>, #define A 10, #if def, #endif…
Main Function
Every C program must contain main function.
Without main function that is not a C program.
After main function empty parenthesis are necessary.
Main () is the starting point of every ‘C’ program.
The execution always begin with the main function
The execution starts with opening brace ‘{’ & closing brace ‘}’
In between these braces the programmer should write executable and declaration part.
Executable part - It contains a set of statements or a single statement. These statements are enclosed
between the braces.
Declaration part - It declares the entire variables that are used in executable part. Variable initialization is
done in declaration section.
lOMoARcPSD|188 724 01
Sub Program Section (Or) User Defined Function- These section defined by user are called user defined
functions. These functions are defined after the main function (Or) before the main function.
Programming Rules
While writing a program, a programmer should follow the following rules.
All statements should be written in lowercase letters.
Uppercase letters are only used for symbolic constants.
Blank space may be inserted between the words. But blank space is not used while declaring a
variable, keyword, constant and function.
The programmers can write the statement anywhere between the two braces.
We can write one or more statements in a same line by separating each statement in a same line with
semicolon (:).
The opening and closing braces should be balanced.
C Tokens
Token is defined as the collection of entities such as identifiers, keywords, constants, strings, operators and
special symbols.
A token is source-program text that the compiler does not break down into component elements.
Identifiers
Identifier is a combination of alphanumeric characters.
An identifier is used for any variable, function, data definition, etc.
Eg., STDNAME, _SUB, TOT_MARKS – Valid Identifiers
Eg., Return, STD NAME - Invalid Identifiers
Rules for Naming an Identifier
It consists of letters (uppercase & lowercase), digits and underscore ( _ ) only.
The first letter of an identifier should be either a letter or an underscore.
No space and special symbols are allowed between the identifier.
The identifier cannot be a keyword.
DATA TYPES
DIFFERENT DATA TYPES IN C
Explain the various data types available in C with example. (Or) Discuss the basic data types in
C. (May/June 2016)[Nov/Dec2021] Data types
Data types are the keywords, which are used for assigning a type to a variable.
Allows the programmers to select the appropriate data type as per the need of the application.
Data types are used to specify the types of data that are going to process within the program.
lOMoARcPSD|188 724 01
Example Program
#include<stdio.h>
main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21;
/* assign float value */ letter = 'A';
/* assign character value */ pi = 2.01E6;
/* assign a double value */ printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}
Output
value of sum = 10
value of money = 2.210000 value of letter = A
value of pi = 2.010000e+06
CONSTANTS
What are Constants? Explain the various types of constants in C. (April/May 2015)
Constants are the entity whose values can't be changed during the execution of a program.
Eg: x=3, Here 3 is a constant.
Constants are classified into two types. They are,
Numerical Constant
Character Constant
Numerical Constant
It is divided into two types,
Integer Constant
Real Constant
Integer constants are the numeric constants formed with the sequence of digits without any fractional part or
exponential part.
There are three types of integer constants in C language: decimal constant (base 10), octal constant (base 8)
and hexadecimal constant (base 16).
Decimal Digits: 0 1 2 3 4 5 6 7 8 9
Octal Digits: 0 1 2 3 4 5 6 7
Hexadecimal Digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
Example
Decimal Constants: 0, 9, 22, etc.
Octal Constants: 021, 077, 033, etc.
Hexadecimal Constants: 0x7f, 0x2a, 0x521, etc.
lOMoARcPSD|188 724 01
Character Constant
Character constants are the constant which use single quotation around characters.
String Constant
A string constant is a sequence of characters enclosed in double quotes, the characters may be letters,
numbers, special characters and blank spaces, etc.
Eg: “Hello”, ”23”, “a”, etc.
VARIABLE
Variables are memory location in computer's memory to store data.
To indicate the memory location, each variable should be given a unique name called identifier.
A variable is an identifier that is used to represent some specified type of information within a
designated portion of the program.
Rules for naming the variables
Variable name can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
The first letter of a variable should be either a letter or an underscore.
No commas or blank spaces are allowed within a variable name.
There is no rule for the length of length of a variable. However, the first 31 characters of a variable
are discriminated by the compiler.
Variable Declaration
Declaration of variable can be done in the declaration part of the program.
The variables must be declared before they are used in the program.
Syntax
Data_type variable name;
Example
int a; char m; float s;
Initializing Variables
Value can be initialized in the valuable name using an assignment operator = .
Syntax
Data_type variable name = value; (or) variable name=value;
Example
Eg: int x=2;
x=2;
Scope of the Variable
Scope of the variable implies the availability of variables within the program.
Variables have 2 types of scope.
Local variables
Global variables
lOMoARcPSD|188 724 01
Local Variables
Local variables are defined inside a main function block (Or) inside a compound statement of a function
subprogram are called local variables.
Example
function() { int i, j;
}
Global / External Variables
The variables that are declared before the function main() are called the global / external variables.
Eg:
int a, b; // here a,ball is a global variables.
main() {
…… function()
}
function() {
…….}
Enumerated constants
Enumerated data types are a special form of integers, with the following constraints:
Only certain pre-determined values are allowed.
Each valid value is assigned a name, which is then normally used instead of integer values when
working with this data type.
Enumerated types, variables, and typedefs, operate similarly to structs:
enum suits { CLUBS, HEARTS, SPADES, DIAMONDS, NOTRUMP } trump;
enum suits ew_bid, ns_bid;
typedef enum Direction{ NORTH, SOUTH, EAST, WEST } Direction; Direction nextMove =
NORTH;
Values may be assigned to specific enum value names.
Any names without assigned values will get one higher than the previous entry.
If the first name does not have an assigned value, it gets the value of zero.
It is even legal to assign the same value to more than one name.
Example:
enum Errors{ NONE=0, // Redundant. The first one would be zero anyway
MINOR1=100, MINOR2, MINOR3, // 100, 101, and 102
MAJOR1=1000, MAJOR2, DIVIDE_BY_ZERO=1000 }; // 1000, 1001, and 1000
again.
Because enumerated data types are integers, they can be used anywhere integers are allowed.
One of the best places in in switch statements:
switch( nextMove ) {
case NORTH: y++;
break;
// etc.
The compiler will allow the use of ordinary integers with enumerated variables, e.g. trump = 2; , but it is bad
practice.
KEYWORDS
Keywords are the reserved words used by the compiler that have standard and fixed (or) predefined
meaning in ‘C’ Language.
Those words cannot be changed by the user and they are the basic building blocks for program
statements.
All the keywords must be written in lower case.
There are 32 keywords in C language. Some of the keywords are,
lOMoARcPSD|188 724 01
Keywords in C Language
auto double int struct do
break else Long switch default
case enum register typedef const
char extern return union if
continue for Signed, void goto
unsigned
float static sizeof short while
Example of precedence
(1 > 2 + 3 && 4)
This expression is equivalent to:
((1 > (2 + 3)) && 4)
e, (2 + 3) executes first resulting into 5
then, first part of the expression (1 > 5) executes resulting into 0 (false) then, (0 && 4) executes resulting
into 0 (false)
Output
0
Associativity of operators
If two operators of same precedence (priority) is present in an expression, Associativity of operators
indicate the order in which they execute.
Example of Associativity
1 == 2 != 3
Here, operators == and != have same precedence.
The Associativity of both == and != is left to right, i.e, the expression on the left is executed first and moves
towards the right.
Thus, the expression above is equivalent to : ((1 == 2) != 3)
i.e, (1 == 2) executes first resulting into 0 (false) then, (0 != 3) executes resulting into 1 (true)
lOMoARcPSD|188 724 01
The table below shows all the operators in C with precedence and Associativity.
What are the various operators available in C? Discuss each one of them with suitable illustrations.
(Nov/Dec 2014) (Or) Explain the different types of operators available in C. (April/May 2015)
(Nov/Dec 2015) (May/June 2016) (Or) Explain various operators in C language in detail. (April / May
2017)[APR/MAY 2018][NOV/DEC 2019] [NOV/DEC 2020][APR/MAY 2021][Nov/Dec2021]
Operators
An operator is a symbol that specifies an operation to be performed on the operands.
Operand
It is a data item on which operators perform operation.
Eg: a+b
Here, a, b Operands + = Operator
Various Types of Operator
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
C allows basic arithmetic operations like addition, subtraction, multiplication and division.
Arithmetic Operators are,
+ , - , * , / , %.
Arithmetic operators are classified as
Unary Arithmetic: It requires only one operand.
Eg: +x, -y
Binary Arithmetic: It requires two operands.
Eg: a+b, a%b, etc.
Integer Arithmetic: It requires both operands are integer values for arithmetic operation.
Eg: a+b a=5, b=2
a+b = 5+2=7
Floating Point Arithmetic: It requires both operands are float type for arithmetic operation.
Eg: a+b, a=6.5 b=3.5
a+b, 6.5+3.5 = 10
Sample Program 1:
#include<stdio.h> // Header File
#include<conio.h>
int a=5, b=10; //Global Declaration
void main( ) /* main is the starting of every c program */
{
int c; //Local Declaration
clrscr( );
printf(“ \n The sum of the two values:”);
c = a+b;
printf(“%d”,c);
getch( );
}
Output: The sum of the two values: 15
lOMoARcPSD|188 724 01
Sample Program 2:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=10, b=4, c;
float d=3, e;
clrscr( );
c = a/b;
printf(" \n Value of a/b is:%d",c);
e = a/d;
printf("\n Value of a/d is:%f",e);
getch( );
}
Output
Value of a/b is: 2
Value of a/d is: 3.333333
Relational Operator
Relational operators are used to compare two or more operands. Operands may be variables,
constants or expression.
If the relation is true, it returns value 1 and if the relation is false, it returns value 0.
Relational operators are, <, >, <=, >=, ==, !=
Example Program
#include<stdio.h> #include<conio.h> void main()
{
int a,b; clrscr();
printf(“\n Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“\n The Result is”);
printf(“%d”, a<b);
printf(“%d”, a>b);
printf(“%d”, a<=b);
printf(“%d”, a>=b);
printf(“%d”, a==b);
printf(“%d”, a!=b); getch();
}
Output
Enter the Values of a and b: 4 2
The Result is
0
1
0
1
0
1
Logical Operators
Logical operators are used to combine the results of two or more conditions.
Operator Meaning Example
&& Logical AND If c=5 and d=2 then,((c==5) &&
(d>5)) Returns false.
|| Logical OR If c=5 and d=2
Then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
lOMoARcPSD|188 724 01
Logical AND – This operator is used where a set of statements are to be executed, if two or more expressions
are true.
Logical OR – This is used, if either of them is true from two or more condition, then set of statements are
executed.
Logical NOT – This operator reverses the value of the expression it operates on.
Sample Program
#include<stdio.h> #include<conio.h> void main()
{
int c1.c2,c3; clrscr();
printf(“Enter the values c1, c2, c3:”);
scanf(“%d%d%d”, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(“c1 is less than c2 and c3”);
if(!(c1<c2))
printf(“\n c1 is greater than c2”);
if((c1<c2)||((c1<c3))
printf(“c1 is less than c2 or c3 both”);
getch();
}
Output
Enter the values c1, c2, c3: 9 6 3
C1 is greater than c2
Assignment Operator
Assignment operators are used to assign a value or an expression or a value of a variable to another
variable.
Syntax: variable=expression (or) value ;
Example : x=10; x=a+b; x=y;
Two types of assignment operator are,
Compound Assignment
Nested Assignment (or) Multiple Assignment
Compound Assignment
Assign a value to a variable in order to assign a new value to a variable after performing a specified
operation.
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Multiple Assignments
It is used to assign a single value or an expression to multiple variables.
Syntax: var1=var2= varn=single variable or expression;
Sample Program
#include<stdio.h>
#include<conio.h>
int b=10;
void main( )
{
int a=3, b=5;
clrscr( );
a+=b; // a= a+b
printf(" \n The sum of the two values:%d",a);
getch( );
lOMoARcPSD|188 724 01
}
Output:
The sum of the two values: 8
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5;
clrscr();
printf(“Post Increment Value a++=%d\n”,a++);
printf(“Pre Increment Value ++a=%d\n”,++a);
printf(“Pre Decrement Value -- a=%d\n”,--a);
printf(“Post Decrement Value a--=%d\n”,a--);
getch();
}
Output:
Post Increment Value a++=5
Pre Increment Value ++a=7
Pre Decrement Value --a=6
Post Decrement Value a--=6
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5, b=2, big;
clrscr();
big=(a>b)?a:b;
printf(“Largest number is %d”,big);
getch();
}
Output: Largest number is 5
Bitwise Operators
It is used to manipulate the data at bit level. It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
lOMoARcPSD|188 724 01
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a, b, c;
clrscr(); a=12; b=25;
c=a&b;
printf(“Bitwise AND=%d”,c);
c=a/b;
printf(“Bitwise OR=%d”,c);
c=a^b;
printf(“Bitwise XOR=%d”,c);
c=~a;
printf(“One’s Complement=%d”,c);
getch();
}
Output:
Bitwise AND=8 Bitwise OR=29 Bitwise XOR=21
One’s Complement= 220
Special Operators
It consists of the following,
Operators Meaning
, Comma Operator
sizeof() Size of Operator
& and * Address Operator / Indirection Operator
. and Member Selection Operator
Comma Operator
It is used to separate the statement elements such as variables, constants or expression, etc.
sizeof() Operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structureetc.
Address Operator / Indirection Operator
Address Operator (&) - This symbol is used to specify the address of the variable.
Indirection Operator (*) - It is used to specify the value of the variable.
Member Selection Operator
These symbols are used to access the elements from a structure.
Sample Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
printf(" \n Size of Int is:%d",sizeof(c));
getch( );
}
Output
Size of Int is: 2
lOMoARcPSD|188 724 01
EXPRESSIONS
An expression represents data item such as variables, constants and are interconnected
withoperators as per the syntax of the language.
Syntax: variable=expression;
An expression is a formula in which operands are linked to each other by the use of operators
to compute a value. An operand can be a function reference, a variable, an array element or a
constant.
Let's see an example:
a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.
For example:
x = 9/2 + a-b;
The entire above line is a statement, not an expression.
The portion after the equal is an expression.
lOMoARcPSD|188 724 01
printf
This offers more structured output than putchar. Its arguments are, in order; a control string,
which controls what gets printed, followed by a list of values to be substituted for entries in the
control string.
Example: int a,b;
printf(“ a = %d,b=%d”,a,b);.
It is also possible to insert numbers into the control string to control field widths for values to
be displayed.
For example %6d would print a decimal value in a field 6 spaces wide, %8.2f would print a
real value in a field
8 spaces wide with room to show 2 decimal places. Display is left justified by default, but
can be right justified
by putting a - before the format information, for example %-6d, a decimal integer right
justified in a 6 space
field.
scanf
scanf allows formatted reading of data from the keyboard.
Like printf it has a control string, followed by the list of items to be read.
However scanf wants to know the address of the items to be read, since it is a function which
will change that value.
Therefore the names of variables are preceded by the & sign.
Character strings are an exception to this.
Since a string is already a character pointer, we give the names of string variables unmodified
by a leading &. Control string entries which match values to be read are preceeded by the
percentage sign in a similar way to their printf equivalents.
Example: int a,b;
scan f(“%d%d”,& a,& b);
lOMoARcPSD|188 724 01
getchar
getchar returns the next character of keyboard input as an int. If there is an error then EOF
(end of file) is returned instead.
It is therefore usual to compare this value against EOF before using it. If the return value is
stored in a char, it will never be equal to EOF, so error conditions will not be handled
correctly.
As an example, here is a program to count the number of characters read until an EOF is
encountered.
EOF can be generated by typing Control - d.
#include <stdio.h>
main()
{ int ch, i = 0;
printf("%d\n", i);
}
putchar
putchar puts its character argument on the standard output (usually the screen).
The following example program converts any typed input into capital letters. To do this it
applies the function to upper from the character conversion library c type .h to each character
in turn.
gets(x);
puts(x);
}
lOMoARcPSD|188 724 01
puts
puts writes a string to the output, and follows it with a new line character.
Example: Program which uses gets and puts to double space typed input.
#include <stdio.h>
main()
{ char line[256]; /* Define string sufficiently large to
store a line of input */
Decision Making
The conditional statements (also known as decision control structures) such as if, if else, switch, etc.
are used for decision-making purposes in C/C++ programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program execution.
1. if in C/C++
The if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block
of statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean values
– if the value is true then it will execute the block of statements below it otherwise not. If we do not
provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the
first immediately below statement to be inside its block.
Flowchart of if Statement
lOMoARcPSD|188 724 01
if (i > 15) {
printf("10 is greater than 15");
}
printf("I am Not in if");
}
Output
I am Not in if
2. if-else in C/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. But what if we want to do something else when the condition is false?
Here comes the C else statement. 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
lOMoARcPSD|188 724 01
// condition is false
}
Example of if-else
int main()
{
int i = 20;
if (i < 15) {
Output
i is greater than 15
The block of code following the else statement is executed as the condition present in
the if statement is false.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean
an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements
within if statements, i.e, we can place an if statement inside another if statement.
int main()
{
lOMoARcPSD|188 724 01
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
return 0;
}
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
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
lOMoARcPSD|188 724 01
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
switch (expression) {
case value1:
statements;
case value2:
lOMoARcPSD|188 724 01
statements;
....
default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any
other data type.
Flowchart of switch
int main()
{
// variable to be used in switch statement
int var = 2;
lOMoARcPSD|188 724 01
return 0;
}
Output
Case 2 is executed
6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else
statement. It is also known as the ternary operator as it works on three operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [flase_statements];
// driver code
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var
// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);
// changing the value of flag
flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);
return 0;
}
Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25
7. Jump Statements in C
These statements are used in C or C++ for the unconditional flow of control throughout the functions
in a program. They support four types of jump statements:
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.
lOMoARcPSD|188 724 01
Example of break
// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
// no of elements
int n = 6;
lOMoARcPSD|188 724 01
// key to be searched
int key = 3;
return 0;
}
Output
Element found at position: 3
B) continue
This loop control statement is just like the break statement. The continue statement is opposite to
that of the break statement, instead of terminating the loop, it forces to execute the next iteration of
the loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration.
When the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Syntax of continue
continue;
Flowchart of Continue
lOMoARcPSD|188 724 01
Example of continue
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
// otherwise print the value of i
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C/C++, it will be local to that if/else block only. You can use
global variables inside the if/else block. If the name of the variable you created in if/else is as same
as any global variable then priority will be given to the `local variable`.
#include <stdio.h>
int main()
{
Output
Before if-else block 0
if block 100
After if block 0
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement can be used to
jump from one point to another within a function.
Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label. Here, a label is a user-defined identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before
the ‘goto label;’ statement in the above syntax.
Output
1 2 3 4 5 6 7 8 9 10
D) return
The return in C or 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.
Flowchart of return
// returns void
// function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}
Output
The sum is 20
Switch Case
This is another form of the multi way decision. It is well structured, but can only be used in certain
cases where;
• Only one variable is tested, all branches must depend on the value of that variable. The
variable must be an integral type. (int, long, short or char).
• Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.
Hopefully an example will clarify things. This is a function which converts an integer into a vague
description. It is useful where we are only concerned in measuring a quantity when it is quite small.
estimate(number)
int number;
/* Estimate a number as none, one, two, several, many */
{ switch(number) {
case 0 :
printf("None\n");
break;
lOMoARcPSD|188 724 01
case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
case 3 :
case 4 :
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}
Each interesting case is listed with a corresponding action. The break statement prevents any further
statements from being executed by leaving the switch. Since case 3 and case 4 have no following
break, they continue on allowing the same action for several values of number.
Both if and switch constructs allow the programmer to make a selection from a number of possible
actions.
Loops
Looping is a way by which we can execute any some set of statements more than one times
continuously .In c there are mainly three types of loops are use :
• while Loop
• do while Loop
• For Loop
While Loop
Loops generally consist of two parts: one or more control expressions which (not surprisingly)
control the execution of the loop, and the body, which is the statement or set of statements which is
executed over and over.
The general syntax of a while loop is
Initialization
while( expression )
{
Statement1
Statement2
Statement3
The most basic loop in C is the while loop. A while loop has one control expression, and executes as
long as that expression is true. This example repeatedly doubles the number 2 (2, 4, 8, 16, ...) and
prints the resulting numbers as long as they are less than 1000:
int x = 2;
{
printf("%d\n", x);
x = x * 2;
}
(Once again, we've used braces {} to enclose the group of statements which are to be executed
together as the body of the loop.)
For Loop
Our second loop, which we've seen at least one example of already, is the for loop. The general
syntax of a while loop is
for( Initialization;expression;Increments/decrements )
{
Statement1
Statement2
Statement3
do
{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0)
C Preprocessors
Preprocessors are programs that process our source code before compilation. There are a number of
steps involved between writing a program and executing a program in C / C++. Let us have a look at
these steps before we actually start learning about Preprocessors.
lOMoARcPSD|188 724 01
You can see the intermediate steps in the above diagram. The source code written by programmers is
first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an
expanded source code file is generated named “program.i”. This expanded file is compiled by the
compiler and an object code file is generated named “program.obj”. Finally, the linker links this
object code file to the object code of the library functions to generate the executable file
“program.exe”.
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. Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember
that the # symbol only provides a path to the preprocessor, and a command such as include is
processed by the preprocessor program. For example, #include will include extra code in your
program. We can place these preprocessor directives anywhere in our program.
1. Macros
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. Let us now understand the macro definition with the help of a
program:
#include <stdio.h>
// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
lOMoARcPSD|188 724 01
printf("%d \n",i);
}
return 0;
}
Output:
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The word
‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a
semi-colon to end.
Macros With Arguments: We can also pass arguments to macros. Macros defined with arguments
work similarly to functions. Let us understand this with a program:
#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;
return 0;
}
Output
Area of rectangle is: 50
Output:
Area of rectangle is: 50
We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it
replaces it with the statement (l*b). Not only this, but the values passed to the macro template
AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to
10*5.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program.
There are two types of files that can be included by the user in the program:
lOMoARcPSD|188 724 01
Header files or Standard files: These 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 file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to
look for the file in the standard directory.
User-defined 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 files. These files can
be included as:
#include"filename"
3. Conditional Compilation
Conditional Compilation directives are 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. This can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute
normally, but if it is not defined, the compiler will simply skip this block of statements.
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These
are:
#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.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off some
features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler.
Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives help us to specify the functions that are needed
to run before program startup (before the control passes to main()) and just before program exit (just
before the control returns from main()).
lOMoARcPSD|188 724 01
#include <stdio.h>
void func1();
void func2();
void func1()
{
printf("Inside func1()\n");
}
void func2()
{
printf("Inside func2()\n");
}
int main()
{
void func1();
void func2();
printf("Inside main()\n");
return 0;
}Output
Inside main()
Output:
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:
Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the
below code for a similar output on GCC compilers.
#include <stdio.h>
void func1();
void func2();
void func1()
{
printf("Inside func1()\n");
lOMoARcPSD|188 724 01
void func2()
{
printf("Inside func2()\n");
}
int main()
{
printf("Inside main()\n");
return 0;
}
Output
Inside func1()
Inside main()
Inside func2()
#pragma warn Directive: This directive is used to hide the warning message which is displayed
during compilation. We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warnings which are raised when a function that is
supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warnings which are raised when a function does not
use the parameters passed to it.
#pragma warn -rch: This directive hides those warnings which are raised when a code is
unreachable. For example, any code written after the return statement in a function is unreachable.
Compilation process in c
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.
The following are the phases through which our program passes before being transformed into an
executable form:
Preprocessor
Compiler
Assembler
Linker
lOMoARcPSD|188 724 01
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'.
lOMoARcPSD|188 724 01
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:
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.
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.
This assembly code is then sent to the assembler, which converts the assembly code into object code.
After the creation of an object code, the linker creates the executable file. The loader will then load
the executable file for the execution.