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:19/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;
}

[Switch Statement in C]

The Switch Statement is a multi-way decision that tests whether an expression matches one of several constant integer values and branches accordingly.

Syntax:

switch (expr) {  
case const-expr1: statements1 
                  break; 
/* break is used to come out of switch statement */
case const-expr2: statements2
                  break;
...
default:          statements
                  break; 

}

Eg:

int language = 10; 

switch (language) {
    case 1: printf("C#\n");
            break; 
    case 2: printf("C\n");
            break; 
    case 3: printf("C++\n");
            break; 
    default: 
            printf("Other programming\n");
}

The output is

Other programming

Eg:

int number = 5; 
switch (number) { 
    case 1: 
    case 2: 
    case 3: 
        printf("One, Two, or Three.\n");
        break; 
    case 4: 
    case 5: 
    case 6: 
        printf("Four, Five, or Six.\n");
        break; 
    default: 
        printf("GreaterthanSix.\n");
}

Here it jumps to case 5. Since nothing is there in case 5, it will go to the next fallthrough case, namely case 6.

The output is

Four, Five, or Six. 

[Loops in C]

Looping: Basics

Why do for a loop?

  • Due to repetitive nature of a problem

Eg:

1 Print all numbers from 1 to 500

2 Compute the average mark of the students in a class of size 100

3 Sum all the digits on a positive integer

Note that a loop must terminate!

How does a Loop work?

[While Loop in C]

The While Loop

while (exp is true) 
    statement; 

OR

while (exp is true) 
{
    statement1; 
    statement2; 
    ...
}

Control Expressions

while (answer == 'Y') 
while (count) 
/* True if nonzero and False if zero */
while (5) 
/* Infinite loop unless you come out of while loop */
while (base>0 && power>=0) 

Eg:

int var = 1; 
while (var <= 3)
{
    printf("%d", var++);
}
printf("While loop over");

The output is

123 While loop over

A Null Body

while(num>0);

is different from

while(num>0)

We shouldn’t use a semicolon.

Eg:

Write a program to calculate the sum of first N positive integers. You may define the value of N using pre-processor directive.

Ans: Here is sum.c.

#include<stdio.h> 
#define N 10 
int main() 
{
    int index = 1, sum = 0; 
    while(index <= N)
    {
        sum += index;
        index++; 
    }
    printf("Sum of %d positive integers is %d", N, sum);
    return 0;
}

[While Loop: Example 1]

Write a program to ensure that the user enters a positive integer.

  • Every time a negative number or a zero is input, give appropriate message.

  • Once a positive integer is entered, print the square of that number.

Ans: Here is positive.c.

#include<stdio.h> 
int main(){ 
    int num; 
    printf("\nEnter a positive integer: ");
    scanf("%d", &num);
    while(num <= 0) 
    {
        printf("\n Please enter a positive integer");
        scanf("%d", &num);
    }
    printf("\nSquare of %d is %d", num, num * num);
    return 0;
}
    

[While Loop: Example 2]

Nesting of While Loops

while (exp1)
{
    ...
    while (exp2) 
    {
        ...
    }
}

Nested While Loops: Example

Assume a class of size N.

Take as input three subject scores for each student.

Print the average marks obtained by each student.

Ans: Here is avg_marks.c

#include<stdio.h> 
#define N 4 
int main() 
{
    int index = 1;
    while (index <= N) 
    {
        float avg;
        int sum = 0; 
        int j = 1, marks; 
        while (j <= 3) 
        {
            printf("\nEnter marks for subject %d ", j);
            scanf("%d", &marks);
            sum += marks;
            j++;
        }
        avg = sum / 3.0;
        printf("Average of student %d is %f", index, avg);
        index++;
    }
    return 0;
}

I guess we can change the inner printf statement to be clearer.

#include<stdio.h> 
#define N 4 
int main() 
{
    int index = 1;
    while (index <= N) 
    {
        float avg;
        int sum = 0; 
        int j = 1, marks; 
        while (j <= 3) 
        {
            printf("\nEnter marks for student %d subject %d ", index, j);
            scanf("%d", &marks);
            sum += marks;
            j++;
        }
        avg = sum / 3.0;
        printf("Average of student %d is %f", index, avg);
        index++;
    }
    return 0;
}

