[go: up one dir, main page]

0% found this document useful (0 votes)
10 views157 pages

Wa0005

The document provides comprehensive notes on the basics of C programming, covering the structure of a C program, data types, and keywords. It outlines the essential sections of a C program, such as documentation, preprocessor, main function, and subprograms, along with examples for each. Additionally, it details various data types, their sizes, ranges, and format specifiers, as well as a list of reserved keywords in C.

Uploaded by

iamjeeva.aj
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)
10 views157 pages

Wa0005

The document provides comprehensive notes on the basics of C programming, covering the structure of a C program, data types, and keywords. It outlines the essential sections of a C program, such as documentation, preprocessor, main function, and subprograms, along with examples for each. Additionally, it details various data types, their sizes, ranges, and format specifiers, as well as a list of reserved keywords in C.

Uploaded by

iamjeeva.aj
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/ 157

C Programming Notes

UNIT I
SYLLABUS:
Basics of C, I/O, Branching and Loops:
Structure of a C Program – Data types – Keywords - Variables – Type Qualifiers - Constants –
Operators–expressions and precedence- Console I/O– Unformatted and Formatted Console I/O
-Conditional Branching and Loops-Writing and evaluation of conditionals and consequent
branching

NOTES:
1. STRUCTURE OF A C PROGRAM:

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program.

Sections of the C Program


There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:

1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation

This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:

// description, name of the program, programmer name, date, time etc.

Or

