0% found this document useful (0 votes)
3 views

Unit 1 - Programming Fundamental of C (12th February 2025)

Uploaded by

Tanishqa Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 1 - Programming Fundamental of C (12th February 2025)

Uploaded by

Tanishqa Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

IM–210B PROGRAMMING USING C++

Study material of Unit – I


Syllabus of Unit-1
Programming fundamentals:-Introduction to C. Variables. Types. Constants. Declarations.
Expressions. Assignments. Operators. Statements. Iterative Instructions.

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.

Why learn C Language?


• 'C' is a base language for many programming languages. So, learning 'C' as the
main language will play an important role while studying other programming
languages. It shares the same concepts such as data types, operators, control
statements and many more. 'C' can be used widely in various applications. It is a
simple language and provides faster execution. There are many jobs available
for a 'C' developer in the current market.
• 'C' is a structured programming language in which program is divided into
various modules. Each module can be written separately and together it forms a

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.

How C Programming Language Works?


• C is a compiled language.
• A compiler is a special tool that compiles the program and converts it into the
object file which is machine readable. After the compilation process, the linker
will combine different object files and creates a single executable file to run the
program. The following diagram shows the execution of a 'C' program
• Nowadays, various compilers are available online, and you can use any of those
compilers. The functionality will never differ and most of the compilers will
provide the features required to execute both 'C' and 'C++' programs.
Following is the list of popular compilers available online:
✓ Clang compiler
✓ MinGW compiler (Minimalist GNU for Windows)
✓ Portable 'C' compiler
✓ Turbo C

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:

C Basic commands Explanation

#include <stdio.h> This command includes standard input output header


file(stdio.h) from the C library before compiling a C
program

int main() It is the main function from where C program execution


begins.

{ Indicates the beginning of the main function.

/*_some_comments_*/ Whatever written inside this command “/* */” inside a


C program, it will not be considered for compilation
and execution.

printf(“Hello_World! “); This command prints the output on the screen.

getch(); This command is used for any character input from


keyboard.

return 0; This command is used to terminate a C program (main


function) and it returns 0.

} It is used to indicate the end of the main function.

C program basically consists of the following parts −


✓ Pre-processor Commands
✓ Functions
✓ Variables
✓ Statements & Expressions
✓ Comments

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");

printf(“this is MBA(MS)-II Semester class”);


return 0;
}
Output of program
Output

Hello World

this is MBA(MS)-II Semester class

Let us take a look at the various parts of the above program −


• The first line of the program #include <stdio.h> is a pre-processor command, which tells a C
compiler to include stdio.h file before going to actual compilation.

• 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.

Compile and Execute C Program in Turbo C


Let us see how to save the source code in a file, and how to compile and run it. Following are the simple
steps −

• Open a text editor and add the above-mentioned code.


• Save the file as hello.c
• Compile the program.
• If there are no errors in your code than excute/run the program
• You will see the output "Hello World" printed on the screen.

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 −

Printf(“Hello, World! \n”);

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 −

name, NAME, _temp, product1, abc, a_123,

#include<stdio.h>

int ABC, abc, Abc, aBc, abC;

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.

Auto else Long Switch

Break enum Register Typedef

Case extern Return Union

Char float Short Unsigned

8
Const for Signed Void

Continue goto Sizeof Volatile

Default if Static While

Do int Struct _Packed

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.

What Compiler Means?

Complier is nothing more than translating one thing to another to do some


useful work.

Compiler in C

In C, Compiler is a kind of translator that translate source code (.c) into


machine code (.obj). This machine code is used by your computer's
microprocessor to do the work as per the command written in source code by
the programmer.

Error In Source Code

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.

Where Compiler Resides

The Compiler usually resides on a disk and not in Random Access Memory
(RAM).

Does Source Code Actually Needed?

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).

How Compiler Works

The Compiler replaces all statements with a series of machine language


instruction. A single statement is a line terminated by semicolon. The
following diagram clearly demonstrate how compiler translate source code to
a machine code.

10
Format Specifiers

Format Specifiers in Programming language tells us which type of data to


store and which type of data to print or to output.

Data Type Keyword Format Specifier

Character Char %c

signed integer Int %d or %i of %l

unsigned integer unsigned int %u or %lu

long double long double %ld

String Char %s
Char name[10];

floating point Float %f

double floating point Double %lf

C Escape Sequences

What Escape Sequences Means?

In C Programming, the word escape sequences means to escape the character


from the sequences of words and give special meaning to the escaped
character.

Example

Let us consider the following word "hello\nworld". Clearly, n is the character


which escapes from the sequences of word, helloworld and a special meaning
is given to n i.e) new line.

Escape Sequences Facts

• An Escape sequences are non-printing characters.


