Blog (mostly math)

BITS-1 Programming

Link to Coursera - BITS BSc Computer Science program: Link.

Note that the individual courses in this program are available under Coursera +.

Course - 1 : Introduction to Programming

Link to the course: Link.

All rights of the content go to BITS Pilani.

Refs:

  • “Computer Fundamentals and C Programming” by S. Das.

ROUGH NOTES (!)
Updated:7/7/2026

[Introduction to Computers]

Components of a Computer

Consider the inside of a desktop system.

We have the Motherboard:

The Motherboard hosts the Central Processing Unit (CPU) or the Processor. (In the pic, the CPU is covered by the fan).

The Processor has two important units:

  • Arithmetic and logical unit: It does all the operations.

  • Control unit: It does all the controlling mechanisms.

We see two slots:

The slots are for holding the memory unit, which is used for storing data while the processor is under execution.

We also see buses/paths:

A device can use buses or paths to communicate with the CPU or with other devices.

We also have SMPS (which stands for Switched-Mode Power Supply):

The SMPS regulates the power supply to the system.

We can also use an external hard disk:

We can use an external hard disk for permanent storage of data.

Other devices can also be connected using PCI (Peripheral Component Interconnect) slots.

How does a Computer work?

A computer is a device that takes data as input, does some operations on it based on a set of instructions called a program, and then returns an output.

Eg: Suppose you are using a Word Editor. Suppose you want to change the font of your text. To do that, you first give an input. You select the lines you want to change by using the mouse, and select the right font you want to apply. The computer does the task and you can see the output.

Eg: Suppose you are playing a video game. Suppose you want to make a character jump on the screen. You have your input device, a joystick, you make certain movements, and you see the output on the screen.

The inputs to a computer can come from different devices (eg, mouse, keyboard, scanner, microphone, etc).

The output of a computer can be presented in various forms (it could be written onto a new file, or sent to a printer, or sent to the display device, or sent to a speaker, etc).

All these physical devices, which we can see and touch, are called hardware.

The set of instructions we give to a computer to do a specific task is called software.

[What is Computer Programming?]

Computer Programming is the art of writing source code (or program) which a computing system can understand eventually, to perform a task.

Eg: We use mobile phones and use many different apps. Every single mobile app is a result of extensive programming.

Eg: An online educational platform like Coursera requires a lot of programming.

Eg: E-commerce portals require a lot of programming.

Eg: Programming is used in medicine. Consider opthalmology. You go to an opthalmologist, and he/she looks at your retinal fundus image. The doctor might use some AI based tools to identify specific lesions in the image.

Eg: Programming is used in physics simulations.

Knowing the art of programming helps in almost every discipline.

Programming is a product in itself - one can create a career based on programming, unlike other courses.

Eg: Animation of a Human Head. The input is a sequence of MRI and CT scans.

Eg: Visualising collagen fibers in a tissue. The input is an image from a special microscope.

Eg: Studying 3D morphology (shape) of cell nuclei. Identifying specific cells of interest, extracting the cell nucleus and reconstructing in 3D.

Eg: Showing the 3D trajectory of a ball in sports (cricket, tennis).

Eg: Computing cell properties (area, perimeter, etc).

Eg: Computers can be used in pedagogy. Consider online educational platforms.

How to write a Computer Program

A Computer can only understand the language of 0s and 1s.

We cannot use natural language (like one’s mother tongue) for programming since they are ambiguous, redundant, complex.

Eg: “Time flies like a rocket” could mean for example:

  • Time is going so fast.

  • In a world of insects, Mr Time flies like a rocket.

Writing programs directly in the machine language of 0s and 1s can be very difficult.

A Programming Language acts as an abstraction level between humans and computers.

C Language

The C language is a programming language.

It is a general purpose, high level (closer to the user) programming language.

The language is independent of the platform (Mac, Windows, etc.)