[Break and Continue Statements with Examples]

The Break Statement

Forces to come out of the immediately enclosing loop.

The Continue Statement

Skips the subsequent statements in the body of the immediately enclosing loop and proceeds to its next iteration.

Eg: Write a program to calculate the sum of positive numbers entered by the user.

  • When a negative value is entered ignore it; prompt the user to enter a positive integer.

  • When zero is entered, terminate the loop.

  • Display the sum of the positive numbers entered by the user.

Ans: Here is break_continue.c

#include<stdio.h> 
int main() 
{
    int num; 
    int sum = 0; 
    while (1)
    {
        printf("\nEnter a positive number: ");
        scanf("%d", &num);
        if (num < 0)
            continue;
        if (num == 0)
            break;
        sum += num;
    }
    printf("\nThe sum of all positive numbers entered is %d\n", sum);
    return 0;
} 

[Writing a For Loop in C]

The For Loop

for (initialization; condition; increment/decrement)
{
    //Statements to be executed repeatedly 
}

Initialization is executed first, and only once.

Condition is evaluated. If true, loop body is executed.

Increment/decrement is executed to update control variable.

Condition is evaluated again. The process repeats.

When the condition becomes false, the loop terminates.

The For Loop: Example

int main() 
{
    int i; 
    for (i = 1; i <= 3; i++)
    {
        printf("%d\n", i);
    }
    return 0;
}

The output is

1
2
3

Various Forms of For Loop

for (num = 10; num < 20; num = num + 2)
int num = 10; 
    for (; num<20; num++)
for (num = 10; num < 20; ) {... ... num++;}
for(;;) 
/* Its going to run infinitely unless you come out of the loop using something like break */ 
for (i = 1, j = 10; i < 10 && j > 0; i++, j--)

The For Loop: Example

Write a program to calculate the sum of first N positive integers.

#define N 5 
int main() 
{
    int sum = 0; 
    for (i = 1; i <= N; i++) 
    {
        sum += i;
    }
    printf("Sum of first %d positive integers = %d", N, sum);
    return 0;
}

[For Loop: Example 1]

Write a C program using a for loop to

  • Print the sum of all numbers from 1 through 1000 which are multiples of 3 but not multiples of 4

  • Both the ends are inclusive

#include<stdio.h> 
int main() 
{
    int i, sum = 0; 
    for (i = 1; i <= 1000; i++) 
    {
        if ( (i%3 == 0) && (i%4 != 0) )
            sum += i; 
    }
    printf("\nRequired Output = %d", sum);
    return 0;
}

[For Loop: Example 2]

Write a C program to print the following pattern using for loops:

Loop 1: Iteration on rows

Loop 2: Iteration on stars

Ans Here is pattern.c.

