Module - 1 An Overview of C, Expressions, Console I - O
Module - 1 An Overview of C, Expressions, Console I - O
There are no defined rules to write an algorithm. However, most authors prefer to use
English-like statements to represent the instructions.
Flowchart
● The flowchart is also a tool to represent logic.
● A flowchart helps us graphically visualize the flow of control within the sequence of
statements.
● The flowchart uses some standard notation to graphically represent logic.
Arrowed lines These are used to show the sequence of flow from
one box to another.
Algorithm
Step 1: START
Step 2: INPUT x, y and z
Step 3: Calculate sum = x + y + z
avg = sum / 3
Step 4: Display AVG
Step 5: STOP
Flowchart
2. Develop an algorithm and a flowchart to find the smallest of two numbers taken as input
from the user.
Algorithm
Step 0: START
Step 1: INPUT first number into variable A
Step 2: INPUT second number into variable B
Step 3: IF A > В THEN MAX = A ELSE MAX = В END IF
Step 4: DISPLAY MAX
Step 5: END
Algorithm
Step 1 : START
Step 2 : INPUT N
Step 3 : i = 1 and sum = 0
Step 4 : Repeat steps (a) - (b) until i <= N
(a) sum = sum + i (b) i = i + 1
Step 5 : Display sum
Step 6 : Stop
Dennis Ritchie and Brian Kernighan published The C Programming Language, now referred to as the
"K&R" book. It established the de facto standard for the C language. In that book, Ritchie and Kernighan
defined C's syntax and semantics, also called "K&R C".
● ANSI C (C89/C90): In 1983 the American National Standards Institute (ANSI) committee
completed a final draft standard known as ANSI C. After the standard development the ANSI C was
approved as a standard in 1989 (C89), then in 1990 the ANSI C standard was approved by International
Organization for Standardization (ISO) as (C90). In addition to introducing function prototypes, and
standard libraries, the ANSI C standard introduced formal libraries and stricter requirements for type
checking.
● C99 (1999): C99 introduced a variety of constructs, including: inline functions, variable-length
arrays, complex numbers, and other improvements to floating-point operations. C99 also introduced the
C Is a Middle-Level Language
Yes, C is considered a middle-level programming language because it blends features of both low-level
and high-level languages, bridging the gap between machine-level instructions and human-readable code.
C Is a Structured Language
C Is a Programmer's Language
Surprisingly, not all computer programming languages are for programmers. Consider the classic
examples of nonprogrammer languages, COBOL and BASIC. COBOL was designed not to better
the programmer's lot, not to improve the reliability of the code produced, and not even to improve
the speed with which code can be written. Rather, COBOL was designed, in part, to enable
nonprogrammers to read and to understand the program. BASIC was created essentially to allow
nonprogrammers to program a computer to solve relatively simple problems. In contrast, C was
created, influenced, and field-tested by working programmers.
C for Programmers
● C was designed by and for professional programmers
● It provides what programmers want:
○ Few restrictions
○ Block structure
○ Stand-alone functions
Legacy of C
● C is the foundation of C++ and many modern languages.
● Still recognized as one of the greatest and most influential programming languages.
Program Compilers scan the entire program in one The program is interpreted/translated one
scanning go. line at a time.
Error detection As and when scanning is performed, all One line of code is scanned, and errors
the errors are shown in the end together, encountered are shown.
not line by line.
Object code Compilers convert the source code to Interpreters do not convert the source
object code. code into object code.
Execution The execution time of the compiler is less, It is not preferred due to its slow speed.
time hence it is preferred. Usually, interpreters are slow, and hence
takes more time to execute the object
code.
Need of source Compiler doesn't require the source code It requires the source code for execution
code for execution later. later.
Documentation having details like author, date, program definition to know about the code and it is
optional.
/* Author: Authors details……..
Date: ………….. —----------> Multi-line comment
Program Definition: ………………….. */
// Author : …………………. —---------------> Single-line comment
● The main( ) function is the most important function and is a part of every C program. The
execution of a C program begins at this function.
● All functions (including main( ) ) are divided into 2 parts – the declaration section and the
statement section.
Compiling a C Program
Separate Compilation
C is a compiled language. So once a C program is written, you must run it through a C compiler that can
create an executable file to be run by the computer.
While the C program is human-readable, the executable, on the other hand, is a machine-readable file
available in an executable form. The mechanical part of running a program begins with one or more
program source files, and ends with an executable file, which can be run on a compiler. The compiler
translates the source code into an object code. The object code contains the machine instructions for the
CPU, and calls to the operating system API. However, even the object is processed with another special
program called a linker. The output of the linker is an executable or runnable file. In C language programs,
there are two kinds of source files. In addition to the main( .c ) source file, which contains executable
statements there are also header (.h) source files. Since all input and output in a C program is done through
library functions, every C program therefore uses standard header files. These header files should be
written as part of the source code for modular C programs.
In modular programming, the source code is divided into two or more source files. All these source files
are compiled separately thereby producing multiple object files. These object files are combined by the
linker to produce an executable file.
The memory layout of a program refers to how the program’s data is stored in the computer memory
during its execution. Understanding this layout helps developers manage memory more efficiently and
avoid issues such as segmentation faults and memory leaks.
A C program's memory is organized into specific regions (segments) as shown in the below image, each
serving distinct purposes for program execution.
1. Text Segment
The text segment (also known as code segment) is where the executable code of the program is stored. It
contains the compiled machine code of the program's functions and instructions. This segment is usually
read-only and stored in the lower parts of the memory to prevent accidental modification of the code while
the program is running.
The size of the text segment is determined by the number of instructions and the complexity of the
program.
2. Data Segment
The data segment stores global and static variables that are created by the programmer. It is present just
above the code segment of the program. It can be further divided into two parts:
A. Initialized Data Segment - As the name suggests, it is the part of the data segment that contains
global and static variables that have been initialized by the programmer. For example, The variables a and b
will be stored in the Initialized Data Segment.
// Global variable
int a = 10;
// Static variable
static int b = 20;
B. Uninitialized Data Segment (BSS) – Uninitialized data segment often called the "bss" segment,
named after an ancient assembler operator, that stood for "Block Started by Symbol" contains global and
static variables that are not initialized by the programmer. These variables are automatically initialized to
zero at runtime by the operating system. For example, the below shown variables will be stored in this
segment:
int a; // Global variable
static int b; // Static variable
3. Heap Segment
Heap segment is where dynamic memory allocation usually takes place. The heap area begins at the end of
the BSS segment and grows towards the larger addresses from there. It is managed by functions such as
4. Stack Segment
The stack is a region of memory used for local variables and function call management. Each time a
function is called, a stack frame is created to store local variables, function parameters, and return
addresses. This stack frame is stored in this segment.
The stack segment is generally located in the higher addresses of the memory and grows opposite to heap.
They adjoin each other so when stack and heap pointer meet, free memory of the program is said to be
exhausted.
The Basic Data Types
A variable in C must be a specified data type, and you must use a format specifier inside the printf()
function to display it: The data type specifies the size and type of information the variable will store.
Output:
5
5.990000
D
Modifying the Basic Types Except type void, the basic data types may have various modifiers preceding
them. A type modifier alters the meaning of the base type to more precisely fit a specific need. The list of
modifiers: signed, unsigned, long and short. The modifiers are keywords which are used to change size
and/or range of the primary datatypes. We can divide them into: Size modifiers and sign
modifiers
Size modifiers
They are used to modify the size of the datatype. We have following size modifiers
i) short : it can be used with int datatype, size of short int is 1 byte.
ii) long : it can be used with int and double datatype. The size of long int is 4 bytes and size of long double
is 16 bytes.
Sign modifiers
They are used to specify whether a data type allows us to store both negative and positive values or only
positive values.
i) signed : by default all the datatypes are signed
ii) unsigned : it can be used with int and char types.
Identifiers, as the name suggests, helps us to identify data and other objects in the program. Identifiers are
basically the names given to program elements such as variables, arrays and functions. Identifiers may
consist of a sequence of letters, numbers, numerals or underscores.
Variables
A variable is defined as a meaningful name given to a data storage location in computer memory. When
using a variable, we actually refer to the address of the memory where the data is stored. All variables
must be declared before they can be used. The general form of declaring a variable is:
datatype variable_list;
Here, datatype must be a valid datatype plus any modifier, and variable_list may consist of one or more
identifier names separated by commas. Here are some declarations:
While declaring variables, we can also initialize them with some value. For example:
In C language, a variable declared within a function or a block of code is called a local variable. Local
variables are frequently used to temporarily store data in a defined scope where they can be accessed and
manipulated. They are stored in the memory stack, Once the function or block of code in which the local
variable is declared finishes executing. The variable is automatically removed from the memory.
void main()
{
int a=10; // local variable declaration
}
Before a local variable can be used, it is necessary first to initialize the variable with a value.
The local variable is only accessible inside the function or block of code in which it is declared. A
variable's scope specifies where it can be used and accessible within a program.
// C Program to demonstrate Function Scoped Local Variables
#include <stdio.h>
// Function declared
void main()
{
int localVar = 10; // localVar is a local variable of main function
printf("The value of localVar is %d\n", localVar);
}
Output
The value of localVar is 10
Explanation: In the above code, When the main function is called, it prints the value of localVar as 10. If
you try to access it outside of its scope will result in a compilation error: 'localVar' undeclared”. This is
referred to as being out of scope.
2. Block Scoped Local Variables – Variables have a specified region or context in which they are valid
and can be manipulated. After a variable goes beyond its scope, it can no longer be accessed or modified.
Output
x was declared in the block: 25
x outside the block: 15
Explanation: Outside of the block, the program defines the variable "x" with a value of 15. Another
variable, 'x,' is defined inside the block with a value of 25. The variable "x" inside the block is printed
with a value of 25. We are unable to access the block-defined variable "x" outside of the block.
Formal parameters
Information can be passed to functions as a parameter. Parameters act as variables inside the
function. Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma:
// code to be executed
If a function is to use arguments, it must declare variables that will accept the values of the arguments.
These variables are called the formal parameters of the function. They behave like any other local
variables inside the function. As shown in the following program fragment, their declarations occur
after the function name and inside parentheses.
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}
Here, char name[] and int age are the formal parameters of the function myFunction.
They represent:
● name → a character array (string) that will store a person’s name
Formal parameters: Declared in the function definition (char name[], int age)
The formal parameters receive the values of the actual parameters when the function is executed.
Global variables
The Declaration of a global variable is very similar to that of a local variable. The only difference is
that the global variable is declared outside any function. We can take an example by assuming that we
have a chair at our house and one in our school/college then we can say that the chair at our home can
only be accessed by the people living inside the home but the chair in our college can be used by any
student or faculty.
Example:
#include <stdio.h>
int x = 5; // global variable
int main() {
int y = 10; // local variable
return 0;
}
Global variables do not stay limited to a specific function, which means that one can use any
Output
25
The terms local and global are used to describe in a general way the difference between
identifiers that are declared within a block and those declared outside all blocks. However, these
two broad categories are more finely subdivided by C. Standard C defines four scopes that
determine the visibility of an identifier. They are summarized here:
Scope Meaning
Type Qualifiers in C
Type qualifiers tell the compiler how a variable’s value can be accessed or modified. C89
defines two of these qualifiers: const and volatile. The type qualifiers must precede the type
names that they qualify for.
// a = 20; //
return 0;
❌ This will cause a compile-time error
}
Explanation:
● a is read-only.
● Any attempt to change a will result in an error.
int main() {
while(counter == 0) {
// waiting for counter to change (e.g., by hardware)
}
printf("Counter changed!\n");
return 0;
}
Explanation:
● Normally, the compiler might optimize while(counter==0) assuming the counter never
changes.
● volatile prevents this, so the program keeps checking the actual value.
int main() {
int value = *port; // read value from hardware port
printf("Port value: %d\n", value);
// *port = 10; //
return 0;
❌ cannot write to port, read-only
}
Explanation:
● The program cannot modify the port (const).
● The hardware can change the value at any time (volatile).
Qualifier Can Program Can Value Change Outside Example Use Case
Change? Program?
1. extern
In C, the extern keyword is used to declare a variable or a function whose definition is present in
some other file. Basically, it extends the visibility of the variables and functions in C to multiple
source files. Generally, the variables and functions defined inside a C source file are only used
inside that file. But in large projects where code is split across multiple files (or translation unit),
users may need the data, or a part of code defined in another translation unit into the current one.
This can be done with the help of extern keywords.
The usage syntax of extern is a multistep process. In the file, where we want to use the
variable/function, we have to provide extern declaration:
extern var_type var_name;
extern ret_type func_name (arg_types .... );
The above declarations tell the compiler that the var_name variable and func_name function are
defined in some other translation unit. The next step is to compile both translation units together so
that the compiler can find the definition of it.
The variables/functions being declared must have external linkage i.e. they must be defined
globally. Local and static variables/functions have internal linkage and cannot be linked by the
compiler if they are declared as extern.
The following examples demonstrate the use of extern keyword in C:
First create a file that contains the definition of a variable. It must be global variable,
src.c
// Definition of a variable
int ext_var = 22;
Create an extern declaration of this variable in the file where we want to use it.
main.c
What it does:
● Normally, a local variable is created when a function is called and destroyed when the function
ends.
● If you declare a local variable as static, it persists between function calls.
● Its value is retained instead of resetting each time the function is called.
int main() {
printf("%d\n", series()); // 123
printf("%d\n", series()); // 146
printf("%d\n", series()); // 169
return 0;
}
Explanation:
● series_num keeps its value between function calls.
● First call → 123, second call → 146, third call → 169.
● If it were a normal local variable, it would reset to 100 each time → every call would return
123.
3. Registers
Registers are faster than memory to access, so the variables which are most frequently used in a C
program can be put in registers using the register keyword. The keyword register hints to the compiler
that a given variable can be put in a register. It's the compiler's choice to put it in a register or not.
Generally, compilers themselves do optimizations and put the variables in a register.
1. If you use & operator with a register variable then the compiler may give an error or warning
(depending upon the compiler you are using), because when we say a variable is a register, it may be
stored in a register instead of memory and accessing the address of a register is invalid.
2. register keyword can be used with pointer variables. Obviously, a register can have the address of a
memory location. There would not be any problem with the below program.
// C program that demonstrates register keyword can be used with pointer variables
#include <stdio.h>
int main()
Output 10
3. Register is a storage class, and C doesn't allow multiple storage class specifiers for a variable. So, the
register can not be used with static.
4. Register can only be used within a block (local), it can not be used in the global scope (outside main).
5. There is no limit on the number of register variables in a C program, but the point is compiler may put
some variables in the register and some not.
4. auto
This is the default storage class for all the variables declared inside a function or a block. Auto variables
can be only accessed within the block/function they have been declared and not outside them (which
defines their scope).
Properties of auto Variables
● Scope: Local
● Default Value: Garbage Value
● Memory Location: RAM
● Lifetime: Till the end of its scope
Example:
#include <stdio.h>
int main() {
// auto is optional here, as it's the default storage class
auto int x = 10;
printf("%d", x);
return 0;
}
Output
10
Explanation: The auto keyword is used to declare a local variable with automatic storage. However, in
Operations in C
An operator is a symbol that specifies the mathematical, logical, or relational operation to be
performed. It is categorized into the following major groups:
● Arithmetic operators
● Relational operators
● Equality operators
● Logical operators
● Unary operators
● Conditional operators
● Bitwise operators
● Assignment operators
● Comma operator
● sizeof operator
A relational operator, also known as a comparison operator, is an operator that compares two values.
● C supports 2 kinds of equality operations to compare the operands for strict equality or inequality.
● They are equal to (==) and not equal to (!=) operators.
Operator Meaning
( 4) Logical Operations
● Supports three logical operators: logical AND (&&), logical OR (||), and logical NOT (!).
● Logical AND is a binary operator, which simultaneously evaluates two values or relational
expressions.
● If both the operands are true, then the whole expression evaluates to true.
● If either of the operands is false, then the whole expression evaluates to false.
A B A && B
0 0 0
0 1 0
1 0 0
1 1 1
For example:
Logical OR (||)
● Returns a false value if both the operands are false; otherwise, it returns a true value.
| A | B | A || B |
|---|---|--------|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
|1|1|1|
For example:
● (a < b) || (b < c)
● (5 < 3) || (5 > 2) = 1 (true)
● (3 < 5) || (2 > 5) = 1 (true)
For example:
int a = 10, b;
int x = 10, y;
y = x++; // is equivalent to writing
// y = x;
// x = x + 1;
y = ++x; // is equivalent to writing
// x = x + 1;
// y = x;
Example:
int a=25;
printf(“a++ = %d \n”, a++);
printf(“a-- = %d \n”, a--);
printf(“++a = %d \n”, ++a);
printf(“--a = %d \n”, --a);
Output:
25
26
26
25
Example 1: C Program to Store the greatest of the two Numbers using the ternary operator
// C program to find largest among two numbers using ternary operator
#include <stdio.h>
int main()
{
int m = 5, n = 4, large;
large = (m > n) ? m : n ;
printf("larger number is %d", large);
return 0;
}
Output
larger number is 5
In C, bitwise operators are used to perform operations directly on the binary representations of
numbers. These operators work by manipulating individual bits (0s and 1s) in a number.
The following 6 operators are bitwise operators (also known as bit operators as they work at the
bit-level). They are used to perform bitwise operations in C.
1. The & (bitwise AND) 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.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of
two numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every
bit of two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand,
and the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
As mentioned in point 1, it works only if numbers are positive.
#include <stdio.h>
int main() {
int x = 19;
printf("x << 1 = %d\n", x << 1);
printf("x >> 1 = %d", x >> 1);
return 0;
}
Output
x << 1 = 38
x >> 1 = 9
int x = 2, y = 3, sum = 0;
sum = x + y;
Expression would be evaluated and the result would be stored in the location denoted by the variable name.
Then sum = 5.
First 10 is assigned to c, then the value of c is assigned to b. Finally, the value of b is assigned to a.
The operand to the left of the assignment operator must always be a variable name.
Assignment operations
a += b ⇒ variable += expression
variable = variable + expression
For example a += b ⇒ a = a + b
/= a /= b a=a/b
*= a *= b a=a*b
+= a += b a=a+b
-= a -= b a=a-b
^= a ^= b a=a^b
● The comma operator in C takes 2 operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the result of
the expression.
Example:
int a = 2, b = 3, x = 0;
x = (a + a, b + a);
Examples:
sizeof(int) → returns 2
sizeof(char) → returns 1
Evaluating Expressions
C operations have 2 properties: priority and associativity. When an expression has more than
one operator, then it is the priority of the operator that determines the order in which the
expression will be evaluated.
Associativity indicates the order in which the operators of equal precedence in an expression are
evaluated.
Operator Associativity
()[] L–R
+, -, ! (unary) R–L
sizeof L–R
*/% L–R
+- L–R
== != (Equality) L–R
? : (Ternary) R–L
, (Comma) L–R
① x = 3 × 4 + 5 × 6
= 12 + 30
= 42
② x = 3 × (++5) × 6
= 3 × 6 × 6
= 3 × 36
= 108
③ x = 3 × ((4 + 8)/2)
= 3 × (12/2)
= 3 × 6
= 18
int a = 0, b = 1, c = -1;
float x = 2.5, y = 0.0;
④ a + b - c × x = 10
= a + (b - (c × 10))
= a + (b - (-10))
= a + (b = 11)
= 0 + 11 = 11
⑤ a && b && c
= 0 && 1 && -1 = 0
H.W problems
Output:
Enter any character: A
The ASCII value of A is: 65
#include <stdio.h>
int main()
{
char ch;
printf("Enter any uppercase character: ");
scanf("%c", &ch);
printf("\n The character in lowercase is: '%c'", ch+32);
return 0;
Output:
#include <stdio.h>
main()
{
int num, digit_atones;
printf("Enter any number:");
scanf("%d", &num);
return 0;
}
Output:
Enter any number: 123
The digit at ones place is 3
#include <stdio.h>
int main()
{
int n1, n2, temp;
printf("\n Enter the first number:");
scanf("%d", &n1);
printf("\n Enter the second number:");
scanf("%d", &n2);
temp = n1;
n1 = n2;
n2 = temp;
C = (0.56) * (F - 32);
Output:
Enter temperature in F: 32
Temperature in C: 0.0
Write a program to calculate the total amount of money in the piggybank, given the coins
return 0;
}
Output:
Type Conversion
● Type conversion is done when the expression has variables of different data types.
● To evaluate the expression, the data type is promoted from lower to higher level where
required.
Type conversion is done automatically when we assign an integer value to a floating point
variable.
(This is known as promotion, when a lower level data type is promoted to a higher type.)
float x;
int y = 3;
x = y;
Now, x = 3.0, as automatically integer value is converted into its equivalent floating point
representation.
If any operand is double or long, the other operand is also converted to double or long
respectively.
i = f results in f to be demoted to type int, i.e., the fractional part of f will be lost and i will
contain 3, not 3.5.
This is known as demotion. (Higher level data type is converted into a lower type.)
Similarly, if we convert an int to a short int or a long int to int, or int to char, the compiler just
drops the extra bits.
Typecasting
Typecasting is also known as forced conversion. Changing a variable of one data type to
another is done explicitly.
● Floating point numbers are converted to integers – the digits after the decimal are truncated.
● Typecasting can be done by placing the destination data type in parentheses followed by the
variable name that has to be converted.
Write a program to convert a floating point number into the corresponding integer.
#include <stdio.h>
int main()
{
float fnum;
int inum;
printf("Enter floating point number: ");
scanf("%f", &fnum);
inum = (int)fnum;
printf("The integer variant of %f is = %d", fnum, inum);
return 0;
}
Sample Output 1
Enter floating point number: 12.98
The integer variant of 12.980000 is = 12
Sample Output 2
Enter floating point number: -45.67
The integer variant of -45.670000 is = -45
● This conversion truncates the decimal part (it does not round off).
○ Example:
12.98 → 12
-45.67 → -45
In C, there are many input and output for different situations, but the most commonly used
functions for Input/Output are scanf() and printf() respectively. These functions are part of the
standard input/output library <stdio.h>. scanf() takes user inputs (typed using keyboard) and
printf() displays output on the console or screen.
printf() — Basic Output in C
The printf() function is used to print formatted output to the standard output stdout (which is
Examples
Output
First Print
Explanation: The text inside "" is called a string in C. It is used to represent textual information.
We can directly pass strings to the printf() function to print them in console screen.
Printing Variables
#include <stdio.h>
int main() {
int age = 22;
// Prints Age
printf("%d\n", age);
return 0;
}
Output
22
Here, the value of variable age is printed. You may have noticed %d in the formatted string. It is
actually called format specifier which are used as placeholders for the value in the formatted
string. You may have also noticed '\n' character. This character is an escape sequence and is used
to enter a newline.
Printing Variables Along with String
#include <stdio.h>
int main() {
int age = 22;
Output
The value of the variable age is 22
The printf function in C allows us to format the output string to console. This type of string is called
formatted string as it allows us to format (change the layout the article).
Remember that this function takes the address of the arguments where the read value is to be stored.
Reading an Integer
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
// Reads an integer
scanf("%d", &age);
int main() {
// Reads an Character
scanf("%c", &ch1);
puts(str1);
printf("You entered: %s\n", str2);
return 0;
}
Output:
Enter a String: hello
Enter second string: world
hello
world
The scanf() function can not handle spaces and stops at the first blank space. To handle this situation
we can use fgets() which is a better alternative as it can handle spaces and prevent buffer overflow.