It is a compiler based language. (The language makes uses of english like constructs. A conversion from high level language to machine level language of 0s and 1s is made possible by a special software called a compiler.)

[What is an Operating System?]

Program vs Software

A program is a set of instructions we give to a computer in a specific programming language to accomplish a specific task.

Software is a coollection of programs.

There are types of software:

  • System software
    • Essential software
    • Helps manage different devices
    • Acts as an intermediary between user and hardware devices
    • Gives a conducive platform or environment to other type of software
    • Most important system software is Operating System (OS)
  • Application software
    • Non-essential software
    • Domain-specific software, meant for specific tasks
    • Spreadsheet software, Browser, Video games, etc.

A computer has different hardware resources:

  • Input devices (eg mouse, keyboard)
  • Output devices (eg speaker, monitor, printer)
  • CPU
  • Memory

A user might want to use these resources. Whatever request a user makes has to go through the OS, which is considered as the chief of system software.

OS is also called a Resource Manager.

Examples of OS: iOS, Android, CentOS, Linux, Windows, etc.

OS is a layer of software interposed between the application program and the hardware. It manages everything on your computer, including hardware; it is a resource manager. It is responsible for executing a program on the CPU.

[How are Programs Executed?]

Types of Memory

  • Volatile Memory aka Random Access Memory (RAM)
    • Temporary storage to run any program
  • Non-Volatile Memory
    • Hard disks, Flashdrives, etc.

Basic Layout of Computer Hardware

What happens to the program?

Your program when saved gets stored on the disk.

What happens to your program when it is executed?

Assume compilation is done, that is the compiler has translated the program into machine language of 0s and 1s.

Now the OS loads the program into the RAM.

Then (when it gets its chance) the program is executed on the CPU line by line.

A program under execution is known as a process. (Open the task manager and look at the processes).

[Introduction to Flowcharts and Algorithms]

An algorithm is a collection of finite unambiguous steps to solve a computational problem.

A flow chart is a pictorial representation of an algorithm.

Any structured programming language supports three constructs:

  • Sequencing
    • Executing a set of statements in a sequential order.
  • Decision making
    • Choose from many alternatives.
  • Repetition
    • Executing one or a group of statements in a loop, iteratively.

Algorithm

  1. Begin.

  2. Input: ${ a, b . }$

  3. Sum ${ \leftarrow }$ ${ a + b . }$

  4. Output Sum.

  5. End.

Flowchart

[Illustrating Decision Making using a Flowchart/Algorithm]

Algorithm

1 Begin.

2 Input: ${ n . }$

3

if n > 0
    print "n is positive" 
else
    print "error"

4 End.

Flowchart

[Creating a Flowchart or Algorithm for Iteration]

Iterative Constructs

An iterative construct means having a statement or a group of statements inside a loop and doing it repeatedly.

Iterative constructs are essential to solve problems that are repetitive in nature.

Eg: Suppose we want to compute the sum ${ 1 + \ldots + n . }$

Algorithm

1 Begin.

2 Input ${ n . }$

3 ${ i \leftarrow 1, }$ ${ \text{sum} \leftarrow 0 . }$

4

while i <= n
    sum <- sum + i 
    i <- i + 1 

5 Output ${ \text{sum} . }$

6 Stop.

Flowchart

[Essential elements of a C program]

Eg: Sum of Two Numbers

1 START

2 Input the numbers num1, num2

3 Initialize sum = 0

4 Set sum = num1 + num2

5 Print sum

6 END

C Program to compute sum of two numbers

/* myfirst.c: to compute the sum of two numbers */ 
#include<stdio.h> //Preprocessor directive 
/*Program body*/
int main() 
{
    int a, b, sum; //variable declarations 
    printf("Please enter the values of a and b:\n");
    scanf("%d %d", &a, &b);
    sum = a + b; //the sum is computed 
    printf("The sum is %d\n", sum);
    return 0; //terminates the program
}

Here stuff in /* .... */ and //... are comments.