• An Escape sequences are certain characters associated
with \ (backslash).

11
• An Escape sequences always begin with \ (backslash) and is followed
by one character.
• An Escape sequences are mostly used in printf() statement.

Escape Sequences Table

There are 12 escape sequences in C Programming. They are

Escape Sequence Use ASCII Value

\n New Line 010

\t Horizontal tab 009

\b Backspace 008

\r Carriage Return 013

\a Alert Bell 007

\' Single quote 039

\" Double quote 034

\? Question 063

\\ Backslash 092

\f Form feed 012

\v Vertical tab 011

\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 −

Sr.No. Type & Description

1 Char : Typically a single octet(one byte). It is an integer type.

2 Int : The most natural size of integer for the machine.

3 Float : A single-precision floating point value.

4 Double : A double-precision floating point value.

5 Void : Represents the absence of type.

C programming language also allows to define various other types of variables,


which we will cover in subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc. For this chapter, let us study only 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

Lvalues and Rvalues in C

There are two kinds of expressions in C −


• lvalue − Expressions that refer to a memory location are called "lvalue"
expressions. An lvalue may appear as either the left-hand or right-hand side of
an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it

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

10 = 20; // invalid statement; would generate compile-time error

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 −

Sr.No. Types & Description

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.

3 The type void


The type specifier void indicates that no value is available.

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 −

Type Storage size

Char 1 byte

unsigned char 1 byte

signed char 1 byte

Int 2 or 4 bytes

unsigned int 2 or 4 bytes

Short 2 bytes

unsigned short 2 bytes

Long 8 bytes or (4bytes for 32 bit OS)

unsigned long 8 bytes

(Note : Not for exam)


To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object
or type in bytes. Given below is an example to get the size of various type on a
machine using different constant defined in limits.h header file −

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

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 −

Type Storage size Precision

Float 4 byte 6 decimal places

Double 8 byte 15 decimal places

long double 10 byte 19 decimal places


The header file float.h defines macros that allow you to use these values and other details
about the binary representation of real numbers in your programs.

(Note : Not for exam)


The following example prints the storage space taken by a float type and its range values −

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

printf("Storage size for float : %d \n", sizeof(float));


printf("FLT_MAX : %g\n", (float) FLT_MAX);
printf("FLT_MIN : %g\n", (float) FLT_MIN);
printf("-FLT_MAX : %g\n", (float) -FLT_MAX);
printf("-FLT_MIN : %g\n", (float) -FLT_MIN);
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
printf("Precision value: %d\n", FLT_DIG );

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

The void type specifies that no value is available. It is used in three kinds of
situations −

Sr.No. Types & Description

1 Function returns as void


There are various functions in C which do not return any value or you
can say they return void. A function with no return value has the return
type as void. For example, void exit (int status);

2 Function arguments as void


There are various functions in C which do not accept any parameter. A
function with no parameter can accept a void. For example, int
rand(void);

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.

(Note : Not for exam)


C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program −

• auto
• register

20
• static
• extern

The auto Storage Class

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

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

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 ) {

static int i = 5; /* local static variable */


i++;

printf("i is %d and count is %d\n", i, count);


}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

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

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an B%A=0


integer division.

++ Increment operator increases the integer value by A++ = 11


one.
A=A+1

-- Decrement operator decreases the integer value by A-- = 9


one.
A=A-1

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

Operator Description Example

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.

!= Checks if the values of two operands (A != B) is true.


Not are equal or not. If the values are not
Equal equal, then the condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand.
If yes, then the condition becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand. If
yes, then the condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand. If yes, then the condition
becomes true.

<= Checks if the value of left operand is (A <= B) is true.


less than or equal to the value of right
operand. 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

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then the condition
becomes true.

24
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then the condition
becomes true.

! Called Logical NOT Operator. It is used to !(A && B) is true.


reverse the logical state of its operand. If a
condition is true, then Logical NOT operator
will make it false.

Assignment Operators

The following table lists the assignment operators supported by the C language −
Examples

Operator Description Example

= Simple assignment operator. Assigns


C = A + B will assign the
values from right side operands to left
value of A + B to C
side operand

+= Add AND assignment operator. It


adds the right operand to the left C += A is equivalent to C = C
operand and assign the result to the +A
left operand.

-= Subtract AND assignment operator. It


subtracts the right operand from the C -= A is equivalent to C = C
left operand and assigns the result to –A
the left operand.

*= Multiply AND assignment operator. It


multiplies the right operand with the C *= A is equivalent to C = C
left operand and assigns the result to *A
the left operand.

/= Divide AND assignment operator. It


divides the left operand with the right C /= A is equivalent to C = C /
operand and assigns the result to the A
left operand.

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.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C <<