#include<stdio.h> 
int main() 
{
    int n; 
    printf("\nEnter the number of rows: ");
    scanf("%d", &n);

    int i_row, i_col; 
    for (i_row = 1; i_row <= n, i_row++)
    {
        for (i_col = 1; i_col <= i_row; i_col++)
        {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

[While vs For Loop]

for (init; condition; iteration)
{
    //body of the loop 
}
while (condition) 
{
    //body of the loop 
}

Usually we use for loop when we know how many times the loop is to be run, and we use while loop when we do not know how many times the loop is to be run.

[Role and Need of Functions]

What are Functions?

Functions are self-contained program segments that carry out some specific, well-defined task.

A function

  • Processes information that is passed to it from the calling portion of the program

  • Returns a single value

Every C program has one or more functions.

Functions: Example

Sum of two numbers

int sum(int a, int b)
{
    int total; 
    total = a + b; 
    return total;
}
int main() 
{
    int x, y, z; 
    x = 5, y = 4; 
    z = sum(x, y); 
    printf("Sum is %d", z);
    return 0;
}

Why are Functions Useful?

Sum of two numbers

int sum(int a, int b) 
{
    int total; 
    total = a + b; 
    return total;
}
int main() 
{
    int x, y, z, k; 
    x = 5, y = 4; 
    z = sum(x, y); 
    k = sum(10, 15); 
    printf("Sum is %d", z);
    return 0;
}

Functions make your code modular.

Functions enhance code reusability.

[Declaration and Definition of a Function]

Using Functions

Functions are

  • Declared

  • Defined

  • Called

/* myProg.c */ 
#include <stdio.h> 

int sum(int a, int b); //Function declaration 

int sum(int a, int b)
{
    int total; 
    total = a + b; 
    return total;
}

//Above is Function definition 

int main() 
{
    int x, y, z; 
    x = 5, y = 4; 
    z = sum(x, y); //Function call 
    printf("Sum is %d", z);
    return 0;
}

Function Declaration

Syntax:

<return_type> <function_name> (list-of-typed-parameters);

Eg:

float sqrt(float x);

void average(float, float);

(Here void indicates this function does not return anything).

(Here we have not mentioned names of the variables, and this is allowed in function declaration).

Function Declaration

Function declaration gives information to the compiler that the function may later be used in the program.

Declarations appear before definitions

Although optional in many compilers, it is a good practice to use it.

int average(float a, float b); 

Function Definition

Syntax:

return_type function_name (list_of_parameters) 
{
    function body 
}

Eg:

int average(float a, float b) 
{
    int avg; 
    avg = (a + b)/2; 
    return avg;
}

Eg:

void print_nums(float a, float b) 
{
    printf("Num1, Num2 are: %d, %d", a, b);
    return;
}

Matching Function Declaration and Definition

[Function Invocation and Flow of Program Execution]

Calling a Function

The functions you define can be called either from the main() function or any other function in your program.

Eg: Function sum() being called from the main() function.

/* myProg.c */ 

#include <stdio.h> 

int sum(int a, int b); 

int sum(int a, int b) 
{
    int total; 
    total = a + b; 
    return total;
}

int main() 
{
    int x, y, z; 
    x = 5, y = 4; 
    z = sum(x, y); 
    printf("Sum is %d", z);
    return 0;
}

Eg: In the below program:

Function sum() is being called from sum_call() function.

Function sum_call() is being called from main() function.

#include <stdio.h> 

int sum(int, int); 

int sum_call(int, int); 

int sum(int a, int b)
{
    int total; 
    total = a + b; 
    return total;
}

int sum_call(int m, int n)
{
    return sum(m, n);
}

int main() 
{
    int x, y, z; 
    x = 5, y = 4; 
    z = sum_call(x, y);
    printf("Sum is %d", z);
    return 0;
}

Calling a Function: Syntax

function_name (arguments_value); 

Eg:

sum(a, b);

sum(a+b, c+d);

sum(5, 6);

Matching Function Call with Function Definition

Flow of Program Execution

/* myProg.c */ 

#include <stdio.h> 

int sum(int a, int b); 

int sum(int a, int b)
{
    int total; 
    total = a + b; 
    return total;
}

int main() 
{
    int x, y, z; 
    x = 5, y = 4; 
    z = sum(x, y); 
    printf("Sum is %d", z);
    return 0;
}

The execution starts with the main function always.

The first line which gets executed is int x, y, z;

The second line which gets executed is x = 5, y = 4;

The third line which gets executed is z = sum(x, y); The function sum() is called with x,y as arguments.

The flow of execution shifts to the function sum(). The value of x gets copied into variable a, and value of y gets copied into variable b. The statement int total; is executed. The statement total = a + b; is executed. The return statement return total; is executed.

The value total is copied into the variable z.

The flow of program execution comes back to the statement z = sum(x, y).

The line printf("Sum is %d", z); is executed.

The line return 0; is executed.

The program exits.

[Pros and Cons of Functions]

Pros of Using Functions

Functions increase modularity of code (i.e. separation of concerns is achieved).

Modularity enhances code reusability as well.

Functions reduce coding time (due to reusability).

Functions make code debugging easier.

Functions improve ease of understanding.

Cons of Using Functions

Reduced execution speed

Each time a function is called, OS allocates some space in memory. This adds an additional overhead to the program. Hence the overall speed of execution of the program comes down.

[Memory Snapshot during Function Execution]

[Functions: Example 1]

Here is ex1.c

#include <stdio.h> 

int fact(int n); 

int fact(int n) 
{
    int temp = 1; 

    while (n>0)
    {
        temp = temp * n; 
        n--;
    }

    return temp;
}

int main() 
{
    print("Please enter the value of n: ");
    int n;
    scanf("%d", &n);
    int factorial = fact(n);
    printf("The factorial of n is %d\n", factorial);
}

[Functions: Example 2]

Here is ex2.c.

#include <stdio.h> 

void isPrime(int n); 

void isPrime(int n) 
{
    int i; 
    int notPrimeFlag = 0;
    for (i = 2; i < n; i++) 
    {
        if (n % i == 0) 
        {
            notPrimeFlag = 1;
            break;
        }
    }
    if (notPrimeFlag == 1) 
        printf("n is not a prime number\n");
    else 
        printf("n is a prime number\n");
    return;
}

int main() 
{
    printf("Enter a number for primality testing: ");
    int n; 
    scanf("%d", &n);
    isPrime(n);
}

[Scope and Storage Class of a Variable]

Storage Class of a Variable

A storage class of a variable tells us about the following:

  • Variable’s scope, or the sections of the code where you can access and use it

  • Location, where the variable will be stored inside the memory

  • Initial value of a variable

  • The lifetime of a variable, or how long the variable resides in the memory

Eg:

#include <stdio.h> 

int y = 5; //scope of y is complete program

void main()
{
    int a = 5; //scope of a is main()
    {
        int b = 10; //scope of b is {}
    }
    printf("a = %d, b = %d", a, b); f1();
}

void f1()
{
    int x = 2, c = 5; //scope of x and c is f1()
}

This program will lead to an error, because you cannot access b outside { and }.

Eg:

#include <stdio.h> 

void f1(int a) 
{
    printf("a = %d\n", a); 
    a = 10; 
    printf("a = %d\n", a);
}

int main()
{
    int a = 5; 
    f1(a);
    printf("a = %d", a);
    return 0;
}

The program starts execution at int a = 5.

The function f1() is called.

The first printf namely printf("a = %d\n", a); is executed. (The line printed is a = 5).

The a = 10 statement gets executed.

The seconf printf is executed. (The line printed is a = 10).

The flow returns to the main() function.

The printf statement is executed. (The line printed is a = 5, because the a local to main is 5).

The output would be:

a = 5 
a = 10 
a = 5 

Here the first two printf statements are using a that is local to f1().

Here the last printf statement is using a that is local to main().

Storage Classes for Variables in C

We have 4 storage classes in C:

  • Auto

  • Global

  • Static

  • Register

All these classes differ in:

  • Scope of the variable

  • Lifetime of the variable

  • Default value

  • Memory location

Subsequently we will learn about Auto, Global and Static variables in this course.

[Memory Layout of a C Program]

Looking at the Main Memory Only

Here

Stack Segment: Stores the memory allocated to the functions and variables declared inside the functions.

Heap Segment: Stores dynamically allocated memory.

Data Segment: Stores global and static variables.

Text segment: Stores the code we write.

[Auto and Global Variables]

Auto Variables

Variables that are declared within a code block {..} are known as auto variables or local variables.

Eg:

#include <stdio.h> 

void main() 
{
    int a; //Auto variable a local to block of main()
    a = 5; 
    {
        int b = 10; //Auto variable b local to block {}
    }
    printf("a = %d, b = %d", a, b);
    f1();
}

void f1()
{
    int a; //Auto variable a local to f1()
    a = 20;
}

Scope of an auto variable: Only the block in which it is declared can access it.

Initial value of an auto variable: By default, it contains a garbage value.

(Eg: Consider int a; in the main function. Before a is instantiated to the value of 5, a contains a garbage value).

Storage location of an auto variable: Stored in the stack segment.

Lifetime of an auto variable: Until the execution of the block finishes.

(Eg: The auto variable a in main would reside in memory as long as main block is being executed).

Global Variables:

Global variables are variables that are declared outside all the blocks (or outside all the functions).

#include <stdio.h> 

int a; //Global variable a accessible to all functions 

void f1() 
{
    printf("a = %d\n", a);
    int a = 2; 
    printf("a = %d\n", a);
}

void main()
{
    f1();
    int a = 5; 
    printf("a = %d", a);
}

The output is

a = 0 //Value of global variable a 
a = 2 //Value of variable a local to f1()
a = 5 //Value of variable a local to main()

Scope: accessible to all the functions in a program.

Initial value: default value is 0.

Storage location: stored in the data segment.

Lifetime: accessible throughout the program execution.

Variables and Functions in Memory

[Static Variables]

Static Variables

Static variables are declared using the keyword static.

Eg: static int a;

#include <stdio.h> 

void main() 
{
    int i= 0; 
    for (i = 0; i < 3; i++)
    {
        static int y = 0; 
        y += 10;
        printf("y = %d\t", y); //Here \t stands for tab 
    }
}

Scope: remains visible only to the function or the block in which it is defined.

Initial value: default value is 0.

Storage location: stored in the data segment.

Lifetime: until the program terminates, the value assigned to it remains even after the function (or block) where it is defined terminates.

Initialized only once.

Eg: LHS has auto variable and RHS has static variable.

Eg:

Static Variables in Memory

[Arrays and Their Importance]

What are Arrays?

Arrays are a fixed-size sequenced collection of elements of the same data type.

Eg:

int arr[10] declares an array (named arr) of 10 elements, each of integer type.

A single name is used to represent a large collection of items.

Eg: arr represents 10 integer elements stored in the above array.

Importance of Arrays

Easier storage, access and data management.

Easier to search.

Easier to organize data elements.

Useful to perform matrix operations.

Useful in databases.

Useful to implement other data structures.

[Defining and Accessing Arrays]

Defining Arrays

Syntax

<Storage-class> <data-type> <array_name> [<size>]

Note: Storage-class is optional.

Eg:

int count[100];

char name[25]

float temp[25]

Initializing Arrays

Few valid ways of initializing arrays in C.

Eg:

int intArray[6] = {1, 2, 3, 4, 5, 6};

Eg:

float floatArray[10] = {1.387, 5.45, 20.01};

Eg:

double fractions[] = {3.141592654, 1.570796327, 0.785398163};

Initializing Arrays during Program Execution

#include <stdio.h> 

int main() 
{
    int nums[10]; int i;
    for (i = 0; i < 10; i++) 
    {
        /* Reading an array of elements */ 
        scanf("%d", &nums[i]);
    }
}

Accessing Array Elements

int arr[10];

ith element is accessed by arr[i]. (The indices begin at 0).

Eg:

A program that takes 10 elements from the user and stores them in an array and then computes their sum.

#include <stdio.h> 

int main() 
{
    int nums[10]; int sum = 0; int i; 
    for (i = 0; i < 10; i++) 
    {
        scanf("%d", &nums[i]);
    }
    for (i = 0; i < 10; i++) 
    {
        sum = sum + nums[i];
    }
    printf("The sum is: %d", sum); 
}

[Arrays in Memory]

Addresses in Memory

Memory is like a table of contiguous memory locations each having an address:

  • Each address is represented by a string of bits. Typically 32 bits or 64 bits in modern computers.

  • Each memory location stores one byte of data.

Addresses in Main Memory

How is an Array stored in Main Memory?

Consider this program

int main() 
{
    int arr[4] = {1, 2, 3, 4};
    ...
    return 0;
}

Say size of an integer variable is 2 bytes.

To store an integer array of size 4, we need 4*2 = 8 bytes of memory or 8 contiguous locations in memory (given each location is of size 1 byte).

[Array Examples: Part 1]

Eg:

int main() 
{
    int arr[6] = {1, 2, 3, 4, 5, 6};

    for (int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

Here sizeof() returns the number of bytes occupied by a variable.

Hence sizeof(arr)/sizeof(arr[0]) gives the usual size of the array arr.

The output is:

1    2    3    4    5    6

Eg:

int main()
{
    int arr[6] = {1, 2, 3};
    for (int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output is:

1    2    3    0    0    0

Eg:

int main() 
{
    int arr[] = {1, 2, 3};
    for (int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++)
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output is:

1    2    3

Eg:

int main() 
{
    int arr[6]; 

    arr[6] = {1, 2, 3, 4, 5, 6}; //Look at this line

    for (int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++) 
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output is

Compile-time error

Note that in arr[6] = {1, 2, 3, 4, 5, 6}; we are trying to store 6 elements in one array location.

Also, the legal locations are arr[0], ..., arr[5] and arr[6] is an illegal location.

[Array Examples: Part 2]

Eg:

int main() 
{
    int arr[6]; 

    for (int i = 0; i < 6; i++) 
    {
        arr[i] = 0;
    }

    for (int i = 0; i < 6; i++) 
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output is:

0    1    2    3    4    5

Eg:

int main() 
{
    int arr[6]; 

    for (int i = 0; i < 6; i++) 
    {
        arr[i] = i; 
    }

    for (int i = 0; i < 9; i++) 
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output looks like:

0    1    2    3    4    5    3965    -8905    4872

(The others are junk values).

Eg:

int main() 
{
    int arr[6]; 

    for (int i = 0; i < 8; i++) 
    {
        arr[i] = i;
    }

    for (int i = 0; i < 6; i++) 
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output looks like:

*** stack smashing detected *** 

./a.out terminated 

0    1    2    3    4    5    Aborted (core dumped) 

(Here trying to assign arr[6], arr[7] is illegal).

Eg:

int main() 
{
    int arr[6] = {0}; 

    arr[6] = 1; 

    for (int i = 0; i < 7; i++) 
    {
        printf("%d\t", arr[i]);
    }
    return 0;
}

The output is:

*** stack smashing detected *** ./a.out terminated 

0    0    0    0    0    0    1

Aborted (core dumped)

Eg: Copying arrays.

#include <stdio.h> 

int main() 

{

    int old_value[5] = {10, 20, 30, 40, 50}; 

    int new_value[5]; 

    for (int i = 0; i < 5; i++) 
    {
        new_value[i] = old_value[i];
    }
    return 0;
}

[Arrays and Functions]

Passing Arrays to Functions

Using functions:

Write a C function that takes an int array of size SIZE and calculates (and displays) the average of all numbers.

#include <stdio,h> 

#define SIZE 9

int avg(int, int []); 

int avg(int n, int list[]) 
{
    int sum = 0; 

    for (int i = 0; i < n; i++) 
    {
        sum = sum + list[i];
    }

    return sum/n; 
}

int main() 
{
    int intArray[SIZE], average; 

    for (int i = 0; i < SIZE; i++) 
    { 
        intArray[i] = i;
    }

    average = avg(SIZE, intArray); 

    printf("Average = %d\n", average); 

    return 0; 
}

(The code seems to perform integer division for the average).

The output is 4.

Eg:

#include <stdio.h> 

#define SIZE 9 

int main() 
{
    int intArray[SIZE], average; 

    for (int i = 0; i < SIZE; i++) 
    {
        intArray[i] = i; 
        printf("%d\t", intArray[i]);
    }

    average = avg(SIZE, intArray); 

    printf("Average = %d\n", average); 

    printf("After calling avg...\n"); 

    for (int i = 0; i < SIZE; i++)
    {
        printf("%d\t", intArray[i]); 
    }

    return 0;
}

int avg(int n, int list[])
{
    int sum = 0; 

    for (int i = 0; i < n; i++) 
    {
        list[i] = list[i]*2; //Doubling  
        sum = sum + list[i]; 
    }
    return sum/n;
}

The output is:

0    1    2    3    4    5    6    7    8
Average = 8
After calling avg...
0    2    4    6    8    10    12    14    16

Arguments to Functions

Ordinary variables are passed by value.

  • Values of the arguments passed are copied into the parameters of the function.

  • Any change made to function parameters is not reflected in the original arguments.

Arrays are passed by reference.

  • Changes made to the array passed in the called function are retained in the calling function.

(More details when we study about pointers).

Can we ‘Return’ an Array from a Function?

If the array is defined inside a function, returning the array would give an error.

Eg: Consider the program

int f1() 
{
    int arr[4] = {1, 2, 3, 4};
    return arr;
}

int main() 
{
    int main_arr[] = f1(); 
    printf("First elem is: %d", main_arr[0]); 

    return 0;
}

[Linear Search]

Task: Search for an element key in the array.

Idea: Each item in the array is examined until the desired item is found or the end of the list is reached.

Code:

main() 
{
    int arr[10], index, key;
    
    printf("Enter Array elements: "); 
    for (index = 0; index < 10; index++) 
    {
        scanf("%d", &arr[index]);
    }
    
    printf("Enter search element"); 
    scanf("%d", &key); 

    for (index = 0; index < 10; index++) 
    {
        if (key == arr[index])
        { 
            printf("Element found at %d location", index);
            return;
        }
    }

    printf("Element not found");
}
  

[Sorting]

What is Sorting?

Sorting refers to ordering data in an increasing or decreasing order.

Sorting can be done by:

  • Numbers

  • Records

  • Names

Why Sorting?

Sorting reduces the time for lookup (or search).

Eg: Telephone directory.

  • Time to search for a phone number.

  • Directory sorted alphabetically vs no ordering.

Various algorithms for sorting

  • Selection sort

  • Bubble sort

  • Insertion sort

  • Merge sort

  • Quick sort

  • Shell sort

  • Bucket sort

  • Radix sort

  • and more.

Here we will deal with Selection Sort.

[Selection Sort: Part 1]

In the selection sorting algorithm, the list (or an array) is divided into two parts:

The first part is the sorted part (at the left), and the second part is the unsorted part (at the right).

Initially the sorted part at the left is empty and the unsorted part at the right is the full list.

In each iteration, the smallest element from the unsorted part of the array is added to the sorted part.

This process continues until the unsorted part of the array is empty.

Eg:

[Selection Sort: Part 2]

Implementation of Selection Sort

#include <stdio.h> 

void selectionSort(int arr[], int n)
{
    int i, j, min;

    for (i = 0; i < n-1; i++) //One by one move boundary of unsorted array
    {
        min = i; //minimum element in unsorted array

        for (j = i+1; j < n; j++) 
        {
            if (arr[j] < arr[min]) 
                min = j;
        }

        //Swap the minimum element with the first element in the unsorted array 
        int temp = arr[min]; 
        arr[min] = arr[i]; 
        arr[i] = temp;
    }
}

int main() 
{
    int a[] = {24, 36, 20, 7, 42, 19};
    int size = sizeof(a) / sizeof(a[0]);

    selectionSort(a, size); 

    return 0;
}

[Character Arrays]

Eg:

char color[3] = "RED";

Eg:

char color[] = "RED";

Note that both the character arrays are not the same.

(Here \0 is the null character).

Eg:

Write a C program that reads a 1D char array, converts all elements to uppercase, and then displays the converted array.

Hint: use toupper(ch) of <ctype.h>

#include <stdio.h> 

#include <ctype.h> 

int main() 
{
    int size, i = 0; 

    char name[50]; 

    name[0] = getchar(); //getchar() reads a character from the user

    while (name[i] != '\n')
    {
        i++; 
        name[i] = getchar(); 
    }

    /* Until you press enter, characters are taken as input. There is an upper limit of 50. */

    name[i] = '\0'; 

    size = i; 

    printf("\nName is %s", name);

    for (i = 0; i < size, i++) 
    {
        putchar(toupper(name[i])); //putchar prints to the screen
    }

    return 0;
    
}

Modifying the previous code to use scanf/printf in place of getchar/putchar:

#include <stdio.h> 

#include <ctype.h> 

int main() 
{
    int size, i = 0; 

    char name[50]; 

    scanf("%c ", &name[0]); 

    while (name[i] != '\n')
    {
        i++;
        scanf("%c ", &name[i]); 
    }

    name[i] = '\0'; 

    size = i; 

    printf("\nName is %s", name); 

    for (i = 0; i < size; i++) 
    {
        printf("%c", toupper(name[i]));
    }

    return 0;
}
comments powered by Disqus