/*

description, name of the program, programmer name, date, time etc.

*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.

2. Preprocessor Section

All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.

Example:

#include<stdio.h>

#include<math.h>

3. Definition

The #define preprocessor is used to create a constant throughout the program. Whenever this
name is encountered by the compiler, it is replaced by the actual piece of defined code.

Example:

#define long long ll

4. Global Declaration

The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.

Example:

int num = 18;

5. Main() Function

Every C program must have a main function. The main() function of the program is written in this
section. Operations like declaration and execution are performed inside the curly braces of the
main program. The return type of the main() function can be int as well as void too. void() main
tells the compiler that the program will not return any value. The int main() tells the compiler that
the program will return an integer value.

Example:

void main()
or

int main()

6. Sub Programs

User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.

Example:

int sum(int x, int y)

return x+y;

Structure of C Program with example


Example: Below C program to find the sum of 2 numbers:
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

Output

Sum: 75

2. DATA TYPES:

Each variable in C has an associated data type. It specifies the type of data that the variable
can store like integer, character, floating, double, etc. Each data type requires different amounts
of memory and has some specific operations which can be performed over it. The data type is a
collection of data with values having fixed values, meaning as well as its characteristics.

The data types in C can be classified as follows:

Types Description
Primitive data types are the most basic data types that are used for
PrimitiveData representing simple values such as integers, float, characters, etc.
Types

User Defined The user-defined data types are defined by the user himself.
Data Types

Derived Types The data types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types.

DATA RANGE:

Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.

Data Type Size (bytes) Range Format Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu


unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long 8 0 to %llu


int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Note: The long, short, signed and unsigned are datatype modifier that can be
used with some primitive data types to change the size or length of the datatype.

The following are some main primitive data types in C:

Integer Data Type


The integer datatype in C is used to store the integer numbers(any number including positive,
negative and zero without decimal part). Octal values, hexadecimal values, and decimal values
can be stored in int data type in C.

● Range: -2,147,483,648 to 2,147,483,647


● Size: 4 bytes
● Format Specifier: %d

Syntax of Integer

We use int keyword to declare the integer variable:

int var_name;

The integer data type can also be used as

1. unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768
to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.

Note: The size of an integer data type is compiler-dependent. We can use sizeof
operator to check the actual size of any data type.

Example of int
// C program to print Integer data types.

#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

printf("Integer value with positive data:


%d\n", a);
printf("Integer value with negative data:
%d\n", b);
printf("Integer value with an unsigned int
data: %u\n",
c);
printf("Integer value with an long int
data: %ld", d);

return 0;
}
Output

Integer value with positive data: 9

Integer value with negative data: -9

Integer value with an unsigned int data: 89

Integer value with an long int data: 99998


Character Data Type
Character data type allows its variable to store only a single character. The size of the character
is 1 byte. It is the most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.

● Range: (-128 to 127) or (0 to 255)


● Size: 1 byte
● Format Specifier: %c

Syntax of char

The char keyword is used to declare the variable of character type:

char var_name;

Example of char
// C program to print Integer data types.

#include <stdio.h>

int main()
{
char a = 'a';
char c;

printf("Value of a: %c\n", a);

a++;
printf("Value of a after increment is:
%c\n", a);

// c is assigned ASCII values


// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf("Value of c: %c", c);

return 0;
}
Output

Value of a: a

Value of a after increment is: b

Value of c: c

Float Data Type


In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.

● Range: 1.2E-38 to 3.4E+38


● Size: 4 bytes
● Format Specifier: %f

Syntax of float

The float keyword is used to declare the variable as a floating point:

float var_name;

Example of Float
// C Program to demonstrate use

// of Floating types

#include <stdio.h>
int main()

float a = 9.0f;

float b = 2.5f;

// 2x10^-4

float c = 2E-4f;

printf("%f\n", a);

printf("%f\n", b);

printf("%f", c);

return 0;

Output

9.000000

2.500000

0.000200

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point values)
with double precision. It is used to define numeric values which hold numbers with decimal
values in C.
The double data type is basically a precision sort of data type that is capable of holding 64 bits
of decimal numbers or floating points. Since double has more precision as compared to that
float then it is much more obvious that it occupies twice the memory occupied by the
floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal
point.

● Range: 1.7E-308 to 1.7E+308


● Size: 8 bytes
● Format Specifier: %lf

Syntax of Double

The variable can be declared as double precision floating point using the double keyword:

double var_name;

Example of Double
// C Program to
demonstrate

// use of double data


type
#include <stdio.h>

int main()
{
double a =
123123123.00;
double b = 12.293123;
double c =
2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}
Output

123123123.000000

12.293123

2312312312.123123

Void Data Type


The void data type in C is used to specify that no value is present. It does not provide a result
value to its caller. It has no values and no operations. It is used to represent nothing. Void is
used in multiple ways as function return type, function arguments as void, and pointers to void.

Syntax:
// function return type void

void exit(int check);

// Function without any parameter can accept void.

int print(void);

// memory allocation function which

// returns a pointer to void.

void *malloc (size_t size);

Example of Void
// C program to
demonstrate

// use of void
pointers
#include <stdio.h>

int main()
{
int val = 30;
void* ptr = &val;
printf("%d",
*(int*)ptr);
return 0;
}
Output

30

Size of Data Types in C


The size of the data types in C is dependent on the size of the architecture, so we cannot define
the universal size of the data types. For that, the C language provides the sizeof() operator to
check the size of the data types.

Example
// C Program to print size of

// different data type in C


#include <stdio.h>

int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n",


size_of_int);
printf("The size of char data type : %d\n",
size_of_char);
printf("The size of float data type :
%d\n",
size_of_float);
printf("The size of double data type : %d",
size_of_double);

return 0;
}
Output

The size of int data type : 4

The size of char data type : 1

The size of float data type : 4

The size of double data type : 8

3. KEYWORDS

What are Keywords?


Keywords are predefined or reserved words that have special meanings to the compiler. These
are part of the syntax and cannot be used as identifiers in the program. A list of keywords in C
or reserved words in the C programming language are mentioned below:
auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigne void volatile while


d

auto
auto is the default storage class variable that is declared inside a function or a block. auto
variables can only be accessed within the function/block they are declared. By default, auto
variables have garbage values assigned to them. Automatic variables are also called local
variables as they are local to a function.

auto int num;

Here num is the variable of the storage class auto and its type is int. Below is the C program to
demonstrate the auto keyword:

// C program to
demonstrate

// auto keyword
#include <stdio.h>

int printvalue()
{
auto int a = 10;
printf("%d", a);
}

// Driver code
int main()
{
printvalue();
return 0;
}
Output

10
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a loop or a
switch statement. The switch statement skips to the next iteration of the loop. Below is the C
program to demonstrate break and continue in C:

// C program to show
use

// of break and
continue
#include <stdio.h>

// Driver code
int main()
{
for (int i = 1; i <=
10; i++)
{
if (i == 2)
{
continue;
}
if (i == 6)
{
break;
}
printf("%d ", i);
}
return 0;
}
Output

1345
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a single
variable i.e, switch variable it allows us to execute multiple operations for different possible
values of a single variable.

switch(Expression)

case '1': // operation 1

break;

case:'2': // operation 2

break;

default: // default statement to be executed

Below is the C program to demonstrate the switch case statement:

// C program to
demonstrate

// switch case statement


#include <stdio.h>

// Driver code
int main() {
int i = 4;
switch (i) {
case 1:
printf("Case
1\n");break;
case 2:
printf("Case
2\n");break;
case 3:
printf("Case
3\n");break;
case 4:
printf("Case
4\n");break;
default:

printf("Default\n");break
;
}
}
Output

Case 4

Note: it is best to add a break statement after every case so that switch statement doesn’t
continue checking the remaining cases.

Output

Case 4

Default

char
char keyword in C is used to declare a character variable in the C programming language.

char x = 'D';

Below is the C program to demonstrate the char keyword:


// C program to
demonstrate

// char keyword
#include <stdio.h>

// Driver code
int main() {
char c = 'a';
printf("%c", c);
return 0;
}
Output

const
The const keyword defines a variable who’s value cannot be changed.

const int num = 10;

Below is the C program to demonstrate the const keyword:

// C program to
demonstrate

// const keyword
#include <stdio.h>

// Driver code
int main() {
const int a = 11;
a = a + 2;
printf("%d", a);
return 0;
}
This code will produce an error because the integer a was defined as a constant and it’s value
was later on changed.
Output:

error: assignment of read-only variable 'a'

a = a + 2;

do
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes
once, and then checks it’s condition to see if it should continue through the loop. After the first
iteration, it will continue to execute the code while the condition is true.

Below is the C program to demonstrate a do-while loop.

// C program to
demonstrate

// do-while keyword
#include <stdio.h>

// Driver code
int main()
{
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);

return 0;
}
Output

12345

double and float


The doubles and floats are datatypes used to declare decimal type variables. They are similar,
but doubles have 15 decimal digits, and floats only have 7.

Example:

float marks = 97.5;

double num;

Below is the C program to demonstrate double float keyword:

// C program to
demonstrate

// double float keyword


#include <stdio.h>

// Driver code
int main() {
float f = 0.3;
double d = 10.67;
printf("Float value:
%f\n", f);
printf("Double value:
%f\n", d);
return 0;
}
Output

Float value: 0.300000

Double value: 10.670000

if-else
The if-else statement is used to make decisions, where if a condition is true, then it will execute
a block of code; if it isn’t true (else), then it will execute a different block of code.

if(marks == 97) {
// if marks are 97 then will execute this block of code

else {

// else it will execute this block of code

Below is the C program to demonstrate an if-else statement:

// C program to
demonstrate

// if-else keyword
#include <stdio.h>

// Driver code
int main()
{
int a = 10;
if(a < 11)
{
printf("A is less
than 11");
}
else
{
printf("A is equal to
or "
"greater than
11");
}
return 0;
}
Output

A is less than 11
enum
The enum keyword is used to declare an enum (short for enumeration). An enum is a
user-defined datatype, which holds a list of user-defined integer constants. By default, the value
of each constant is it’s index (starting at zero), though this can be changed. You can declare an
object of an enum and can set it’s value to one of the constants you declared before. Here is an
example of how an enum might be used:

// An example program to

// demonstrate working of
// enum in C
#include<stdio.h>

// enum declaration:
enum week{Mon, Tue, Wed, Thur, Fri,
Sat, Sun};

// Driver code
int main()
{
//object of the enum (week), called
day
enum week day;
day = Wed;
printf("%d", day);
return 0;
}
Output

extern
The extern keyword is used to declare a variable or a function that has an external linkage
outside of the file declaration.
#include
<stdio.h>

extern int a;

int main(){

printf("%d",
a);

return 0;
}

for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a
certain amount of times.

Below is the C program to demonstrate a for-loop:

// C program to
demonstrate

// for keyword
#include <stdio.h>

// Driver code
int main()
{
for (int i = 0; i <
5; i++)
{
printf("%d ", i);
}
return 0;
}
Output
01234

goto
The goto statement is used to transfer the control of the program to the given label. It is used to
jump from anywhere to anywhere within a function.

Example:

goto label;

// code

label:

Below is the C program to demonstrate the goto keyword:

// C program
demonstrate

// goto keyword
#include <stdio.h>

// Function to print
numbers
// from 1 to 10
void printNumbers() {
int n = 1;

label:
printf("%d ", n);
n++;
if (n <= 10) goto
label;
}
// Driver code
int main(){
printNumbers();
return 0;
}
Output

1 2 3 4 5 6 7 8 9 10

int
int keyword is used in a type declaration to give a variable an integer type. In C, the integer
variable must have a range of at least -32768 to +32767.

Example:

int x = 10;

Below is the C program to show the int keyword:

// C program to
demonstrate

// int keyword
#include <stdio.h>

void sum() {
int a = 10, b =
20;
int sum;
sum = a + b;
printf("%d",
sum);
}

// Driver code
int main() {
sum();
return 0;
}
Output

30

short, long, signed, and unsigned


Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.

Data Type Memory Range Format


(bytes) Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

long int 4 -2,147,483,648 to %ld


2,147,483,647

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long 8 0 to %llu


int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Below is the C program to demonstrate the short, long, signed, and unsigned keywords:
// C program to demonstrate

// short, long, signed,


// and unsigned keyword
#include <stdio.h>

// Driver code
int main() {
// short integer
short int a = 12345;

// signed integer
signed int b = -34;

// unsigned integer
unsigned int c = 12;

// L or l is used for
// long int in C.
long int d = 99998L;

printf("Integer value with a short int data:


%hd", a);
printf("\nInteger value with a signed int
data: %d", b);
printf("\nInteger value with an unsigned int
data: %u", c);
printf("\nInteger value with a long int data:
%ld", d);
return 0;
}
Output

Integer value with a short int data: 12345

Integer value with a signed int data: -34

Integer value with an unsigned int data: 12

Integer value with a long int data: 99998


return
The return statement returns a value to where the function was called.

Example:

return x;

Below is the C program to demonstrate the return keyword:

// C program to
demonstrate

// return keyword
#include <stdio.h>
int sum(int x, int y)
{
int sum;
sum = x + y;
return sum;
}

// Driver code
int main() {
int num1 = 10;
int num2 = 20;
printf("Sum: %d",
sum(num1,
num2));
return 0;
}
Output

Sum: 30

sizeof
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.

Example:

sizeof(char);

sizeof(int);

sizeof(float); in bytes.

Below is the C program to demonstrate sizeof keyword:

// C program to
demonsstrate

// sizeof keyword
#include <stdio.h>

// Driver code
int main() {
int x = 10;
printf("%d",
sizeof(x));
return 0;
}
Output

register
Register variables tell the compiler to store variables in the CPU register instead of memory.
Frequently used variables are kept in the CPU registers for faster access.

Example:

register char c = 's';

static
The static keyword is used to create static variables. A static variable is not limited by a scope
and can be used throughout the program. It’s value is preserved even after it’s scope.

For Example:

static int num;

struct
The struct keyword in C programming language is used to declare a structure. A structure is a
list of variables, (they can be of different data types), which are grouped together under one
data type.

For Example:

struct Geek {

char name[50];

int num;

double var;

};

Below is the C program for the struct keyword:


// C program to demonstrate

// struct keyword
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
};

// Driver code
int main( ) {
// Declare Book1 of type Book
struct Books book1;

// book 1 specification
strcpy(book1.title, "C++
Programming");
strcpy(book1.author, "Bjarne
Stroustrup");

// Print book details


printf("Book 1 title : %s\n",
book1.title);
printf("Book 1 author : %s\n",
book1.author);
return 0;
}
Output

Book 1 title : C++ Programming

Book 1 author : Bjarne Stroustrup

typedef
The typedef keyword in C programming language is used to define a data type with a new name
in the program. typedef keyword is used to make our code more readable.

For Example:

typedef long num

In this example we have changed the datatype name of “long” to “num”.

union
The union is a user-defined data type. All data members which are declared under the union
keyword share the same memory location.

Example:

union GeekforGeeks {

int x;

char s;

} obj;

Below is the C program for the union keyword:

#include <stdio.h>

union student {
int age;
char marks;
} s;

// Driver code
int main() {
s.age = 15;
s.marks = 56;
printf("age = %d",
s.age);
printf("\nmarks = %d",
s.marks);
}
Output
age = 56

marks = 56

void
The void keyword means nothing i.e, NULL value. When the function return type is used as the
void, the keyword void specifies that it has no return value.

Example:

void fun() {

// program

volatile
The volatile keyword is used to create volatile objects. Objects which are declared volatile are
omitted from optimization as their values can be changed by code outside the scope of the
current code at any point in time.

For Example:

const volatile marks = 98;

marks are declared constant so they can’t be changed by the program. But hardware can
change it as they are volatile objects.

4. VARIABLES:

What is a variable in C?
A variable in C is a memory location with some name that helps store some form
of data and retrieves it when required. We can store different types of data in the
variable and reuse the same variable for storing some other data any number of
times.

They can be viewed as the names given to the memory location so that we can refer to it
without having to memorize the memory address. The size of the variable depends upon the
data type it stores.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.

data_type variable_name = value; // defining single variable

or

data_type variable_name1, variable_name2; // defining multiple variable

Here,

● data_type: Type of data that a variable can store.


● variable_name: Name of the variable given by the user.
● value: value assigned to the variable by the user.

Example

int var; // integer variable

char a; // character variable

float fff; // float variables

Note: C is a strongly typed language so all the variables types must be specified
before using them.

There are 3 aspects of defining a variable:

1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. C Variable Declaration

Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type.When the variable is declared compiler automatically allocates the memory
for it.

2. C Variable Definition

In the definition of a C variable, the compiler allocates some memory and some value to it. A
defined variable will contain some random garbage value till it is not initialized.

Example

int var;

char var2;

Note: Most of the modern C compilers declare and define the variable in single step.

3. C Variable Initialization

Initialization of a variable is the process where the user assigns some meaningful value to the
variable.

Example

int var; // variable definition

var = 10; // initialization

or

int var = 10; // variable declaration and definition

How to use variables in C?


The below example demonstrates how the use variables in C language.
// C program to demonstrate the

// declaration, definition and


// initialization
#include <stdio.h>

int main()
{
// declaration with definition
int defined_var;

printf("Defined_var: %d\n", defined_var);

// initialization
defined_var = 12;

// declaration + definition + initialization


int ini_var = 25;

printf("Value of defined_var after initialization:


%d\n",defined_var);
printf("Value of ini_var: %d", ini_var);

return 0;
}
Output

Defined_var: 0

Value of defined_var after initialization: 12

Value of ini_var: 25

Rules for Naming Variables in C


You can assign any name to the variable as long as it follows the following rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start with a
digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.

C Variable Types
The C variables can be classified into the following types:

1. Local Variables
2. Global Variables
3. Static Variables
4. Automatic Variables
5. Extern Variables
6. Register Variables

1. Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its
scope is limited to the block or function in which it is declared.

Example of Local Variable in C


// C program to declare and print local
variable inside a

// function.
#include <stdio.h>

void function()
{
int x = 10; // local variable
printf("%d", x);
}

int main() { function(); }

Output

10

In the above code, x can be used only in the scope of function(). Using it in the main function
will give an error.

2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of code. Its
scope is the whole program i.e. we can access the global variable anywhere in the C program
after it is declared.

Example of Global Variable in C


// C program to demonstrate use of
global variable

#include <stdio.h>

int x = 20; // global variable

void function1() { printf("Function 1:


%d\n", x); }

void function2() { printf("Function 2:


%d\n", x); }

int main()
{

function1();
function2();
return 0;
}

Output

Function 1: 20

Function 2: 20

In the above code, both functions can use the global variable as global variables are accessible
by all the functions.

Note: When we have same name for local and global variable, local variable will be
given preference over the global variable by the compiler.

For accessing global variable in this case, we can use the method mention here.

3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be defined
only once in a C program and its scope depends upon the region where it is declared (can be
global or local).

The default value of static variables is zero.

Syntax of Static Variable in C

static data_type variable_name = initial_value;

As its lifetime is till the end of the program, it can retain its value for multiple function calls as
shown in the example.

Example of Static Variable in C

// C program to demonstrate use of


static variable

#include <stdio.h>

void function()
{
int x = 20; // local variable
static int y = 30; // static
variable
x = x + 10;
y = y + 10;
printf("\tLocal: %d\n\tStatic:
%d\n", x, y);
}

int main()
{
printf("First Call\n");
function();
printf("Second Call\n");
function();
printf("Third Call\n");
function();
return 0;
}

Output

First Call

Local: 30

Static: 40

Second Call

Local: 30

Static: 50

Third Call

Local: 30

Static: 60

In the above example, we can see that the local variable will always print the same value
whenever the function will be called whereas the static variable will print the incremented value
in each function call.

Note: Storage Classes in C is the concept that helps us to determine the scope,
lifetime, memory location, and default value (initial value) of a variable.

4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto
variables.

Their scope is local and their lifetime is till the end of the block. If we need, we can use the
auto keyword to define the auto variables.

The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C


auto data_type variable_name;

or

data_type variable_name; (in local scope)

Example of auto Variable in C

// C program to demonstrate use of


automatic variable

#include <stdio.h>

void function()
{
int x = 10; // local variable (also
automatic)
auto int y = 20; // automatic variable
printf("Auto Variable: %d", y);
}
int main()
{

function();
return 0;
}

Output

Auto Variable: 20

In the above example, both x and y are automatic variables. The only difference is that variable
y is explicitly declared with the auto keyword.

5. External Variables in C
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword.

Their scope is global and they exist between multiple C files.

Syntax of Extern Variables in C

extern data_type variable_name;

Example of Extern Variable in C

----------myfile.h------------

extern int x=10; //external variable (also global)

----------program1.c----------

#include "myfile.h"

#include <stdio.h>

void printValue(){

printf("Global variable: %d", x);

In the above example, x is an external variable that is used in multiple C files.

6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM. Their scope is local and exists till the end of the block or
a function.

These variables are declared using the register keyword.

The default value of register variables is a garbage value.

Syntax of Register Variables in C


register data_type variable_name = initial_value;

Example of Register Variables in C

// C program to demonstrate the definition


of register

// variable
#include <stdio.h>

int main()
{
// register variable
register int var = 22;

printf("Value of Register Variable:


%d\n", var);
return 0;
}

Output

Value of Register Variable: 22

NOTE: We cannot get the address of the register variable using addressof (&)
operator because they are stored in the CPU register. The compiler will throw an
error if we try to get the address of register variable.

Constant Variable in C
Till now we have only seen the variables whose values can be modified any number of times.
But C language also provides us a way to make the value of a variable immutable. We can do
that by defining the variable as constant.

A constant variable in C is a read-only variable whose value cannot be modified once it is


defined. We can declare a constant variable using the const keyword.
Syntax of Const Variable in C

const data_type variable_name = value;

Note: We have to always initialize the const variable at the definition as we cannot
modify its value after defining.

Example of Const Variable in C

// C Program to Demonstrate
constant variable

#include <stdio.h>

int main()
{
// variable
int not_constant;

// constant variable;
const int constant = 20;

// changing values
not_constant = 40;
constant = 22;

return 0;
}

Output

5. TYPE QUALIFIERS
Type qualifiers add special attributes to existing data types in C programming
language.

There are three type qualifiers in C language and volatile and restrict type
qualifiers are explained below −

Volatile
A volatile type qualifier is used to tell the compiler that a variable is shared.
That is, a variable may be referenced and changed by other programs (or)
entities if it is declared as volatile.

For example, volatile int x;

Restrict
This is used only with pointers. It indicates that the pointer is only an initial way
to access the deference data. It provides more help to the compiler for
optimization.

Example Program

Following is the C program for volatile type qualifier −

int *ptr
int a= 0;
ptr = &a;
____
____
____
*ptr+=4; // Cannot be replaced with *ptr+=9
____
____
____
*ptr+=5;

Here, the compiler cannot replace the two statements *ptr+=4 and *ptr+=5 by
one statement *ptr+=9. Because, it is not clear if the variable ‘a’ can be
accessed directly (or) through other pointers.

For example,

restrict int *ptr


int a= 0;
ptr = &a;
____
____
____
*ptr+=4; // Can be replaced with *ptr+=9
____
____
*ptr+=5;
____
____

Here, the compiler can replace the two statements by one statement, *ptr+=9.
Because, it is sure that variable cannot be accessed through any other
resources.

Example
Following is the C program for the use of restrict keyword −

Live Demo

#include<stdio.h>
void keyword(int* a, int* b, int* restrict c){
*a += *c;
// Since c is restrict, compiler will
// not reload value at address c in
// its assembly code.
*b += *c;
}
int main(void){
int p = 10, q = 20,r=30;
keyword(&p, &q,&r);
printf("%d %d %d", p, q,r);
return 0;
}

Output
When the above program is executed, it produces the following result −

40 50 30
6. CONSTANTS

What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program. We can not make any change in the value of the
constant variables after they are defined.

How to define a constant in C?


We define a constant in C language using the const keyword. Also known as a
const type qualifier, the const keyword is placed at the start of the variable
declaration to declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;


Example of Constants in C

// C program to illustrate constant variable definition


#include <stdio.h>

int main()
{

// defining integer constant using const keyword


const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",


int_const);
printf("Printing value of Character Constant: %c\n",
char_const);
printf("Printing value of Float Constant: %f",
float_const);

return 0;
}

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we
won’t be able to change it. The following image describes examples of incorrect
and correct variable definitions.

Types of Constants in C
The type of the constant is the same as the data type of the variables. Following
is the list of the types of constants

● Integer Constant

● Character Constant

● Floating Point Constant

● Double Precision Floating Point Constant


● Array Constant

● Structure Constant

We just have to add the const keyword at the start of the variable declaration.

Properties of Constant in C
The important properties of constant variables in C defined using the const
keyword are as follows:

1. Initialization with Declaration

We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.

2. Immutability

The constant variables in c are immutable after its definition, i.e., they can be
initialized only once in the whole program. After that, we cannot modify the
value stored inside that variable.

// C Program to demonstrate the behaviour of constant


// variable
#include <stdio.h>

int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;

printf("Value of var: %d", var);


return 0;
}

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

Difference between Constants and Literals


The constant and literals are often confused as the same. But in C language,
they are different entities and have different semantics. The following table list
the differences between the constants and literals in C:

Constant Literals

Constants are variables that cannot be Literals are the fixed values that
modified once declared. define themselves.

Constants are defined by using the They themselves are the values
const keyword in C. They store literal that are assigned to the variables
values in themselves. or constants.

We can determine the address of We cannot determine the address


constants. of a literal except string literal.
They are lvalues. They are rvalues.

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor


We can also define a constant in C using #define preprocessor. The constant
defined using #define are macros that behaves like a constant. These constants
are not handled by the compiler, they are handled by the preprocessor and are
replaced by their value before complication.

0 seconds of 15 secondsVolume 0%
This ad will end in 13

Syntax of Constant in C using #define

#define const_name value

Example

// C Program to define a constant using #define


#include <stdio.h>
#define pi 3.14

int main()
{

printf("The value of pi: %.2f", pi);


return 0;
}

Output
The value of pi: 3.14
7. OPERATORS:

What is a constant in C?
As the name suggests, a constant in C is a variable that cannot be modified once
it is declared in the program. We can not make any change in the value of the
constant variables after they are defined.

How to define a constant in C?


We define a constant in C language using the const keyword. Also known as a
const type qualifier, the const keyword is placed at the start of the variable
declaration to declare that variable as a constant.

Syntax to Define Constant

const data_type var_name = value;

Example of Constants in C
// C program to illustrate constant variable definition
#include <stdio.h>

int main()
{

// defining integer constant using const keyword


const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",


int_const);
printf("Printing value of Character Constant: %c\n",
char_const);
printf("Printing value of Float Constant: %f",
float_const);

return 0;
}

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the constant variables at
declaration. Otherwise, the variable will store some garbage value and we
won’t be able to change it. The following image describes examples of incorrect
and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following
is the list of the types of constants

● Integer Constant

● Character Constant

● Floating Point Constant

● Double Precision Floating Point Constant

● Array Constant

● Structure Constant

We just have to add the const keyword at the start of the variable declaration.

Properties of Constant in C
The important properties of constant variables in C defined using the const
keyword are as follows:

1. Initialization with Declaration

We can only initialize the constant variable in C at the time of its declaration.
Otherwise, it will store the garbage value.

2. Immutability

The constant variables in c are immutable after its definition, i.e., they can be
initialized only once in the whole program. After that, we cannot modify the
value stored inside that variable.

// C Program to demonstrate the behaviour of constant


// variable
#include <stdio.h>

int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;

printf("Value of var: %d", var);


return 0;

Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Difference between Constants and Literals
The constant and literals are often confused as the same. But in C language,
they are different entities and have different semantics. The following table list
the differences between the constants and literals in C:

Constant Literals

Constants are variables that cannot be Literals are the fixed values that
modified once declared. define themselves.

Constants are defined by using the They themselves are the values
const keyword in C. They store literal that are assigned to the variables
values in themselves. or constants.

We can determine the address of We cannot determine the address


constants. of a literal except string literal.

They are lvalues. They are rvalues.


Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.

Defining Constant using #define Preprocessor


We can also define a constant in C using #define preprocessor. The constant
defined using #define are macros that behaves like a constant. These constants
are not handled by the compiler, they are handled by the preprocessor and are
replaced by their value before complication.

0 seconds of 15 secondsVolume 0%
This ad will end in 13

Syntax of Constant in C using #define

#define const_name value

Example

// C Program to define a constant using #define


#include <stdio.h>
#define pi 3.14

int main()
{

printf("The value of pi: %.2f", pi);


return 0;
}

Output
The value of pi: 3.14
8. OPERATORS

What are Operators in C?


Operators can be defined as the symbols that help us to perform specific
mathematical, relational, bitwise, conditional, or logical computations on
operands. In other words, we can say that an operator operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;

Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are
operands. The addition operator tells the compiler to add both of the operands
‘a’ and ‘b’. The functionality of the C programming language is incomplete
without the use of operators.

Types of Operators in C
C has many built-in operators and can be classified into 6 types:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

6. Other Operators
The above operators have been discussed in detail:

1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on
operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:

a) Unary Operators:

Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6

b) Binary Operators:

Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, whether an
operand is greater than the other operand or not, etc. Some of the relational
operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b

3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or
to complement the evaluation of the original condition in consideration. The
result of the operation of a logical operator is a Boolean value either true or
false.

For example, the logical AND represented as the ‘&&’ operator in C returns
true when both the conditions under consideration are satisfied. Otherwise, it
returns false. Therefore, a && b returns true when both a and b are true (i.e.
non-zero)(See this article for more reference).
cout<<((4 != 5) && (4 < 5)); // true

4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is
performed on the operands. Mathematical operations such as addition,
subtraction, multiplication, etc. can be performed at the bit level for faster
processing. For example, the bitwise AND operator represented as ‘&’ in C
takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side operand of
the assignment operator is a value. The value on the right side must be of the
same data type as the variable on the left side otherwise the compiler will raise
an error.

Different types of assignment operators are shown below:

a) “=”

This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';

b) “+=”

This operator is the combination of the ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

c) “-=”

This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and
then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

d) “*=”

This operator is a combination of the ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.

e) “/=”

This operator is a combination of the ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.

6. Other Operators
Apart from the above operators, there are some other operators available in C
used to perform some specific tasks. Some of them are discussed here:

i. sizeof operator

● sizeof is much used in the C programming language.

● It is a compile-time unary operator which can be used to compute the

size of its operand.


● The result of sizeof is of the unsigned integral type which is usually

denoted by size_t.

● Basically, the sizeof the operator is used to compute the size of the

variable.

To know more about the topic refer to this article.

ii. Comma Operator

● The comma operator (represented by the token) is a binary operator

that evaluates its first operand and discards the result, it then

evaluates the second operand and returns this value (and type).

● The comma operator has the lowest precedence of any C operator.

● Comma acts as both operator and separator.

To know more about the topic refer to this article.

iii. Conditional Operator

● The conditional operator is of the form Expression1? Expression2:

Expression3

● Here, Expression1 is the condition to be evaluated. If the

condition(Expression1) is True then we will execute and return the

result of Expression2 otherwise if the condition(Expression1) is false

then we will execute and return the result of Expression3.


● We may replace the use of if..else statements with conditional

operators.

To know more about the topic refer to this article.

iv. dot (.) and arrow (->) Operators

● Member operators are used to referencing individual members of

classes, structures, and unions.

● The dot operator is applied to the actual object.

● The arrow operator is used with a pointer to an object.

to know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.

v. Cast Operator

● Casting operators convert one data type to another. For example,

int(2.2000) would return 2.

● A cast is a special operator that forces one data type to be converted

into another.

● The most general cast supported by most of the C compilers is as

follows − [ (type) expression ].

To know more about the topic refer to this article.

vi. &,* Operator


● Pointer operator & returns the address of a variable. For example &a;

will give the actual address of the variable.

● The pointer operator * is a pointer to a variable. For example *var; will

pointer to a variable var.

To know more about the topic refer to this article.

C Operators with Example


C
// C Program to Demonstrate the working concept of

// Operators

#include <stdio.h>

int main()

int a = 10, b = 5;

// Arithmetic operators

printf("Following are the Arithmetic operators in C\n");


printf("The value of a + b is %d\n", a + b);

printf("The value of a - b is %d\n", a - b);

printf("The value of a * b is %d\n", a * b);

printf("The value of a / b is %d\n", a / b);

printf("The value of a % b is %d\n", a % b);

// First print (a) and then increment it

// by 1

printf("The value of a++ is %d\n", a++);

// First print (a+1) and then decrease it


// by 1

printf("The value of a-- is %d\n", a--);

// Increment (a) by (a+1) and then print

printf("The value of ++a is %d\n", ++a);

// Decrement (a+1) by (a) and then print

printf("The value of --a is %d\n", --a);

// Assignment Operators --> used to assign values to

// variables int a =3, b=9; char d='d';


// Comparison operators

// Output of all these comparison operators will be (1)

// if it is true and (0) if it is false

printf(

"\nFollowing are the comparison operators in C\n");

printf("The value of a == b is %d\n", (a == b));

printf("The value of a != b is %d\n", (a != b));

printf("The value of a >= b is %d\n", (a >= b));

printf("The value of a <= b is %d\n", (a <= b));

printf("The value of a > b is %d\n", (a > b));


printf("The value of a < b is %d\n", (a < b));

// Logical operators

printf("\nFollowing are the logical operators in C\n");

printf("The value of this logical and operator ((a==b) "

"&& (a<b)) is:%d\n",

((a == b) && (a < b)));

printf("The value of this logical or operator ((a==b) "

"|| (a<b)) is:%d\n",

((a == b) || (a < b)));

printf("The value of this logical not operator "


"(!(a==b)) is:%d\n",

(!(a == b)));

return 0;

Output
Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10

Following are the comparison operators in C


The value of a == b is 0
The value of a != b is 1
The value of a >= b is 1
The value of a <= b is 0
The value of a > b is 1
The value of a < b is 0

Following are the logical operators in C


The value of this logical and operator ((a==b) && (a<b)) is:0
The value of this logical or operator ((a==b) || (a<b)) is:0
The value of this logical not operator (!(a==b)) is:1

Time and Space Complexity


Time Complexity: O(1)
Auxiliary Space: O(1)

Precedence of Operators in C
The below table describes the precedence order and associativity of operators in
C. The precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

Member selection via object


. left-to-right
name
Member selection via a
-> left-to-right
pointer

Postfix increment/decrement
a++/a– left-to-right
(a is a variable)

Prefix increment/decrement (a
++a/–a right-to-left
is a variable)

+/- Unary plus/minus right-to-left

2
Logical negation/bitwise
!~ right-to-left
complement

Cast (convert value to


(type) right-to-left
temporary value of type)
* Dereference right-to-left

& Address (of operand) right-to-left

Determine size in bytes on


sizeof right-to-left
this implementation

Multiplication/division/modulu
3 *,/,% left-to-right
s

4 +/- Addition/subtraction left-to-right

Bitwise shift left, Bitwise shift


5 << , >> left-to-right
right
Relational less than/less than
< , <= left-to-right
or equal to

Relational greater
> , >= left-to-right
than/greater than or equal to

Relational is equal to/is not


7 == , != left-to-right
equal to

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right


11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

Addition/subtraction
+= , -= right-to-left
assignment

14

Multiplication/division
*= , /= right-to-left
assignment
Modulus/bitwise AND
%= , &= right-to-left
assignment

Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment

Bitwise shift left/right


<>= right-to-left
assignment

15 , expression separator left-to-right

Conclusion
In this article, the points we learned about the operator are as follows:

● Operators are symbols used for performing some kind of operation in

C.

● The operation can be mathematical, logical, relational, bitwise,

conditional, or logical.
● There are seven types of Unary operators, Arithmetic operator,

Relational operator, Logical operator, Bitwise operator, Assignment

operator, and Conditional operator.

● Every operator returns a numerical value except logical and conditional

operator which returns a boolean value(true or false).

● ‘=’ and ‘==’ are not same as ‘=’ assigns the value whereas ‘==’ checks if

both the values are equal or not.

● There is a Precedence in the operator means the priority of using one

operator is greater than another operator.

The above operators have been discussed in detail:

1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on
operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:

a) Unary Operators:

Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6

b) Binary Operators:

Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9

2. Relational Operators in C
These are used for the comparison of the values of two operands. For example,
checking if one operand is equal to the other operand or not, whether an
operand is greater than the other operand or not, etc. Some of the relational
operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b

3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or
to complement the evaluation of the original condition in consideration. The
result of the operation of a logical operator is a Boolean value either true or
false.

For example, the logical AND represented as the ‘&&’ operator in C returns
true when both the conditions under consideration are satisfied. Otherwise, it
returns false. Therefore, a && b returns true when both a and b are true (i.e.
non-zero)(See this article for more reference).
cout<<((4 != 5) && (4 < 5)); // true

4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is
performed on the operands. Mathematical operations such as addition,
subtraction, multiplication, etc. can be performed at the bit level for faster
processing. For example, the bitwise AND operator represented as ‘&’ in C
takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010

5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side
operand of the assignment operator is a variable and the right side operand of
the assignment operator is a value. The value on the right side must be of the
same data type as the variable on the left side otherwise the compiler will raise
an error.

Different types of assignment operators are shown below:

a) “=”

This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';

b) “+=”

This operator is the combination of the ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on the right from the current value of the variable on left and
then assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

d) “*=”

This operator is a combination of the ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.

e) “/=”

This operator is a combination of the ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.

6. Other Operators
Apart from the above operators, there are some other operators available in C
used to perform some specific tasks. Some of them are discussed here:

i. sizeof operator

● sizeof is much used in the C programming language.


● It is a compile-time unary operator which can be used to compute the

size of its operand.

● The result of sizeof is of the unsigned integral type which is usually

denoted by size_t.

● Basically, the sizeof the operator is used to compute the size of the

variable.

To know more about the topic refer to this article.

ii. Comma Operator

● The comma operator (represented by the token) is a binary operator

that evaluates its first operand and discards the result, it then

evaluates the second operand and returns this value (and type).

● The comma operator has the lowest precedence of any C operator.

● Comma acts as both operator and separator.

To know more about the topic refer to this article.

iii. Conditional Operator

● The conditional operator is of the form Expression1? Expression2:

Expression3

● Here, Expression1 is the condition to be evaluated. If the

condition(Expression1) is True then we will execute and return the


result of Expression2 otherwise if the condition(Expression1) is false

then we will execute and return the result of Expression3.

● We may replace the use of if..else statements with conditional

operators.

To know more about the topic refer to this article.

iv. dot (.) and arrow (->) Operators

● Member operators are used to referencing individual members of

classes, structures, and unions.

● The dot operator is applied to the actual object.

● The arrow operator is used with a pointer to an object.

to know more about dot operators refer to this article and to know more about
arrow(->) operators refer to this article.

v. Cast Operator

● Casting operators convert one data type to another. For example,

int(2.2000) would return 2.

● A cast is a special operator that forces one data type to be converted

into another.

● The most general cast supported by most of the C compilers is as

follows − [ (type) expression ].

To know more about the topic refer to this article.


vi. &,* Operator

● Pointer operator & returns the address of a variable. For example &a;

will give the actual address of the variable.

● The pointer operator * is a pointer to a variable. For example *var; will

pointer to a variable var.

To know more about the topic refer to this article.

C Operators with Example


// C Program to Demonstrate the working concept of
// Operators
#include <stdio.h>

int main()
{

int a = 10, b = 5;
// Arithmetic operators
printf("Following are the Arithmetic operators in C\n");
printf("The value of a + b is %d\n", a + b);
printf("The value of a - b is %d\n", a - b);

printf("The value of a * b is %d\n", a * b);


printf("The value of a / b is %d\n", a / b);
printf("The value of a % b is %d\n", a % b);
// First print (a) and then increment it
// by 1
printf("The value of a++ is %d\n", a++);

// First print (a+1) and then decrease it


// by 1
printf("The value of a-- is %d\n", a--);

// Increment (a) by (a+1) and then print


printf("The value of ++a is %d\n", ++a);

// Decrement (a+1) by (a) and then print


printf("The value of --a is %d\n", --a);

// Assignment Operators --> used to assign values to


// variables int a =3, b=9; char d='d';

// Comparison operators
// Output of all these comparison operators will be (1)
// if it is true and (0) if it is false
printf(
"\nFollowing are the comparison operators in C\n");
printf("The value of a == b is %d\n", (a == b));
printf("The value of a != b is %d\n", (a != b));
printf("The value of a >= b is %d\n", (a >= b));
printf("The value of a <= b is %d\n", (a <= b));
printf("The value of a > b is %d\n", (a > b));
printf("The value of a < b is %d\n", (a < b));

// Logical operators
printf("\nFollowing are the logical operators in C\n");
printf("The value of this logical and operator ((a==b) "
((a == b) && (a < b)));
printf("The value of this logical or operator ((a==b) "
"|| (a<b)) is:%d\n",
((a == b) || (a < b)));
printf("The value of this logical not operator "
"(!(a==b)) is:%d\n",
(!(a == b)));

return 0;
}

Output
Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10

Following are the comparison operators in C


The value of a == b is 0
The value of a != b is 1
The value of a >= b is 1
The value of a <= b is 0
The value of a > b is 1
The value of a < b is 0

Following are the logical operators in C


The value of this logical and operator ((a==b) && (a<b)) is:0
The value of this logical or operator ((a==b) || (a<b)) is:0
The value of this logical not operator (!(a==b)) is:1

Precedence of Operators in C
The below table describes the precedence order and associativity of operators in
C. The precedence of the operator decreases from top to bottom.
Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

Member selection via object


. left-to-right
name
1

Member selection via a


-> left-to-right
pointer

Postfix increment/decrement
a++/a– left-to-right
(a is a variable)
Prefix increment/decrement (a
++a/–a right-to-left
is a variable)

+/- Unary plus/minus right-to-left

Logical negation/bitwise
!~ right-to-left
complement

2
Cast (convert value to
(type) right-to-left
temporary value of type)

* Dereference right-to-left

& Address (of operand) right-to-left


Determine size in bytes on
sizeof right-to-left
this implementation

Multiplication/division/modulu
3 *,/,% left-to-right
s

4 +/- Addition/subtraction left-to-right

Bitwise shift left, Bitwise shift


5 << , >> left-to-right
right

Relational less than/less than


< , <= left-to-right
or equal to

Relational greater
> , >= left-to-right
than/greater than or equal to
Relational is equal to/is not
7 == , != left-to-right
equal to

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left


= Assignment right-to-left

Addition/subtraction
+= , -= right-to-left
assignment

Multiplication/division
*= , /= right-to-left
assignment

14

Modulus/bitwise AND
%= , &= right-to-left
assignment

Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment

Bitwise shift left/right


<>= right-to-left
assignment
15 , expression separator left-to-right

Conclusion
In this article, the points we learned about the operator are as follows:

● Operators are symbols used for performing some kind of operation in

C.

● The operation can be mathematical, logical, relational, bitwise,

conditional, or logical.

● There are seven types of Unary operators, Arithmetic operator,

Relational operator, Logical operator, Bitwise operator, Assignment

operator, and Conditional operator.

● Every operator returns a numerical value except logical and conditional

operator which returns a boolean value(true or false).

● ‘=’ and ‘==’ are not same as ‘=’ assigns the value whereas ‘==’ checks if

both the values are equal or not.

● There is a Precedence in the operator means the priority of using one

operator is greater than another operator.

9. Expression: An expression is a combination of operators, constants and


variables. An expression may consist of one or more operands, and zero or more
operators to produce a value.
Example:
a+b
c
s-1/7*f
.
.
etc

Types of Expressions:

Expressions may be of the following types:


● Constant expressions: Constant Expressions consists of only constant

values. A constant value is one that doesn’t change.

Examples:
5, 10 + 5 / 6.0, 'x’

● Integral expressions: Integral Expressions are those which produce

integer results after implementing all the automatic and explicit type

conversions.

Examples:
x, x * y, x + int( 5.0)

where x and y are integer variables.

● Floating expressions: Float Expressions are which produce floating

point results after implementing all the automatic and explicit type

conversions.
Examples:
x + y, 10.75

where x and y are floating point variables.

● Relational expressions: Relational Expressions yield results of type

bool which takes a value true or false. When arithmetic expressions

are used on either side of a relational operator, they will be evaluated

first and then the results compared. Relational expressions are also

known as Boolean expressions.

Examples:
x <= y, x + y > 2

● Logical expressions: Logical Expressions combine two or more

relational expressions and produces bool type results.

Examples:
x > y && x == 10, x == 10 || y == 5

● Pointer expressions: Pointer Expressions produce address values.

Examples:
&x, ptr, ptr++

where x is a variable and ptr is a pointer.

● Bitwise expressions: Bitwise Expressions are used to manipulate data

at bit level. They are basically used for testing or shifting bits.

Examples:
x << 3

shifts three bit position to left


y >> 1
shifts one bit position to right.

Shift operators are often used for multiplication and division by powers

of two.

Note: An expression may also use combinations of the above expressions. Such
expressions are known as compound expressions.
10.FORMATTED AND UNFORMATTED INPUT AND OUTPUT FUNCTIONS IN C

Formatted and Unformatted Input/Output


functions in C with Examples
● Formatted I/O Functions.
● Unformatted I/O Functions.
● Formatted I/O Functions vs Unformatted I/O Functions.

Formatted I/O Functions

Formatted I/O functions are used to take various inputs from the user and display
multiple outputs to the user. These types of I/O functions can help to display the
output to the user in different formats using the format specifiers. These I/O
supports all data types like int, float, char, and many more.

Why they are called formatted I/O?

These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions according
to our needs.

List of some format specifiers-


S Format
Type Description
NO. Specifier

int/signed
1 %d used for I/O signed integer value
int

2 %c char Used for I/O character value

Used for I/O decimal floating-point


3 %f float
value

Used for I/O string/group of


4 %s string
characters

Used for I/O long signed integer


5 %ld long int
value
unsigned
6 %u Used for I/O unsigned integer value
int

unsigned
7 %i used for the I/O integer value
int

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-

1. printf()
2. scanf()
3. sprintf()
4. sscanf()

printf():

printf() function is used in a C program to display any value like float, integer,
character, string, etc on the console screen. It is a pre-defined function that is
already declared in the stdio.h(header file).
Syntax 1:

To display any variable value.

printf(“Format Specifier”, var1, var2, …., varn);

Example:

// C program to implement
// printf() function
#include <stdio.h>

// Driver code
int main()
{
// Declaring an int type variable
int a;

// Assigning a value in a variable


a = 20;

// Printing the value of a variable


printf("%d", a);

return 0;
}

Output
20
Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
Example:
​ C
// C program to implement
// printf() function
#include <stdio.h>

// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}

Output

This is a string

scanf():

scanf() function is used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float,
character, string, and many more. This function is declared in stdio.h(header file),
that’s why it is also a pre-defined function. In scanf() function we use
&(address-of operator) which is used to store the variable value on the memory
location of that variable.

Syntax:

scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example:

​ C
// C program to implement
// scanf() function
#include <stdio.h>

// Driver code
int main()
{
int num1;

// Printing a message on
// the output screen
printf("Enter a integer number: ");

// Taking an integer value


// from keyboard
scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);

return 0;
}

Output

Enter a integer number: You have entered 0

Output:

Enter a integer number: 56


You have entered 56

sprintf():

sprintf stands for “string print”. This function is similar to printf() function but this
function prints the string into a character array instead of printing it on the
console screen.

Syntax:
sprintf(array_name, “format specifier”, variable_name);

Example:

// C program to implement
// the sprintf() function
#include <stdio.h>

// Driver code
int main()
{
char str[50];
int a = 2, b = 8;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);

// Displays the string


printf("%s", str);
return 0;

Output

2 and 8 are even number

sscanf():

sscanf stands for “string scanf”. This function is similar to scanf() function but
this function reads data from the string or character array instead of the console
screen.
Syntax:

sscanf(array_name, “format specifier”, &variable_name);

Example:

// C program to implement
// sscanf() function
#include <stdio.h>

// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;

// The string "a = 2 and b = 8"


// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);

// The value of a and b is now in


// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);

// Displays the value of c and d


printf("c = %d and d = %d", c, d);
return 0;
}

Output

c = 2 and d = 8

Unformatted Input/Output functions

Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype. These functions are used
to read single input from the user at the console and it allows to display the value
at the console.

Why they are called unformatted I/O?

These functions are called unformatted I/O functions because we cannot use
format specifiers in these functions and hence, cannot format these functions
according to our needs.

The following unformatted I/O functions will be discussed in this section-

1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()

getch():

getch() function reads a single character from the keyboard by the user but
doesn’t display that character on the console screen and immediately returned
without pressing enter key. This function is declared in conio.h(header file).
getch() is also used for hold the screen.

Syntax:

getch();

or
variable-name = getch();

Example:

// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();

return 0;

Output:

Enter any character:

getche():

getche() function reads a single character from the keyboard by the user and
displays it on the console screen and immediately returns without pressing the
enter key. This function is declared in conio.h(header file).

Syntax:
getche();

or

variable_name = getche();

Example:

// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character and


// displays immediately
getche();
return 0;
}

Output:

Enter any character: g

getchar():

The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads
one character at one time until and unless the enter key is pressed. This function
is declared in stdio.h(header file)
Syntax:

Variable-name = getchar();

Example:

// C program to implement

// the getchar() function

#include <conio.h>

#include <stdio.h>

// Driver code
int main()

// Declaring a char type variable

char ch;

printf("Enter the character: ");

// Taking a character from keyboard


ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;

Output:

Enter the character: a

putchar():
The putchar() function is used to display a single character at a time by passing
that character directly to it or by passing a variable that has already stored a
character. This function is declared in stdio.h(header file)

Syntax:

putchar(variable_name);

Example:

// C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
char ch;
printf("Enter any character: ");

// Reads a character
ch = getchar();

// Displays that character


putchar(ch);
return 0;
}

Output:

Enter any character: Z

Z
gets():

gets() function reads a group of characters or strings from the keyboard by the
user and these characters get stored in a character array. This function allows us
to write space-separated texts or strings. This function is declared in
stdio.h(header file).

Syntax:

char str[length of string in number]; //Declare a char type variable of any


length

gets(str);

Example:

​ C
// C program to implement

// the gets() function

#include <conio.h>

#include <stdio.h>

// Driver code

int main()

{
// Declaring a char type array

// of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or

// a string
gets(name);

// Displaying this line of character

// or a string

printf("You have entered: %s",

name);

return 0;

Output:
Please enter some texts: geeks for geeks

You have entered: geeks for geeks

puts():

In C programming puts() function is used to display a group of characters or


strings which is already stored in a character array. This function is declared in
stdio.h(header file).

Syntax:

puts(identifier_name );

Example:
// C program to implement

// the puts() function

#include <stdio.h>

// Driver code

int main()

char name[50];
printf("Enter your text: ");

// Reads string from user

gets(name);

printf("Your text is: ");

// Displays string
puts(name);

return 0;

Output:

Enter your text: GeeksforGeeks

Your text is: GeeksforGeeks

putch():

putch() function is used to display a single character which is given by the user
and that character prints at the current cursor location. This function is declared
in conio.h(header file)

Syntax:

putch(variable_name);
Example:

// C program to implement

// the putch() functions

#include <conio.h>

#include <stdio.h>

// Driver code

int main()
{

char ch;

printf("Enter any character:\n ");

// Reads a character from the keyboard

ch = getch();

printf("\nEntered character is: ");


// Displays that character on the console

putch(ch);

return 0;

Output:

Enter any character:

Entered character is: d

Formatted I/O vs Unformatted I/O


S
Formatted I/O functions Unformatted I/O functions
No.

These functions allow us to take These functions do not allow to


1 input or display output in the take input or display output in
user’s desired format. user desired format.

These functions support format These functions do not support


2
specifiers. format specifiers.

These are used for storing data These functions are not more
3
more user friendly user-friendly.

Here, we can use only character


4 Here, we can use all data types.
and string data types.

printf(), scanf, sprintf() and getch(), getche(), gets() and


5 sscanf() are examples of these puts(), are some examples of
functions. these functions.
10. Conditional Branching Statements in C

Conditional Branching Statements in C are used to execute the specific blocks


of code on the basis of some condition (as per requirements). These type of
Branching statements in C enables the programmers to execute the code only
and only certain statements are met. The following are different types of
conditional branching statements in C.

● if statement
● else statement
● else-if statement
● switch statement

if Statement

This statement is used to execute the specific block of code if a certain


condition is evaluated to be true.

Syntax of if Statement in C

Here is the syntax of the if statement in C.

if (condition) {
//code to be executed if condition specified evaluates is true
}

Here in the above syntax “condition” is a logical expression that is evaluated


for being true or false. If the condition is evaluated to be true, the code within
curly braces will be executed but if the condition is false, the code in braces
will be skipped.

Example of if Statement in C

Here is an example demonstrating the if statement in action.


​ C

#include <stdio.h>

int main() {

int x = 10;

if (x > 5) {

printf("x is greater than 5");

return 0;

Output

x is greater than 5

Explanation:
In the above example, the "if" statement checks whether the value of "x" is
greater than 5. Since the condition is true (x is indeed greater than 5), the code
within the curly braces is executed, and the message "x is greater than 5" is
printed to the console.
else Statement

The else Statement in C is considered just the opposite of the if statement.


This statement is used to execute the code if the condition specified in the if
statement evaluates to false.

Syntax of else Statement in C

Here is the syntax of the else Statement.

if (condition) {
// statemnets
} else{
// code executed if condition is false
}

Example of else Statement in C

Here is an example of how the else statement works in C.

​ C

#include <stdio.h>

int main() {

int x = 10;

if (x < 5) {

printf("x is less than 5\n");


} else {

printf("x is greater than or equal to 5\n");

return 0;

Output

x is greater than or equal to 5

Explanation:
In this example, the if statement in C checks whether the value of the variable
x is less than 5 or not. Since the value of x (which is 10), this condition is false,
and the code within the "if" block is not executed. Instead, the code within the
"else" block is executed, which prints the message "x is greater than or equal
to 5" to the console.

else if Statement

The else if statement in Cis used when we want to check multiple conditions.
It follows an "if" statement and is executed if the previous "if" statement’s
condition is false.

Syntax of else-if Statement in C

Here is the syntax for the "else if" statement:


if (condition1) {
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true and condition1 is
false
}

The "else if" statement can be repeated multiple times to check for multiple
conditions. If all conditions are false, the code within the final "else" block will
be executed.

Example of else-if Statement in C

Here is an example of the "else if" statement in action.

​ C

#include <stdio.h>

int main() {

int x = 10;

if (x > 15) {

printf("x is greater than 15");

else if (x > 5) {
printf("x is greater than 5 but less than or equal to 15");

else {

printf("x is less than or equal to 5");

return 0;

Output

x is greater than 5 but less than or equal to 15

Explanation:
In the above code, we have used a complete block of if, else if and else
statements. The if statement first checks whether the value of x is greater
than 15 or not. Since x(which is 10) is less than 15, so the control moves to
the else if block. Now the program checks whether x is greater than 5 or not.
This time the condition is true, so the code block inside this else-if block will
be executed and we get the required output on the screen i.e., "x is greater
than 5 but less than or equal to 15".

switch Statement
The switch statement in C is used when we have multiple conditions to check.
It is often used as an alternative to multiple "if" and "else if" statements.

Syntax of switch Statement in C

The syntax for the switch statement is as follows:

switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
...
default:
// code to be executed if none of the cases match
break;
}

The "expression" in the above syntax is the value being evaluated. Each "case"
statement represents a possible value of the expression. If the expression
matches one of the "case" statements, the code block within the matching
"case" statement is executed. If none of the "case" statements match, the
code within the "default" block is executed.

Example of switch Statement in C

Here is an example how the switch statement in C works.

​ C

#include <stdio.h>

int main() {
int x = 2;

switch (x) {

case 1:

printf("x is 1");

break;

case 2:

printf("x is 2");

break;

case 3:

printf("x is 3");

break;

default:

printf("x is not 1, 2, or 3");


break;

return 0;

Output

x is 2

Explanation:
In the above example, the "switch" statement checks the value of "x". Since "x"
is equal to 2, the code within the second "case" statement is executed, and the
message "x is 2" is printed to the console.

11. LOOPS
Loops in programming are used to repeat a block of code until the specified
condition is met. A loop statement allows programmers to execute a statement
or group of statements multiple times without repetition of code.

C
// C program to illustrate need of loops

#include <stdio.h>

int main()

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");


printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

printf( "Hello World\n");

return 0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
There are mainly two types of loops in C Programming:

1. Entry Controlled loops: In Entry controlled loops the test condition is

checked before entering the main body of the loop. For Loop and

While Loop is Entry-controlled loops.

2. Exit Controlled loops: In Exit controlled loops the test condition is

evaluated at the end of the loop body. The loop body will execute at

least once, irrespective of whether the condition is true or false.

do-while Loop is Exit Controlled loop.

Loop
Description
Type
first Initializes, then condition check, then executes the body
for loop
and at last, the update is done.

while first Initializes, then condition checks, and then executes the
loop body, and updating can be inside the body.

do-while do-while first executes the body and then the condition check is
loop done.

for Loop
for loop in C programming is a repetition control structure that allows
programmers to write a loop that will be executed a specific number of times.
for loop enables programmers to perform n number of steps together in a single
line.

Syntax:
for (initialize expression; test expression; update expression)
{
//
// body of for loop
//
}

Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
In for loop, a loop variable is used to control the loop. Firstly we initialize the
loop variable with some value, then check its test condition. If the statement is
true then control will move to the body and the body of for loop will be
executed. Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.

● Initialization Expression: In this expression, we assign a loop variable

or loop counter to some value. for example: int i=1;

● Test Expression: In this expression, test conditions are performed. If

the condition evaluates to true then the loop body will be executed

and then an update of the loop variable is done. If the test expression

becomes false then the control will exit from the loop. for example,

i<=9;

● Update Expression: After execution of the loop body loop variable is

updated by some value it could be incremented, decremented,

multiplied, or divided by any value.

for loop Equivalent Flow Diagram:


Example:

C
// C program to illustrate for loop

#include <stdio.h>

// Driver code

int main()

int i = 0;

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

{
printf( "Hello World\n");

return 0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop
While loop does not depend upon the number of iterations. In for loop the
number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition. If the test condition
will become false then it will break from the while loop else body will be
executed.

Syntax:
initialization_expression;

while (test_expression)
{
// body of the while loop

update_expression;
}

Flow Diagram for while loop:


C

// C program to illustrate

// while loop

#include <stdio.h>

// Driver code

int main()

// Initialization expression

int i = 2;
// Test expression

while(i < 10)

// loop body

printf( "Hello World\n");

// update expression

i++;

}
return 0;

Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the
do-while loop test condition which is tested at the end of the body. In the
do-while loop, the loop body will execute at least once irrespective of the test
condition.

Syntax:
initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);
C
// C program to illustrate

// do-while loop

#include <stdio.h>

// Driver code

int main()

// Initialization expression

int i = 2;
do

// loop body

printf( "Hello World\n");

// Update expression

i++;

// Test expression

} while (i < 1);


return 0;

Output
Hello World

Above program will evaluate (i<1) as false since i = 2. But still, as it is a


do-while loop the body will be executed once.

Loop Control Statements


Loop control statements in C programming are used to change execution from
its normal sequence.

Name Description

the break statement is used to terminate the switch and


break
loop statement. It transfers the execution to the statement
statement
immediately following the loop or switch.

continue continue statement skips the remainder body and


statement immediately resets its condition before reiterating it.
goto goto statement transfers the control to the labeled
statement statement.

Infinite Loop
An infinite loop is executed when the test expression never becomes false and
the body of the loop is executed repeatedly. A program is stuck in an Infinite
loop when the condition is always true. Mostly this is an error that can be
resolved by using Loop Control statements.

Using for loop:

// C program to demonstrate infinite

// loops using for loop

#include <stdio.h>

// Driver code
int main ()

int i;

// This is an infinite for loop

// as the condition expression

// is blank

for ( ; ; )

printf("This loop will run forever.\n");

}
return 0;

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

Using While loop:

// C program to demonstrate

// infinite loop using while

// loop

#include <stdio.h>
// Driver code

int main()

while (1)

printf("This loop will run forever.\n");

return 0;

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

Using the do-while loop:

C
// C program to demonstrate

// infinite loop using do-while

// loop

#include <stdio.h>

// Driver code

int main()

do

{
printf("This loop will run forever.\n");

} while (1);

return 0;

Output
This loop will run forever.
This loop will run forever.
This loop will run forever.
...

You might also like