2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >>


2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator.

|= Bitwise inclusive OR and assignment C |= 2 is same as C = C | 2


operator.

Misc Operators ↦ sizeof & ternary

Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Examples

Operator Description Example

sizeof() Returns the size of a sizeof(a), where a is integer, will return 4.


variable.

& Returns the address of a &a; returns the actual address of the
variable. variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X :


Conditional Expression.
otherwise value Y

26
(Note : Not for exam)
Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides


how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the
addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

27
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

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.

Sr.No. Statement & Description

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.

5 nested switch statements


You can use one switch statement inside another switch statement(s).

C Control Statements

C Programs that we encountered up to now were executed in the same order


which they appeared in it. In practical applications, there is numerous
situations where we have to neglect some parts of program codes. For this
purpose, C Programming uses the control statements to control the flow of a
program. If the condition is satisfied the code followed by that condition will
execute. If not simply that the code will be neglected by the compiler.

Flowchart 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.

C if Syntax And Definition

• C uses the keyword if to execute a set of statements when logical condition is


true.
• When the logical condition is false, the compiler simply skips the statement
within the block.
• The "if" statement is also known as one way decision statement.

Syntax if statement

Syntax

if(condition)
{
here goes statements;
.
.
here goes statements;
}

30
if Statement Uses

if statements are commonly used in following scenarios

• Is A bigger than B?
• Is X equal to Y?
• Is M not equal to N?

if Statement Rules

• The expression (or) condition is always enclosed within pair of parenthesis.


e.g.) if ( a > b )
• The if statement should not be terminated with a semicolon. If it happens, the
block of statements will not execute even the condition is true.
• The statements following the if condition is normally enclosed between 2
braces (in curly braces).

if statement Flow Chart

Following flow chart will clearly explain how if statement

works

if statement C Program

ifstatement.c

#include <stdio.h> //header file section

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()*/

• you are eligible for voting


• This is normal flow

C if-else Statement

Why if-else Statement?

As We've seen, the if statement allows us to run a block of code if an


expression evaluates to true. If the expression evalutes to false, the code is
skipped. Thus we can enhance this decision-making process by adding
an else statement to an if construction. This lets us run one block of code if an
expression is true, and a different block of code if the expression is false.

C if-else Syntax And Definition

• 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.

Syntax if-else statement

32
Syntax

if(condition)
{
here go statements....
}
else
{
here go statements....
}

if else Statement Flow Chart

Following flow chart will clearly explain how if else statement works

if-else C Program

ifelsestatement.c

#include <stdio.h> //header file section


int main()

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;
}

• Enter your age : 16


• Sorry, you are not eligible for voting
• This is normal flow

C if...else Statement

C if Statement

The syntax of the if statement in C programming is:

if (test expression)
{
// code
}

How if statement works?

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

// Program to display a number if it is negative

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// true if number is less than 0


if (number < 0) {
printf("Your entered Number is Negative %d \n", number);
}

printf("The if statement is easy.");


return 0;
}

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

Example 2: if...else statement

// Check whether an integer is odd or even

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",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 and Definition Nested if statement

• In C programming, control statements like as if can be nested, that means we


can write one within another.
• If outer if statement fails, then the compiler skips the entire block
irrespective of their inner if statement.

Syntax nested if statement

Syntax

if(condition)
{
if(condition)
{
here goes statements;
}
}

Nested if Statement Flowchart

The following flowchart will clearly demonstrate how nested if statement


works

37
Program Nested if statement

Let us write a C program using Nested if statement

nestedif.c

#include <stdio.h> //header file section


int main()
{
int a = 47, b = 25, c = 3;
if (a > b)
{
if (a > c)
{
printf("The value a is greater than b and c ");
}
}
printf("\nThis is normal flow ");
return 0;

38
}

• The value a is greater than b and c


• This is normal flow

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 And Facts


• A switch statement is an alternative to if-else-if statement.
• The switch statement has four important elements.
• The test expression
• The case statements
• The break statements
• The default statement

C Switch Syntax

Syntax Switch Statement

Syntax

switch ( variable )
{
case value1:

39
statement;
break;
case value2:
statement;
break;
default:
statement;
}

C Switch Statement Program

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;
}

• Press 1 to greet your dad


• Press 2 to greet your mom
• Press 3 to greet yourself
• 1
• Hello dad,How are you?

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.

How does the switch statement work?


The expression is evaluated once and compared with the values of each case label.
• If there is a match, the corresponding statements after the matching label are executed.
For example, if the value of the expression is equal to constant2, statements after case
constant2: are executed until break is encountered.
• If there is no match, the default statements are 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

Example: Simple Calculator

// Program to create a simple calculator