Header files

Here

#include<stdio.h>

is a directive to include the contents of the header file stdio.h, in the program. (As soon as a pre-processor comes across #include<stdio.h> it will replace this line by contents of the header file.)

Functions

printf() function allows to print something on screen.

scanf() function allows to read input into a C program.

Comments

/* This is a multi-line 

comment */ 
// This is a single line comment 

Handling errors

Compile-time errors:

When a statement fails to conform to the rules of the C language.

Eg: int a, b, sum misses a ; and raises a compile time error.

Run-time error:

Fails when program is executed after successful compilation

Eg: a = b / c // when c tames a value of zero

Semantic error:

Code compiles and executes, but doesn’t behave as intended.

Eg: Using = instead of ==.

[Executing a C Program in Coursera Labs]

1 Write the program and save it Where does it get saved? DIsk 2 Compile the program to generate its executable Where will the executable be saved? Disk 3 Run the executable Where will the executable run? Executable is loaded into RAM and executed line by line on the CPU

Compiling C program

Say our C program is stored in myfirst.c.

To generate the executable file, navigate to the directory where myfirst.c is stored and run the following command:

gcc myfirst.c 

Files generated:

a.out 

The above process is known as compilation of the program to generate the executable a.out.

To run the executable:

./a.out 

Eg:

#include<stdio.h> 

int main()
{
    float a, b, c, average; 
    printf("Enter values for a, b, and c : ");
    scanf("%f %f %f", &a, &b, &c);
    average = (a + b + c)/3; 
    printf("Average = %f\n", average);
    return 0;
}

[Basic Unix Commands in Coursera Labs]

Unix Operating System

Unix OS is developed using C language at the Bell Labs in 1969.

Its a multitasking and multiuser system.

Layers of Unix OS

Kernel

  • Heart of the OS

  • Interacts with hardware

  • Manages memory, task scheduling, and files

Shell

  • Utility that processes your requests

Commands and utilities

  • cp, mv, mkdir, ls, and so on

Files and Directories

  • Data organized as files and then into directories

Files and Directories

Hierarchical Structure

Root (Denoted by /)

Home

Basic Unix Commands

pwd: Displays the path of present working directory

ls: Lists the contents of the directory

cd: Changes directory of the shell

mkdir: Make a new directory

rmdir: Removes empty directory

cp: Copy contents of a file

mv: Move one or more files from one location to another or rename file or directory

Eg: Make a sum.c file with program

#include<stdio.h> 

int main()
{
    int a = 5, b = 6, c; 
    c = a + b; 
    printf("\n a + b = %d\n", c);
}

Now run gcc sum.c and then ./a.out.

[Variables, Constants, and Datatypes in C]

Program Data

Program data occurs in the form of

  • Constants. Eg 25, 3.14.

  • Variables.

Every data item has an associated type.

Variables

A variable is a named memory location.

(We can access a specific location in memory, and we can modify the contents in that specific location.)

Variable name can begin with a letter or underscore (esp it cannot begin with a digit), and comprise of letters, digits or underscore. Names are case sensitive.

Eg: int a; int _count; int A;

Certain reserved keywords cannot be used as variable names (like continue, if, short, union, return, ...)

A variable must be declared before its use.

Eg: int age, quantity, price; /* declares three variables that can store integer values */

To initialize a variable, use =.

Eg: age = 21; (The memory location of the variable age will be used to store the value 21.)

age = 43; (The initial value of 21 will be erased and overwritten with the value 43.)

Declaration and initialization can be combined in one statement.

Eg: int amount1 = 45, amount2 = 500, amount3 = 999;

An uninitialized variable is simply junk (in general).

Data Types

C is a typed language. Every data item has a type associated with it.

Examples of declaring variables:

int num1;

float cgpa; (Can store numbers like 9.85)

char initial; (Can store a single character)

Fundamental Data Types in C

Integer (short, int, long, long long)

Floating point (float, double, long double)

Character (char)

Fixed size of each data type / sub-type.

Constants

Fixed values used in a program, and their value never changes in a program.

C specifies a default type for a constant.

Eg: 25 (default int), 35.65 (default double) have specific types associated with each.

Default for an integer is int. If a constant doesn’t fit in int, the next higher type is tried.

Suffixes can be used. Eg: U or u for unsigned, L or l for long. Like 25u.

Default for floating point number is double.

Suffix F or f demotes it to float. Suffix L or l promotes it to long double.

Declaring constants

There are two ways.

1 Using const qualifier

const float pi = 3.14f; //pi is read-only

2 Symbolic constants using #define

#define PI 3.24f //no semi-colon used

Eg:

#include<stdio.h> 

#define X 10 //always written before int main() 

int main() 

{ 
    ...some code...
}

[Where and How are Program Data Stored?]

Variables in Main Memory

#include <stdio.h> 

int main()
{
    int num1, num2, num3; 
    num1 = 2; 
    num2 = 4; 
    num3 = num1 + num2; // computing the sum of num1 and num2 
    printf("The sum is: %d \n", num3); // printing the sum 
    return 0; 
}

The program has 3 variables num1, num2, and num3.

Where are these variables stored?

Execution of a Program

Look at the Main Memory Only

Space allocated to the entire program

contains

Space allocated to main() function

and the declared variables are stored in this space.

[Variable Types and Their Storage]

Size of Variables

Every variable in a program occupies space in the memory depending on its type.

For example, variable of type int occupies either 2 or 4 bytes depending on the specific compiler you are using.

What is this byte?

Organization of Main Memory

Main Memory is typically a table of memory location of 8 bits.

A bit stores a value of 1 or 0 (True or False).

A set of contiguous 8 bits is called a byte.

Each location (of 8 bits) is associated with an address.

(In the above pic, 1000, 1001, etc. are example addresses.)

Storing int in Main Memory

If int variables are 4 bytes size (or 32 bits), then each int variable occupies 4 contiguous locations in the memory.

short int may occupy 2 bytes.

long int may occupy 8 bytes.

Types of Integer Variables

Knowing the Size of Data Types

How do we know the size of a data type for our C compiler?

Use sizeof() operator.

Eg:

printf("Size of int is %lu bytes", sizeof(int)); 

/* prints size of int in bytes. The format specifier 
is unsigned long int (%lu) on gcc compiler */ 

By default, integer data type is signed.

Types of Floating-Point Numbers

While integers are classified by size, floating-point numbers are classified by precision.

Eg: 3.14 and 3.1415 have different precision.

[Character Types in C]

Storing Characters in C

If everything is in binary, how do we deal with characters?

Use character-encoding schemes, such as ASCII (American Standard Code for Information Interchange).

ASCII defines an encoding for representing English characters as numbers, with each letter assigned a number from 0 to 127.

8 bit ASCII is used, so the character data type is one byte wide.

Computing with char

char ch1 = 'A', ch2; 

/* ch1 is internally stored as the ascii code 65 */

printf("%c\n", ch1); 

/* It prints A */

/* Suppose we said printf("%d", ch1); it prints 65 */

ch2 = ch1 + 1; 

print("%c\n", ch2); 

/* It prints B */

Nonprintable char

Escape sequences: backslash followed by the lowercase letter.

Eg: \n, \t, \f, etc.

To print special characters like ' or " or \ use a preceding \.

Eg: \' and \".

char vs String

“Welcome” is a string, which is basically a bunch of characters put together.

A string in C is an array of chars.

You will study about arrays and strings in greater detail later.

Note the use of double quotes. "hello", 'A', 'y'.

The distinction between ‘A’, “A”, ‘Axe’ (this doesn’t make sense) and “Axe” (this is a string).

[Type Conversions in C]

Implicit Conversion

Eg: Consider 21314 + 22.

The system performs 21314 + 00022.

Eg:

short x = 2; 
int y = 4; 

To perform x + y, the short x is converted to an int x. The result is then computed as the int 6.

Type Conversions

1 Implicit Conversions.

If either operand is a long double, convert the other into a long double.

Otherwise, if either operand is a double, convert the other into double.

Otherwise, if either operand is float, convert the other into float.

Otherwise, convert char and short to int.

Then, if either operand is long, convert the other to long.

2 Explicit Conversions.

(Also known as coercion or typecasting.)

Eg: float A = 100/3; Output: 33.000000

float A = 100/3.0; Output: 33.333333

(Here the int 100 is promoted to a double 100.0 and the division is performed.)

Eg: int A = 10;

A = A + 'B'; Output: 76

(Here ‘B’ is type converted to integer.)

Eg: float X = 0.2; double A = X/0.1; Output: 2.000000

Explicit Type Conversion (Type Casting)

Eg: Conversion of integer to a float variable.

int a = 10; 
float f = (float) a; 

/* Here (float) tells to promote the value to a float */

Eg: Conversion of integer to a char variable.

int a = 20; 
char ch = (char) a; 

The above conversion is valid as after all characters are integer values of ASCII code.

[Operators and Expressions in C]

Types of Operators

  • Unary

  • Binary

Eg: Consider 2 + 3. Here 2, 3 are operands, and + is an operator. Here + is a binary operator.

Eg: 2 * 4, 8 - 3, 15/4 are all expressions involving binary operators.

Eg: Consider -5. It can be thought of as the operator “-“ operating on the operand “5”. Here “-“ is a unary operator.

We also have Expressions.

Eg: a + b/7.

Eg: b*b - 4*a*c

Types of Operators

1 Arithmetic Operators.

Eg: +, -, *, /, %

2 Relational Operators

Eg: x > y (This expression will result in True or False.)

Eg: >, <, >=, <=, ==

3 Logical Operators

Eg: Let x represent `Finished homework.”

Let y represent Not raining outside.

Suppose only when both are True we want to go out and play.

Hence we can consider x &&y . Here && is the logical and operator.

4 Assignment Operators

Eg: x = 5; Here x is assigned the value 5.

[Arithmetic and Assignment Operators]

Arithmetic Operators

Used for performing arithmetic operations.

Binary arithmetic operators

  • Takes two operands as input

  • *, /, %, +, -

Eg:

2 + 3 = 5 
2 - 3 = -1 
2 * 3 = 6 
2/3 = 0 (This is integer division) 
2 % 3 = 2 (This is modulo operator) 

Eg:

int a = 31, b = 10; 

a + b (gives 41) 

a - b (gives 21) 

a / b (gives 3) 

a % b (gives 1) 

a * b (gives 310) 

Eg:

float c = 31.0, d = 10.0; 

c + d (gives 41.0) 

c - d (gives 21.0) 

c / d (gives 3.1) 

c % d (NA) 

c * d (gives 310.0) 

Assignment Operator I

y = 5; // assigns the value of 5 to the variable (or memory location) y
 x = y; // assigns the value of y to the variable (or memory location) x 

Assignment Operator II

x op= y is the same as x = x op y where op can be any binary arithmetic operator.

Eg: x += 2 is same as x = x + 2.

Eg:

int x = 43, y = 7; 

/* Here x would store 43 and y would store 7 */

x += y ; 

/* Now x would store 50 and y would store 7 */

Eg:

int x = 43, y = 7; 

/* Here x would store 43 and y would store 7 */

x *= y 

/* Now x would store 301 and y would store 7 */

[Operator Precedence and Associativity]

Operator Precedence

In an expression with multiple operators, the order of evaluation of operators is based on the precedence level.

Eg: 2+3*6. Here * has a higher precedence than +. Hence * will be done first and then + will happen.

Hence 2+3*6 -> 2+18 -> 20.

To be clear we could’ve written 2+(3*6).

Here is a precedence table:

Eg: x = 2+3. Here + has a higher precedence than =. Hence the addition will occur first and then the assignment.

Associativity

In an expression with multiple operators, the order of evaluation of operators is based on the precedence level.

Operators with the same precedence work by rules of associativity.

Eg: Consider 2*3/6. The associativity is left to right (see the table), hence we have 2*3/6 -> (2*3)/6 -> 6/6 -> 1.

Order of Evaluation of Operands

In an expression with multiple operators, the order of evaluation of operators is based on the precedence level.

Operators with the same precedence work by rules of associativity.

C does not define the order in which the operands of an operator will be evaluated.

Eg: Consider opd1 op opd2. We dont know which of the operands opd1 and opd2 will be evaluated first.

[Unary Arithmetic Operators]

Arithmetic Operators

Binary: *, /, %, +, -

Unary: ++, --

Eg: x++ means x = x + 1.

Eg: ++x means x = x + 1.

There is a subtle difference between x++ and ++x, which we will see shortly…

Similarly we have x-- and --x.

Unary Arithmetic Operator

Can be used as a prefix or postfix.

Prefix: For example ++count. “Change value and then use”.

int count = 5; 

/* Here count contains value 5 */

x = ++count;

/* Here count is updated to contain 6, and x contains this value (namely 6) */

Postfix: For example count++. “Use and then change value”.

int count = 5; 

/* Here count contains value 5 */ 

x = count++; 

/* Here x contains the value of count (namely 5), and then value in count is updated to 6  */

Suppose we have 

int count = 5; 

Now... 

"x = ++count;" 

seems to be same as the lines 

"
count = count + 1; 
x = count;
"

Also

"x = count++;" 

seems to be same as the lines 

"
x = count; 
count = count + 1;
"

Increment and Decrement Operators

Prefix:

++<variable_name> / --<variable_name> 

Eg:

int A = 10; 
printf("A is %d\n", ++A); 

/* We get A is 11 */ 

printf("A is %d", --A); 

/* We get A is 10 */ 

Postfix:

<variable_name>++ / <variable_name>--

Eg:

int A = 10; 
printf("A is %d\n", A++);

/* We get A is 10 */ 

printf("A is %d\n", A--)

/* We get A is 11 */

Relational and Logical Operators

Relational operators result in a True or False.

a==b -> checks whether a is equal to b

a!=b-> checks whether a is not equal to b

a<b -> checks whether a is less than b

a>b -> checks whether a is greater than b

a<=b -> checks whether a is less than or equal to b

a>=b -> checks whether a is greater than or equal to b

All are of the same precedence and are left to right associative

Logical Operators

expr1 && expr2 -> Returns True, when both operands are non-zero

expr1 || expr2 -> Returns True when at least one of the expressions is non-zero

!(expr) -> If (expr) is non-zero, then !(expr) returns zero.

All are of the same precedence and are left to right associative

Logical operators result in True or False

True or False in C

Anything nonzero is considered True.

Zero is considered False.

Eg:

It seems 

15 > 10 > 5; 

evaluates to False, because 

15 > 10 > 5 -> (15 > 10) > 5 -> 1 > 5 -> 0 

Although mathematically 

15 > 10 > 5 

is a perfectly valid inequality. 

[Operators Examples]

Write a C program to convert a given temperature from Celcius scale to Fahrenheit scale.

Mathematically,

F = C*1.8 + 32

Here is the temperature.c code:

#include<stdio.h> 

int main() 
{
    float celsius, fahrenheit; 
    printf("Enter the temperature in celsius scale:"); 
    scanf("%f", &celsius);
    fahrenheit = (celsius * 1.8) + 32;
    printf("\nCelsius degree = %f and Fahrenheit scale = %f\n", celsius, fahrenheit);
    return 0;
}

To compile we do gcc temperature.c and to run we do ./a.out.

[Statements and Blocks in C]

Statement

Statement:

An expression followed by a semicolon (;)

Examples of three statements:

c = a + b; i++; // two statements 
printf("Hello World");

Eg: 25;

Block statement:

Set of statements enclosed inside a set of brace { and }.

Eg:

{
    c = a + b; 
    c++; 
    printf("c is %d", c);
}

[The If statement in C]

Control Flow: Branching

Different set of instructions gets executed depending on the outcome of a conditional expression.

Writing a conditional expression:

Using relational operators such as ==, >=, <=, !=, <, >

Using logical operators &&, ||, !

Eg: a>b

Eg: a>b && c<d

Eg: (x + y >= 10)

Eg: (marks >= 90 && marks <= 100)

Control Flow: Branching

Outcome of the condition:

Non-zero or true

Zero or false

Eg:

int x = 5, y = 10; 
(x + y <= 20) // Value is True 

Eg:

int Marks = 95; 
(Marks <= 100 && Marks >= 90) // Value is True 

Branching: If statement

if (condition) 
    statement; 
if (condition)
{
    statement_1; 
    ...
    statement_n; 
}  

Statement or block of statements gets executed only if the condition evaluates to true or non-zero.

Eg:

int main() 
{
    int a; 
    printf("Enter a number ");
    scanf("%d", &a);
    if (a > 0) 
    {
    printf("Number is positive\n");
    }
    printf("Rest of the program");
    return 0;
}

Output_Case_1:

Enter a number 
10 
Number is positive 
Rest of the program 

Output_Case_2:

Enter a number 
-5 
Rest of the program 

[The If-Else Statement in C]

Branching: If-Else Statement

if (condition) 
{
  // if-block of statements 
} 
else
{
  // else-block of statements
}
if (condition) 
  // statement; 
else 
  // statement; 

If the condition inside the if parentheses is true then if-block of statements is executed, else else-block of statements is executed.

Eg:

int a; 
printf("Enter a number ");
scanf("%d", &a);
if (a > 0) 
{
  printf("Number is positive\n");
}
else 
{
  printf("Number is either negative or zero\n");
}
printf("Rest of the program");

Output_Case_1:

Enter a number 
5 
Number is positive 
Rest of the program 

Output_Case_2:

Enter a number 
-5 
Number is either negative or zero 
Rest of the program

Branching If-Else Ladder

if (condition1){
//These statements would execute if the condition1 is true 
}
else if (condition2){
// These statements would execute if the condition2 is true 
}
else if (condition3){
// These statements would execute if the condition3 is true 
} 
else {
/* These statements would execute if none of the previous conditions is true */
}

Eg: Write a C program using if-else to find the grade of a student based on the following conditions:

  1. Marks greater than 90 implies grade A
  2. Marks between 80 and 90 implies grade B
  3. Marks between 70 and 80 implies grade C
  4. Else, the grade is Fail
if(Marks > 90)
    printf("Grade is A");
else if(Marks <= 90 && Marks >= 80)
    printf("Grade is B");
else if(Marks <= 80 && Marks >= 70)
    printf("Grade is C");
else 
    printf("Grade is FAIL");

[Nested If Else Statements]

Branching: Nested If-Else Statements

If one or more if and/or else statements is/are present inside the body of another “if” or “else”

if (condition1){ 
    if (condition2) // statement or block of statements for if 
    else // statement or block of statements for else 
} 
else{
    if (condition3) // statement or block of statements for if 
    else // statement or block of statements for else 
} 

Eg: Code Snippet to compute the largest of three numbers.

#include<stdio.h> 
int main() {
int a, b, c; 
printf("Enter the numbers ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) 
{
if (a > c) 
    printf("A"); 
else
    printf("C");
}
else 
{
if (b > c) 
    printf("B is the largest");
else 
    printf("C is the largest");
}
printf("End of the program");
return 0;
}
comments powered by Disqus