Unit 1 - Programming Fundamental of C (12th February 2025)
Unit 1 - Programming Fundamental of C (12th February 2025)
1
Introduction of C Programming Language
• C is a general-purpose programming language.
• It is extremely popular, simple, and flexible to use.
• It is a structured programming language that is machine-independent and
extensively used to write various applications, Operating Systems like
Windows, and many other complex programs like Oracle database, Git, Python
interpreter, and more.
• It is said that 'C' is a god's programming language.
• C is a base for the programming. If you know 'C,' you can easily grasp the
knowledge of the other programming languages that uses the concept of 'C'
• It is essential to have a background in computer memory mechanisms because it
is an important aspect when dealing with the C programming language.
• 'C' is a powerful programming language which is strongly associated with the
UNIX operating system.
• Even most of the UNIX operating system is coded in 'C’.
• Initially 'C' programming was limited to the UNIX operating system, but as it
started spreading around the world, it became commercial, and many compilers
were released for cross-platform systems.
• Now 'C' runs under a variety of operating systems and hardware platforms.
• As it started evolving many different versions of the language were released.
• At times it became difficult for the developers to keep up with the latest version
as the systems were running under the older versions.
• To assure that 'C' language will remain standard, American National Standards
Institute (ANSI) defined a commercial standard for 'C' language in 1989. Later,
it was approved by the International Standards Organization (ISO) in 1990. 'C'
programming language is also called as 'ANSI C'.
• Languages such as C++/Java are developed from 'C'. These languages are
widely used in various technologies. Thus, 'C' forms a base for many other
languages that are currently in use.
2
History of C language (in detail read by students)
• The base or father of programming languages is 'ALGOL(Algorithmic
Language).
• It was first introduced in 1960. 'ALGOL' was used on a large basis in European
countries.
• 'ALGOL' introduced the concept of structured programming to the developer
community.
• In 1967, a new computer programming language was announced called as
'BCPL (Basic Combined Programming Language).
• BCPL was designed and developed by Martin Richards, especially for writing
system software. This was the era of programming languages.
• Just after three years, in 1970 a new programming language called 'B' was
introduced by Ken Thompson that contained multiple features of 'BCPL.
• This programming language was created using UNIX operating system at
AT&T and Bell Laboratories. Both the 'BCPL' and 'B' were system
programming languages.
• BCPL is a procedural, imperative and structured programming language.
• In 1972, a great computer scientist Dennis Ritchie created a new programming
language called 'C' at the Bell Laboratories.
• It was created from 'ALGOL', 'BCPL' and 'B' programming languages.
• 'C' programming language contains all the features of these languages and many
more additional concepts that make it unique from other languages.
3
single 'C' program. This structure makes it easy for testing, maintaining and
debugging processes.
• 'C' contains 32 keywords, various data types and a set of powerful built-in
functions that make programming very efficient.
• Another feature of 'C' programming is that it can extend itself. A 'C' program
contains various functions which are part of a library. We can add our features
and functions to the library. We can access and use these functions anytime we
want in our program. This feature makes it simple while working with complex
programming.
• Various compilers are available in the market that can be used for executing
programs written in this language.
• It is a highly portable language which means programs written in 'C' language
can run on other machines. This feature is essential if we wish to use or execute
the code on another computer.
4
Where is C used? Key Applications
1. 'C' language is widely used in embedded systems.
2. It is used for developing system applications.
3. It is widely used for developing desktop applications.
4. Most of the applications by Adobe are developed using 'C' programming
language.
5. It is used for developing browsers and their extensions. Google's Chromium is
built using 'C' programming language.
6. It is used to develop databases. MySQL is the most popular database software
which is built using 'C'.
7. It is used in developing an operating system. Operating systems such as Apple's
OS X, Microsoft's Windows, and Symbian are developed using 'C' language. It
is used for developing desktop as well as mobile phone's operating system.
8. It is used for compiler production.
9. It is widely used in IoT applications.
C has now become a widely used professional language for various reasons −
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
5
C Basic Commands
Following are the basic commands in C programming language:
6
#include <stdio.h>
int main()
{
int mum1, num2, sum; /*variable*/
sum= num1+num2; /8define sum*/
/* my first program in C */
printf("Hello, World! \n");
Hello World
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments
in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message "Hello, World!"
to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
Hello, World!
7
Tokens in C
• A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a
string literal, or a symbol. For example, the following C statement consists of five tokens −
Semicolons
• In a C program, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
Comments
• Comments are like helping text in your C program and they are ignored by the compiler. They start
with /* and terminate with the characters */ as shown below −
/* my first program in */
You cannot have comments within comments and they do not occur within a string or character
literals.
Identifiers
• A C identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).
• C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language.
• Thus, Manpower and manpower are two different identifiers in C. Here are some examples of
acceptable identifiers −
#include<stdio.h>
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
8
Const for Signed Void
Double
About C Programs
A C program can vary from 3 lines to millions of lines and it should be written into
one or more text files with extension ".c"; for example, hello.c. You can
use "vi", "vim" or any other text editor to write your C program into a file.
Environment for C
• If you want to set up your environment for C programming language, you need
the following two software tools available on your computer, (a) Text Editor
and (b) The C Compiler.
Text Editor
• This will be used to type your program. Examples of few a editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
• The name and version of text editors can vary on different operating systems.
For example, Notepad will be used on Windows, and vim or vi can be used on
windows as well as on Linux or UNIX.
• The files you create with your editor are called the source files and they contain
the program source codes. The source files for C programs are typically named
with the extension ".c".
• Before starting your programming, make sure you have one text editor in place
and you have enough experience to write a computer program, save it in a file,
compile it and finally execute it.
The C Compiler
• The source code written in source file is the human readable source for your
program. It needs to be "compiled", into machine language so that your CPU
can actually execute the program as per the instructions given.
• The compiler compiles the source codes into final executable programs. The
most frequently used and free available compiler is the GNU C/C++ compiler,
9
otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems.
Compiler in C
During translation process the Compiler reads the source code (.c) and
checks the syntax errors. If any error, the Compiler generates an error
message, which is usually displayed on a screen. In case of any errors a object
code will not be created by the Compiler. Until all the errors are rectified.
The Compiler usually resides on a disk and not in Random Access Memory
(RAM).
Once the program has been compiled the resulting machine code is saved in
an executable file, which can be run on its own at any time. Once the
executable file (.obj) is generated there is no need of actual source code file.
Execution file (.obj) generation will not affect a source code file (.c).
10
Format Specifiers
Character Char %c
String Char %s
Char name[10];
C Escape Sequences
Example
11
• An Escape sequences always begin with \ (backslash) and is followed
by one character.
• An Escape sequences are mostly used in printf() statement.
\b Backspace 008
\? Question 063
\\ Backslash 092
\0 Null 000
\n Escape Sequence
newline.c
#include <stdio.h>
int main()
{
printf("Hello \nProgrammer ");
return 0;
}
12
C Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double,
bool, or any user-defined object; and variable_list may consist of one or more
identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
13
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable
with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs actual
variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of the
program. You will use the keyword extern to declare a variable at any place. Though
you can declare a variable multiple times in your C program, it can be defined only
once in a file, a function, or a block of code.
14
Example
Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f : 23.333334
15
which means an rvalue may appear on the right-hand side but not on the left-
hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so they may not be assigned and cannot appear on
the left-hand side. Take a look at the following valid and invalid statements −
int g = 20; // valid statement
C - Data Types
Data types in c refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows −
1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and
(b) floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can
only assign certain discrete integer values throughout the program.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
16
The array types and structure types are referred collectively as the aggregate types.
The type of a function specifies the type of the function's return value. We will see the
basic types in the following section, where as other types will be covered in the
upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage
sizes and value ranges −
Char 1 byte
Int 2 or 4 bytes
Short 2 bytes
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
17
printf("CHAR_BIT : %d\n", CHAR_BIT);
printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("INT_MAX : %d\n", INT_MAX);
printf("INT_MIN : %d\n", INT_MIN);
printf("LONG_MAX : %ld\n", (long) LONG_MAX);
printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("SHRT_MAX : %d\n", SHRT_MAX);
printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
CHAR_BIT : 8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535
Floating-Point Types
18
The following table provide the details of standard floating-point types with storage
sizes and value ranges and their precision −
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
return 0;
}
When you compile and execute the above program, it produces the following result
on Linux −
Storage size for float : 4
FLT_MAX : 3.40282e+38
19
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6
The void type specifies that no value is available. It is used in three kinds of
situations −
3 Pointers to void
A pointer of type void * represents the address of an object, but not its
type. For example, a memory allocation function void *malloc( size_t
size ); returns a pointer to void which can be casted to any data type.
• auto
• register
20
• static
• extern
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can
only be used within functions, i.e., local variables.
The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to
the register size (usually one word) and can't have the unary '&' operator applied to it
(as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
21
In C programming, when static is used on a global variable, it causes only one copy
of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −
• Arithmetic Operators
22
• Relational Operators
• Logical Operators
• Bitwise Operators (Not consider for Exam)
• Assignment Operators
• Misc Operators (Not consider for Exam)
Here, we will look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20 then −
Examples
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
Examples A=10; B=20
23
== Checks if the values of two operands (A == B) is not true.
Equal are equal or not. If yes, then the
condition becomes true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Examples
24
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then the condition
becomes true.
Assignment Operators
The following table lists the assignment operators supported by the C language −
Examples
25
%= Modulus AND assignment operator. It
C %= A is equivalent to C = C
takes modulus using two operands and
%A
assigns the result to the left operand.
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Examples
& Returns the address of a &a; returns the actual address of the
variable. variable.
26
(Note : Not for exam)
Operators Precedence in C
27
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
C - Decision Making
Decision making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most
of the programming languages −
C programming language assumes any non-zero and non-null values as true, and if
it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making
statements.
1 if statement
An if statement consists of a boolean expression followed by one or more
statements.
2 if...else statement
An if statement can be followed by an optional else statement, which
28
executes when the Boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else
if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list
of values.
C Control Statements
29
Types of Control statements
• if
• if else
• if-else-if control statement
• switch() case control statement
C if statement
Why if Statement?
All programming languages enable you to make decisions. They enable the
program to follow a certain course of action depending on whether a
particular condition is met. This is what gives programming language their
intelligence.
Syntax if statement
Syntax
if(condition)
{
here goes statements;
.
.
here goes statements;
}
30
if Statement Uses
• Is A bigger than B?
• Is X equal to Y?
• Is M not equal to N?
if Statement Rules
works
if statement C Program
ifstatement.c
31
#include <conio.h>
int main()
{/*OPENING OF MAIN()*/
int age = 18;
if(age > 17){
printf("you are eligible for voting ");
}
printf("\nThis is normal flow ");
return 0;
}/*CLOSING IF MAIN()*/
C if-else Statement
• C uses the keywords if and else to execute a set of statements either logical
condition is true or false.
• If the condition is true, the statements under the keyword if will be
executed.
• If the condition is false, the statements under the keyword else will be
executed.
32
Syntax
if(condition)
{
here go statements....
}
else
{
here go statements....
}
Following flow chart will clearly explain how if else statement works
if-else C Program
ifelsestatement.c
33
{
int age;
printf("Enter your age : ");
scanf("%d",&age);
if(age > 17)
{
printf("\nyou are eligible for voting ");
}
else
{
printf("\nSorry, you are not eligible for voting ");
}
printf("\nThis is normal flow ");
return 0;
}
C if...else Statement
C if Statement
if (test expression)
{
// code
}
The if statement evaluates the test expression inside the parenthesis ().
34
• If the test expression is evaluated to true, statements inside the body of if are
executed.
• If the test expression is evaluated to false, statements inside the body of if are not
executed.
Example 1: if statement
#include <stdio.h>
int main() {
int number;
Output 1
Enter an integer: -2
You entered Number is Negative -2.
35
The if statement is easy.
When the user enters -2, the test expression number<0 is evaluated to true.
Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
When the user enters 5, the test expression number<0 is evaluated to false and the
statement inside the body of if is not executed
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
36
C Nested if Statement (Note : Not for exam)
Why Nested if Statement
The statement that is executed when an if expression is true can be another if,
as can the statement in an else clause. This enables you to express such
convoluted logic as "if age of Lingcoln is greater than age of john "and if age
of Lingcoln is greater than age of renu". Then we decide Lingan is elder of all
Syntax
if(condition)
{
if(condition)
{
here goes statements;
}
}
37
Program Nested if statement
nestedif.c
38
}
Note:
When the first if statement executed, the value 'a' is compared with value 'b',
if the expression is true, then inner if statement executed, the inner expression
compares the value a with value c, if the inner if statement also true, the
compiler will display the output.
C Switch Statement
We use the switch statement to select from multiple choices that are
identified by a set of fixed values for a given expression. The expression that
selects a choice must produce a result of an integer type other than long, or a
string, or a value of an enumeration type. Thus, the expression that controls
a switch statement can result in a value of type char, int, short, long, string,
or an enumeation constant.
C Switch Syntax
Syntax
switch ( variable )
{
case value1:
39
statement;
break;
case value2:
statement;
break;
default:
statement;
}
Let's take a look at the switch statement in action. In the following program
we will greet either dad or mom or yourself.
switch.c
#include <stdio.h>
int main()
{
int choice;
printf("Press 1 to greet your dad\n ");
printf("Press 2 to greet your mom\n ");
printf("Press 3 to greet yourself\n ");
scanf("%d ",&choice);
switch (choice)
{
case 1:
printf("\nHello dad,How are you? ");
break;
case 2:
40
printf("\nHello mom,How are you? ");
break;
case 3:
printf("\nHello awesome,How are you? ");
break;
default:
printf("\nInvalid choice ");
}
return 0;
}
Note:
The above program offers three choices to a user. A choice(number) entered
by the user is stored in a variable choice. In switch() statement the value is
checked with all the case constants. The matched case statement is executed
in which the line is printed according to the user's choice. If user's choice
doesn't match with any case statement, then a statement followed by default
will be executed.
If we do not use break, all statements after the matching label are executed.
By the way, the default clause inside the switch statement is optional.
41
switch Statement Flowchart
int main() {
char operator;
int n1, n2;
42
switch(operator)
{
case '+':
printf("%d + %d = %d",n1, n2, n1+n2);
break;
case '-':
printf("%d - %d = %d",n1, n2, n1-n2);
break;
case '*':
printf("%d * %d = %d",n1, n2, n1*n2);
break;
case '/':
printf("%d / %d = %f",n1, n2, n1/n2);
break;
return 0;
}
Output
43
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement.
C Break Statement
C Break Statement
• The word break is a keyword that terminates the execution of the loop or the
control statement and the control is transferred to the statement immediately
following it.
• The break statement is mostly used in switch control statement.
44
The following flowchart will clearly demonstrate how break statement works
break.c
45
break;
}
printf("%d ", a);
}
return 0;
}
• 123
Note:
C Continue Statement
The continue statement enables you to skip to the next iteration in the loop
containing the continue statement. The labeled continue statement enables
you to skip to the next iteration in an outer loop enclosing the labeled
continue that is identified by the label. The labeled loop need not be the loop
immediately enclosing the labeled continue.
C Continue Statement
The following flowchart will help you to understand how continue statement
works
46
Continue Statement Program
continue.c
• 1235
47
Note:
When the variable reaches the value 4, the loop skips the statements within a
block, only for that particular iteration.
C goto statement
C goto Syntax
Syntax
goto Label;
.
.
Label:
{
statement n;
}
The following flowchart will clearly demonstrate, how goto statement works
48
goto statement Program
Let's take a look at the goto statement in action. In the following program we
will print whether the number is positive or negative using goto statement
goto.c
#include <stdio.h>
int main()
{
int num;
printf("Enter a positive or negative integer number:\n ");
scanf("%d",&num);
if(num >= 0)
goto pos;
else
goto neg;
pos:
{
printf("%d is a positive number",num);
return 0;
}
neg:
{
printf("%d is a negative number",num);
return 0;
}
}
49
• Enter a positive or negative integer number:
• 2
• 2 is a positive number
Note:
In this program, the user entered number is checked for positive or negative
number. If the user entered number is positive, the control is passes to pos :
by goto statement. If the user entered number is negative, the control is passes
to neg : by goto statement.
Control Loops In C
What Is Loop
C - Loops
You may encounter situations, when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement
in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the
programming languages −
50
C programming language provides the following types of loops to handle looping
requirements.
In programming, a loop is used to repeat a block of code until the specified condition
is met.
1 while loop
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
3 do...while loop
It is more like a while statement, except that it tests the condition at the
end of the loop body.
4 nested loops
You can use one or more loops inside any other while, for, or do..while
loop.
for Loop
51
How for loop works?
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body
of for loop are executed, and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
To learn more about test expression (when the test expression is evaluated to true and
false), check out relational and logical operators.
52
Example 1: for loop
int main() {
int i;
Output
1 2 3 4 5 6 7 8 9 10
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body
of for loop is executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test
expression is evaluated to true, and the body of for loop is executed. This will
print 2 (value of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is
evaluated. This process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
53
scanf("%d", &num);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
The value entered by the user is stored in the variable num. Suppose, the user entered
10.
The count is initialized to 1 and the test expression is evaluated. Since the test
expression count<=num (1 less than or equal to 10) is true, the body of for loop is
executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and the count will equal to 2. Again,
the test expression is evaluated. Since 2 is also less than 10, the test expression is
evaluated to true and the body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the loop
terminates.
54
(Note : Not for exam)
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the
'for' loop are required, you can make an endless loop by leaving the conditional
expression empty.
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the
for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
while loop
The syntax of the while loop is:
while (testExpression)
{
// the body of the loop
}
• The while loop evaluates the test expression inside the parenthesis ().
• If the test expression is true, statements inside the body of while loop are executed.
Then, the test expression is evaluated again.
55
• The process goes on until the test expression is evaluated to false.
• If the test expression is false, the loop terminates (ends).
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i)
++i;
}
return 0;
}
Output
56
1
2
3
4
5
do...while loop
The do..while loop is similar to the while loop with one important difference. The
body of do...while loop is executed at least once. Only then, the test expression is
evaluated.
The syntax of the do...while loop is:
do
{
// the body of the loop
}
while (testExpression);
57
Flowchart of do...while Loop
#include <stdio.h>
int main()
{
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
Output
58
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
In the above example, son's age is 18 whereas father's age is 40. But we need the
younger age so we make use of conditional operator to extract least age.
The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to
replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
• Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the
entire ? expression.
• If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.
59
Syntax
Note:
Here the code looks more verbose as we make use of if else statement.
60