#include <stdio.h>

int main() {
char operator;
int n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%d %d",&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;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

return 0;
}

Output

Enter an operator (+, -, *,): -


Enter two operands: 32
12
32 - 12 = 20
The - operator entered by the user is stored in the operator variable. And, two
operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.

Since the operator is -, the control of the program jumps to

printf("%d - %d = %d", n1, n2, n1-n2);

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.

Sr.No. Control Statement & Description

1 break statement

Terminates the loop or switch statement and transfers execution to the


statement immediately following the loop or switch.

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

Why Break Statement?

Though break statement comes under decision-making statement, its most


oftenly using in looping. One can use the break statement to break out from a
loop or switch statement. When break is executed within a loop, the loop ends
immediately, and execution continues with the first statement following the
loop.

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.

Break Statement Flowchart

44
The following flowchart will clearly demonstrate how break statement works

Break Statement Program

Let us write a C program to demonstrate break statement.

break.c

#include <stdio.h> //header file section


int main()
{
int a;

for(a = 1;a <= 5;a++)


{
if(a == 4)
{

45
break;
}
printf("%d ", a);
}
return 0;
}

• 123

Note:

The loop will be terminated immediately, when a variable a = 4 is


encountered.

C Continue Statement

Why 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 continue statement is exactly opposite to the break statement.


• The loop does not terminate when a continue statement is encountered.
• Instead, the continue statement skips that particular iteration.
• The continue statement is also called as bypass statement.

Continue Statement Flowchart

The following flowchart will help you to understand how continue statement
works

46
Continue Statement Program

continue.c

#include <stdio.h> //header file section


int main()
{
int a;
for(a = 1;a <= 5; a++)
{
if(a == 4)
{
continue;
}
printf("%d", a);
}
return 0;
}

• 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

goto statement in c sometimes called as goto operation in other languages


like php.

Why goto Statement

C programming introduces a goto statement by which you can jump directly


to a line of code within the same file.

Syntax And Facts

• The goto statement does not require any condition.


• The goto statement simply passes control anywhere in a program
without testing any condition.

C goto Syntax

Syntax goto Statement

Syntax

goto Label;
.
.
Label:
{
statement n;
}

goto statement Flowchart

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

A loop enables a programmer to execute a statement or block of statement


repeatedly. The need to repeat a block of code arise in almost every program.

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.

Sr.No. Loop Type & Description

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

The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


(i=1; i<10; ++i)
{
// statements inside the body of 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.

for loop Flowchart

Working of for loop

52
Example 1: for loop

// Print numbers from 1 to 10


#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}

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.

Example 2: for loop


// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");

53
scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

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.

Then, the value of sum is printed on the screen.

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
}

How while loop works?

• 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).

Flowchart of while loop

Working of while loop


Example 1: while loop

// Print numbers from 1 to 5

#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

Here, we have initialized i to 1.


1. When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is
executed. This prints 1 on the screen and the value of i is increased to 2.
2. Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is
executed again. This prints 2 on the screen and the value of i is increased to 3.
3. This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be
false and the loop terminates.

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);

How do...while loop works?


• The body of do...while loop is executed once. Only then, the test expression is
evaluated.
• If the test expression is true, the body of the loop is executed again and the test
expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop ends.

57
Flowchart of do...while Loop

Working of do...while loop


Example 2: do...while loop

// Program to add numbers until the user enters zero

#include <stdio.h>
int main()
{
double number, sum = 0;

// the body of the loop is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number; sum=sum+number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a number: 1.5

58
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

(Note : Not for exam)


C Conditional or Ternary Operator

The conditional operator is sometimes called a ternary operator because it


involves three operands. It is best understood by considering the following example
younger = son < father ? 18 : 40;

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.

Syntax of Conditional Operator in C

• The conditional operator contains a condition followed by two statements or


values.
• If the condition is true the first statement is executed, otherwise the second
statement or value.

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

condition ? (value 1) : (value 2)

How Conditional Operator Works

Conditional operator performs nothing more special. It is the abstraction of if


else statement. Consider the following example how Condtional
Operator works
younger = true ? 18 : 40;

If the logical expression resulted true, 18 will be stored in a variable younger.


younger = false ? 18 : 40;

If the logical expression resulted true, 40 will be stored in a variable younger.

Program without Conditional Operator

Here we are to find the least age and store it in a


variable younger_age without using Conditional operator.

#include <stdio.h> //header file section


int main() //main section
{
int son = 18;
int father = 40;
int younger_age;
if(son < father)
younger_age = son;
else
younger_age = father;
printf("%d is the younger age", younger_age);
return 0;
}

• 18 is the younger age

Note:
Here the code looks more verbose as we make use of if else statement.

60

You might also like