0% found this document useful (0 votes)
5 views89 pages

C Programming

The document provides an introduction to programming, covering the basic organization of a computer, including its components such as the input unit, CPU, and output unit. It explains programming languages, types of languages, and the program development life cycle, which includes phases like problem definition, analysis, algorithm development, coding, testing, and maintenance. Additionally, it discusses problem-solving techniques and the differences between top-down and bottom-up approaches in programming.

Uploaded by

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

C Programming

The document provides an introduction to programming, covering the basic organization of a computer, including its components such as the input unit, CPU, and output unit. It explains programming languages, types of languages, and the program development life cycle, which includes phases like problem definition, analysis, algorithm development, coding, testing, and maintenance. Additionally, it discusses problem-solving techniques and the differences between top-down and bottom-up approaches in programming.

Uploaded by

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

INTRODUCTION

TO
PROGRAMMING

UNIT-I

LECTURE NOTES

J. SRAVAN KUMAR, FACULTY IN CSE-AIML, KITS AKSHAR INSTITUTE OF TECHNOLOGY


BASIC ORGANIZATION OF A COMPUTER:

DEFINITION OF COMPUTER
Computer is fast electronic machine which can perform arithmetic and logic operations.
(OR)
Computer is a fast electronic calculating machine that accepts digitized input information,
processes it according to a list of internally stored instructions, and produces the resulting
output information.
BLOCK DIAGRAM OF COMPUTER
 Founder of computer is Charles Babbage.
 The block diagram of computer is

 On the basis of its internal structure, a computer can be divided into three main parts.
1. Input unit.
2. CPU
3. Output unit.
1. INPUT UNIT: -
 Input unit is the device used to enter data and instructions into the computer. The
data read from the input device is stored in the computer’s memory.
Ex: key board, mouse, joy stick, track ball, light pen…..etc.
2. CPU: -
 CPU is the main part of the computer.
 In other words, it is brain of the computer.
 This is also called as processor.
 This unit takes the input data from input devices and processes it according
to the set of instructions called as “program”. The output for the processed
data is directed to the output devices.
 It controls the operations.

 The CPU consists of 3 parts i.e.


1. ALU.
2. CU.
3. MEMORY.

ARITHMETIC LOGIC UNIT (ALU):-


 The function of this unit is to verify the data received from memory unit and
transfers the same back to the main memory of the computer.
 The ALU performs arithmetic and logical operations.
 The arithmetic operations include addition, subtraction, multiplication and
division.
 Integer numbers & floating point numbers are used to perform the operations.
 Logical operations include the Boolean functions such as AND, OR, NOT
and increment/ decrement, shift operations.
 These operations are used during the conditional branching.

CONTROL UNIT (CU):-


 CU controls the working of the computer and check whether the computer is
functioning as per the commands or not.
 This unit is mainly used for generating electronic control & timing signals
for program execution.
 It controls all the operations of the computer.

MEMORY UNIT: -
 Memory unit is also one of the most important parts of the computer.
 Memory is the storage area in a computer where data, instructions, and
information are kept.
 It is essential because the CPU can only process data that is stored in memory.
 This unit stores the data, calculations and results into it and in case of need it sends
the data in the form of output.
 Memory is made up of semiconductor cells, each cell is capable of storing one bit
of information either 0 or 1.
 The capacity of memory is measured in terms of Bytes, Kbytes or megabytes.

 Memory may be volatile (or) non – volatile in nature.


 Volatile memory is washed as soon as the power is cut. The information and the
data is also washed as soon as the power supply is stopped.
 Non – volatile memory is not washed if the power supply is cut and hence the
data and information are safe in that memory.

PRIMARY MEMORY (MAIN / INTERNAL MEMORY)

Directly accessible by the CPU. Very fast but expensive.

 a) RAM (Random Access Memory):


o Temporary storage.
o Data is lost when power is turned off (volatile).
o Example: Running programs are stored in RAM.
 b) ROM (Read Only Memory):
o Permanent storage.
o Data is not lost when power is turned off (non-volatile).
o Example: BIOS instructions.
 c) Cache Memory:
o Very high-speed memory between CPU and RAM.
o Stores frequently used data for faster access.
 d) Registers:
o Small storage units inside the CPU.
o Store data temporarily during execution of instructions.

SECONDARY MEMORY: -
 It is used to hold the output data or program for future use.
 These memory devices are for long term storage.
 These are larger in capacity than main memory but these are very slower than
main memory.
 The data from this memory is first transferred to the main memory.
 Examples are Magnetic Tapes, Magnetic Disks, CD ROM, and Floppy disk.

3. OUTPUT UNIT: -
 The function of output unit is reverse in nature than that of input unit.
 Output unit takes out the data from the computer.
 The information generated from the processor is displayed on the output device.
 Some output devices are monitors, Printers, Floppy disk etc.

SOME IMPORTANT DEFINITION: -

1. PROGRAM:-
A sequence of instructions that can be executed by the computer to solve the given
problem is known as program.
2. SOFTWARE:-
A set of programs to operate and controls the operation of a computer.
3. HARDWARE:-
All the physical components or units of the computer system connected to the
computer circuit are known as hardware.

BITS & BYTES CHART

Unit Equivalent Approx. Value


1 Bit Smallest unit (0 or 1) –
1 Nibble 4 Bits –
1 Byte (B) 8 Bits –
1 Word 16 to 64 bits
1 Kilobyte (KB) 1,024 Bytes ≈ 10³ Bytes
1 Megabyte (MB) 1,024 KB ≈ 10⁶ Bytes
1 Gigabyte (GB) 1,024 MB ≈ 10⁹ Bytes
1 Terabyte (TB) 1,024 GB ≈ 10¹² Bytes
1 Petabyte (PB) 1,024 TB ≈ 10¹⁵ Bytes
1 Exabyte (EB) 1,024 PB ≈ 10¹⁸ Bytes
1 Zettabyte (ZB) 1,024 EB ≈ 10²¹ Bytes
1 Yottabyte (YB) 1,024 ZB ≈ 10²⁴ Bytes
Introduction to Programming Languages
 A programming language is a set of instructions that allows humans to communicate
with a computer.
 It acts as a bridge between humans and machines.
 Computers only understand binary (0s and 1s), but programming languages provide a
way to write instructions in human-readable form.
 These instructions are later translated into machine code for execution.

Examples: Machine language, Assembly language, C, C++, Java, Python.

Types of Programming Languages

Machine Language
 First generation programming language.
 Consists only of binary code (0s and 1s).
 Example: 10110000 01100001
 Features:
o Directly understood by the computer.
o Very fast execution.
o Difficult for humans to learn, read, or debug.
o Hardware dependent (different for each CPU).

Assembly Language
 Second generation programming language.
 Uses mnemonics (symbols/short codes) instead of binary.
 The general form of Assembly Language code is

Opcode destination, Source


Opcode: operation to be performed

Source and destination are two operands and result is stored in destination operand.

Ex: addition program

Mov R1, 10 ; Value 10 is assigned to R1

Mov R2, 20 ; Value 20 is assigned to R2

Add R1, R2 ; Add the contents of R1 and R2 and result stored in R1 ( R1-R1+R2)

 Features:
o Easier to write than machine language.
o Still hardware dependent.
o Needs an assembler to convert to machine code.
o Used for system programming and embedded systems.
High Level Language
 Third generation programming language.
 Uses English-like instructions.
 Examples: C, C++, Java, Python.
 Features:
o Easy to learn, write, and understand.
o Portable (can run on different machines).
o Requires a compiler or interpreter to translate into machine code.
o Supports structured programming, loops, functions, etc.

#include <stdio.h>
void main()
{
int a=10,b=20,c;
c=a+b;
printf("addition value is %d", c);
}

Middle-Level Language
It has features of both low-level languages (machine/assembly) and high-level languages.

It allows programmers to write system-level programs (like operating systems, device drivers)
and application programs (like calculators, games, business software).

 Low-Level Features:
o Can directly access memory using pointers.
o Can perform bitwise operations and interact with hardware.
 High-Level Features:
o Uses English-like syntax (if, while, printf).
o Programs are portable across different computers.

👉 Since it lies between low-level and high-level, it is called middle-level.

Translators Comparison
Feature Compiler Interpreter Assembler

High-level
Input Language High-level (C, Java) Assembly language
(Python, JS)

Translation Whole program at once Line by line Instruction by instruction

Speed Fast execution Slow execution Fast

Error Handling Shows all errors after compilation Stops at first error Shows assembly errors

Example Tools GCC, javac Python, Node.js MASM, NASM


PROBLEM SOLVING TECHNIQUES

PROGRAM DEVELOPMENT STEPS

When we want to develop a program using any programming language, we follow a sequence
of steps. These steps are called phases in program development. Generally, the program
development life cycle contains 6 phases, they are as follows….

 Problem Definition
 Problem Analysis
 Algorithm Development
 Coding & Documentation
 Testing & Debugging
 Maintenance

1. PROBLEM DEFINITION
In this phase, we define the problem statement and we decide the boundaries of the problem.
In this phase we need to understand the problem statement, what is our requirement,
what should be the output of the problem solution. These are defined in this first phase of
the program development life cycle.

2. PROBLEM ANALYSIS
In phase 2, we determine the requirements like variables, functions, etc. to solve the
problem. That means we gather the required resources to solve the problem defined in the
problem definition phase.

3. ALGORITHM DEVELOPMENT
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. That means we write the solution in step by step
statements. A step- by – step procedure to solve the given problem is known as Algorithm.
An algorithm is defined as finite set of steps which accomplish the particular task.
Characteristics of an algorithm are:
1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each and every instruction should be precise and unambiguous i.e. each and
every instruction should be clear and should have only one meaning.
3. Effectiveness: Each instruction should be performed in finite amount of time.
4. Input and Output: An algorithm must take zero or more inputs, and produce one or more
outputs.

Ex1: addition of two numbers


Step1: start the program.
Step2: read a, b values.
Step3: find the sum of a, b values.
Step4: store the sum in c.
Step5: print the sum c.
Step6: stop the program.

Ex2: find the simple interest


Step1: start the program.
Step2: read p, t, and r values.
Step3: multiply p, n, r.
Step4: divide the p*n*r by 100.
Step5: Store the result in si.
Step5: print the result si.
Step6: stop the program.

FLOW CHART: -

A flow chart is nothing but a graphical or symbolic representation of an algorithm. It


shows the logic of the algorithm and flow of control.

The flow charts use some symbols to represent specific actions and arrows to indicate the flow
of control.

Flow chart symbols: -

 These symbols have been standardized by the American National Standard Institute
(ANSI).
 Here are the five most common shapes used in a flowchart.
Connectors: - A small, labeled circle used to connect different parts of a flowchart.

Usefulness of Flowcharts in Programming

1. Helps in visualizing the logic before writing code.


2. Makes problem solving simpler and systematic.
3. Easy to understand, debug, and explain.
4. Reduces the chances of errors in the program.
5. Acts as a blueprint for writing programs in any language.

Example: Addition of two numbers


Ex:2 Flow chart to find Simple Interest

Example: 3 Flow chart to find largest of 2 numbers


4. CODING AND IMPLEMENTATION: -

Coding is a process of converting the algorithmic solution or flow chart into a computer
program.

In this process each and every step of an algorithm will be converted into computer
programming language.

Before selecting a programming language, we must follow the following three considerations.
a. Nature of the problem.
b. Programming language available on the computer system.
c. Limitations of the computer.

5.TESTING & DEBUGGING

 During this phase, we test the program whether it is solving the problem for various
input data values or not.

 We also test whether it is providing the desired output or not.


The process of correcting errors in a program is called Debugging.
There are 3 types of errors that generally occur in a program namely.
a. Syntax errors.
b. Run time errors.
c. Logical errors.

6. MAINTENANCE

 During this phase, the program is actively used by the users.


 If any enhancements found in this phase, all the phases are to be repeated to make the
enhancements.

Common Problem-Solving Techniques


1. Trial and Error → Trying possible solutions until one works.
2. Divide and Conquer → Breaking the problem into smaller sub-problems.
3. Algorithmic Thinking → Writing clear step-by-step instructions.
4. Top-Down Approach → Start from the main problem → break into modules.
5. Bottom-Up Approach → Solve smaller sub-problems first → integrate into big
solution.

Top-Down vs Bottom-Up Approach


Top-Down Approach
Meaning

 Start from the main problem and break it into smaller sub-problems (modules).
 Keep dividing until each module is simple enough to implement.

Process

1. Identify the big task.


2. Divide it into major sub-tasks.
3. Further divide each sub-task into smaller steps.
4. Write code for each module.

Example: Calculate Student Result

 Main Problem → Calculate Result


o Sub-task 1 → Input Marks
o Sub-task 2 → Calculate Total
o Sub-task 3 → Calculate Average
o Sub-task 4 → Print Result

 Like a tree breaking down from top to bottom.

Bottom-Up Approach
Meaning

 Start solving from smallest sub-problems (modules) and then combine them to make
the complete system.
 Build complex programs by combining small, tested components.

Process

1. Identify small modules first.


2. Implement and test them individually.
3. Integrate modules step by step into bigger units.
4. Form the complete system.

Example: Calculate Student Result

 Start with small modules:


o Module 1 → Input Marks
o Module 2 → Add Numbers
o Module 3 → Find Average
 Combine them together → Full Result Calculation
 👉 Like building blocks, from bottom to top.
Feature Top-Down Approach Bottom-Up Approach
Starts from the overall system Starts from small modules/functions and
Starting Point and breaks it into smaller combines them to form the complete
modules system
Focus on problem Focus on module implementation and
Focus
decomposition and design integration
Design vs Implement small modules first, then
Design first, then implement
Implementation integrate
Ease of Planning Easier to plan large projects Good for reusable modules and libraries
Testing is usually done after
Testing Modules can be tested independently
modules are combined
Complexity Handles system complexity
Handles modular functionality better
Handling better
When the problem is well When existing modules or libraries are
Best Use
understood available
C is an Example for Top Down C++ is an example for Bottom Up
Example
Approach. Approach

----------------- -------------------- ----------------- --------------- -------------

Time Complexity

When we design or analyze a program or algorithm, we check:

 How fast it runs → ⏱️ Time Complexity


 How much memory it uses → 💾 Space Complexity

Both help us measure the efficiency of an algorithm.

Time complexity Definition:

 Time complexity measures how much time an algorithm takes to run as a function of
the input size (usually denoted as n).
 It tells us how fast or slow the algorithm is.

Key Points:

 Expressed in Big O notation (O(1), O(n), O(n²), etc.)


 Depends on the number of basic operations or steps performed.

Example: Factorial Program (Iterative)


for(i = 1; i <= n; i++)
fact = fact * i;
 Loop runs n times, each iteration = 1 multiplication → O(n)
 Initialization & output = O(1)
 Total Time Complexity = O(n)

Space Complexity

Definition:

 Space complexity measures how much memory an algorithm uses as a function of


the input size.
 Includes variables, arrays, recursion stack, and auxiliary space.

Key Points:

 Constant variables = O(1)


 Arrays of size n = O(n)
 Recursive calls use stack space

Example: Factorial Program

Iterative version:

int fact = 1;
for(i = 1; i <= n; i++)
fact *= i;

 Variables: fact and i → O(1)


 Total Space Complexity = O(1)

Comparison Table

Basis Time Complexity Space Complexity


Meaning Time taken by program to execute Memory used by program
Focus Execution speed Memory usage
Unit of Measure Number of operations Bytes or memory units
Goal Reduce execution time Reduce memory usage
Example Loop execution count Number/size of variables used
Notation O(1), O(n), O(log n) O(1), O(n), O(n²)
History of C

Inventor of C - Dennis Ritche


 1960s – Before C

 Assembly language was used, but it was too complex and machine-dependent.
 Higher-level languages like ALGOL (1960) and BCPL (1966) were developed to
make programming easier.

 1967 – BCPL (Basic Combined Programming Language)

 Developed by Martin Richards.


 Aimed for system and compiler development.
 Simple but lacked data types.

 1970 – B Language

 Developed by Ken Thompson at Bell Labs.


 Derived from BCPL.
 Used for UNIX operating system development (early versions).

 1972 – Birth of C

 Developed by Dennis Ritchie at Bell Laboratories (AT&T, USA).


 Improved version of B, with data types, operators, and better structure.
 Designed mainly for system programming.

 1973 – UNIX rewritten in C

 Major breakthrough!
 UNIX operating system (originally in Assembly) was rewritten in C.
 This proved C’s power, portability, and efficiency.

 Late 1970s – Spread of C

 C became widely used for system software and compiler writing.


 Many universities began teaching C.

 1978 – K&R C

 Brian Kernighan and Dennis Ritchie published “The C Programming Language”


book.
 This became the first official documentation of C, often called K&R C.

 1983 – ANSI C Standardization begins

 The American National Standards Institute (ANSI) formed a committee to


standardize C.
 1989 – ANSI C (C89)

 Official standardized version of C released.


 Widely adopted across the world.

 1990 – ISO C (C90)

 International standard approved by ISO.


 Ensured global acceptance of C.

 Later Versions

 C99 (1999): Added new features like inline functions, long long int, variable length
arrays.
 C11 (2011): Added multi-threading support and improved standard libraries.
 C18 (2018): Minor bug fixes and updates.

The latest official C standard is ISO/IEC 9899:2024, commonly referred to as C23. It was published in
October 2024 and supersedes the previous standard C17/C18.

Applications of C Language

1. Operating Systems
o Most of the UNIX operating system is written in C.
o Other OS like Windows, Linux kernel, and Android parts also use C.
2. Embedded Systems
o Widely used in microcontrollers, automotive systems, medical devices, and
consumer electronics.
o Example: Programming firmware for washing machines, TVs, cars, etc.
3. Compilers and Interpreters
o Many language compilers (C++, Java, Python interpreters) are implemented in
C.
4. Databases
o Popular databases like MySQL, Oracle, PostgreSQL use C for speed and
efficiency.
5. System Programming
o Device drivers, networking software, file systems, and system utilities are
often written in C.
6. Game Development
o Used for game engines and graphics rendering because of high performance.
o Example: Many early PC/console games were written in C.
7. Graphics and GUI Applications
o C is used in libraries for graphics, simulations, and GUI frameworks.
o Example: OpenGL, DirectX-based tools.
8. IoT (Internet of Things)
o Lightweight and efficient, making it suitable for IoT devices and sensors.
9. Scientific Computing and Simulations
o Used in numerical methods, simulations, and performance-critical research
applications.
10. Portable Applications
o C programs can run on different platforms with minimal modification, making
them highly portable.
STRUCTURE OF C PROGRAM
A C program has a well-defined structure. Every program is made up of the following sections:

1. Documentation section: The documentation section consists of a set of comment lines giving
the name of the program, the author and other details, and statements mentioned in this section are
not executed by the compiler.

2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.

 A preprocessor directive is an instruction given to the C compiler’s preprocessor.


 It tells the compiler to do some preprocessing before actual compilation starts.
 All preprocessor directives begin with # (hash symbol).

Example : #include<stdio.h> #include<math.h>

3. Definition section: The definition section defines all symbolic constants such using the #define
directive.

Example: #define PI 3.141 #define MAX 120

4. Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that is
outside of all the functions
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part

1. Declaration part: The declaration part declares all the variables used in the executable
part.

2. Executable part: There is at least one statement in the executable part. These two parts
must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function is
the logical end of the program. All statements in the declaration and executable part end
with a semicolon.

6. Subprogram section: If the program is a multi-function program then the subprogram


section contains all the user-defined functions that are called in the main () function.

User-defined functions are generally placed immediately after the main () function, although they
may appear in any order.

#include <stdio.h> // Preprocessor directive


#define PI 3.14159

void main()
{
// Variable declaration
int radius;
float area;

// Input
printf("Enter radius: ");
scanf("%d", &radius);

// Processing
area = PI * radius * radius;

// Output purpose
printf("Area = %f", area);
}

Output:
Enter radius: 5.5
Area = 78.539749
BASIC INPUT AND OUTPUT FUNCTIONS

C programming has several in-built library functions to perform input and output tasks.

Two commonly used functions for I/O (Input/Output) are printf() and scanf().

The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).

printf( ) in C
 printf() is a standard library function in C (defined in <stdio.h>).
 It is used to print/output text, variables, and results on the screen.
 It helps in displaying messages to the user and the results of computations.

Syntax:

print("format string”);

print("string with format specifiers",variables);

format string → Text/characters to be displayed

format specifiers – defines the type of data to be printed (%d,%f,%c,%s etc.)

variables → Values that will replace the format specifiers

#include <stdio.h> //This is needed to run printf() function.


void main()
{
printf("C Programming"); //displays the content inside quotation
}
Scanf ( ) function in C

 scanf() is a standard input function in C.


 It is used to read data from the keyboard (user input).
 Declared in the header file: #include <stdio.h>
 It stores the entered values into variables.

scanf("format_specifiers", &variable1, &variable2, ...);

 format_specifiers → tells the type of data to be read (%d, %f, %c, %s, etc.).
 & (address operator) → gives the memory location of variables so that the entered
value can be stored there.

Common Format Specifiers


Data Format Example
Type Specifier Input

Integer %d 10

Float %f 12.34

Double %lf 45.6789

Character %c A

String %s Hello

Example:

#include <stdio.h>
void main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b); // input operation
printf("Sum = %d", a + b);
}

Output: Enter two numbers: 10 30

Sum = 40
Introduction to Compilation and Execution,
 Generally, the programs created using programming languages like C, C++, Java, etc., are
written using a high-level language like English. But, the computer cannot understand the
high-level language.
 It can understand only low-level language. So, the program written in the high-level
language needs to be converted into the low-level language to make it understandable for
the computer. This conversion is performed using either Interpreter or Compiler.
 A compiler is a program that converts high-level language instructions into low-level
language instructions.
 To create and execute C programs in the Windows Operating System, we need to install
Turbo C software. We use the following steps to create and execute C programs in
Windows OS…

1. Source Code
 The program you write in a high-level language (like C, C++, Java, Python).
 Example in C:

printf("Hello, World!");

2. Compilation
 The compiler translates the entire source code into machine code (binary).
 Machine code is what the computer understands directly (0s and 1s).
 If there are errors, the compiler shows them (like syntax errors, missing semicolon).
 After successful compilation, a machine code file (called object code / executable file)
is created.
👉 Example:

 In C (Windows): program.c → compiled → program.exe


 In C (Linux): program.c → compiled → a.out

3. Linking
 Sometimes your program uses libraries (like printf from stdio.h).
 The linker combines your code with these library functions to make the final executable
file.

4. Execution
 When you run the program, the executable is loaded into memory.
 The CPU executes the machine code step by step.
 Output is shown on the screen.

Execution Process of a C Program

When we execute a C program it undergoes with the following process…

Stage Tool Output


Source Code Editor .c file
Compilation Compiler Object file (.obj / .o)
Linking Linker Executable file (.exe)
Execution Loader Final Output
THE C CHARACTER SET

The C Character Set includes all the valid characters that can be used to write C programs.
These characters are used to form keywords, identifiers, constants, operators, and symbols.

There are two set of characters in “C” language


1. Source characters 2. Execution characters

Source Characters
These are characters that are used to create source text file. Source characters include
Alphabets A to Z, a to z
Digits 0,1,2,3,4,5,6,7,8,9
Special Characters , . ; : ? ‘ “ ! | / \ ~ _ $ % # & ^ * + - <> ( ) { } [ ] and blank

Execution Characters

o The meaning of these characters is interpreted at the time of execution.


o These are also known as “Escape sequences because the backslash (\) is considered as an
‘escape’ character.
o It causes an escape from normal interpretation of a string. so that the next character is
recognized as one having special meaning.

Escape sequences

Escape
Sequence Name Meaning
Moves the cursor to the previous position of the
\b Backspace current line
\r Carriage return Moves the cursor to beginning of the current line.

\n New line Moves the cursor to beginning of the next line.

\0 Null Null character

\v Vertical tab Moves the cursor to next vertical tab position.

\t Horizontal tab Moves the cursor to next horizontal tab position.

\\ Backslash Present a character with backslash(\)


C TOKENS
 Smallest individual unit of a program is known as token.

Keywords
 These are also called as reserved words.
 All Keywords have fixed meanings and these meanings cannot be changed.
 There are 32 keywords in C programming.
 Keywords serve as basic building blocks for a program statement.
 All keywords must be written in lowercase only.
 The keywords cannot be used as Identifiers

There are only 32 keywords available in C.


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Identifiers
 An identifier is the name given to variables, functions, arrays, or any user-defined item
in a C program.
 Identifiers must be unique. They are created to give a unique name to an entity to identify it
during the execution of the program
Examples: int marks; float average; void display();
Here, marks, average, and display are identifiers.
Rules for naming identifiers
 Identifiers can contain letters (A–Z, a–z), digits (0–9), and underscores (_)
 The first letter of an identifier should be either a letter or an underscore.
 No special symbols (like @, $, #, !) are allowed
 No spaces in identifiers.
 C is case-sensitive → Total and total are different
 Keywords (reserved words) cannot be used as identifiers
 Length should be reasonable. ( Max -31 characters)
 Valid Identifiers-- a, A1, _sum, total_marks, average, MaxValue
 Invalid Identifiers 1sum, total marks, float, @value, marks#

Constants
 Constant can be defined as a value that can be stored in memory and cannot be
changed during execution of the program.
 Constants are used to define fixed values like pi.
 C has four basic types of constants. They are:

Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can be
either positive or negative.
Examples for integer constants
1 9 234 999
It may be specified in Decimal, Octal and Hexa decimal notation.

Floating point Constant


A floating point constant is decimal number that contains either a decimal point or an
exponent. In the other words, they can be written in 2 forms: fractional and exponential.
When expressed in fractional form, note the following points.

1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Examples for fractional form
12.33 -19.56 +123.89 -0.7

When expressed in exponential form, a floating point constant will have 2 parts.
One is before e and after it. The part which appears before e is known as mantissa and the
one which follows is known as exponent. When expressed in this format, note the following
points.
1. mantissa and exponential should be separated by letter E.
2. mantissa can have a positive and negative sign.
3. default is positive.

Examples for fractional form


2E-10 0.5e2 1.2E+3 -5.6E-2

Character Constant

 These are single character enclosed in single quotes.


 A character can be single alphabet, single digit, single special symbol enclosed with
in single quotes. Not more than a single character is allowed.

Example : ‘a’ ‘Z’ ‘5’ ‘$’

String Constant
A String constant is sequence of characters enclosed in double quotes.

Example
“hello” “Programming”

Variables in C
A variable is a named memory location that stores a value which can change during program
execution. It acts like a container that holds data.

Each variable in C has a specific type, which determines the size of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.

Variable Declaration Syntax:

datatype variable_name;
int a;

How to define a value to variable?

datatype variable_name = value ;


int a= 10; // Initialization
Rules for defining variables.

Rule Example Invalid Example


A variable name must begin with a letter or
total, _sum 1total
underscore (_)
marks1,
Only letters, digits, and underscores are allowed marks#, student-score
student_score
No spaces are allowed in variable names studentMarks student marks
Keywords (like int, for, return) cannot be used as
value int, float
variable names
Case-sensitive → Age and age are different
Count vs count —
variables
using num before
Variable must be declared before use int num; num=10;
declaring
Should be meaningful and easy to understand totalMarks, price x1, abc
Data Types
👉 Data Type in C refers to the type of data that a variable can store.
It tells the compiler:

 What type of value (number, character, etc.) the variable holds?


 How much memory is needed?
 What operations can be performed on that data

Integer Data Type

 The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part).

 We use int keyword to declare the integer variable:

Example : int val;


Note: Modern compilers (like GCC) generally use 32-bit int.

In C language, Type Modifiers (or Type Specifiers) are keywords that change the size, range, or
behavior of a basic data type. They don’t create new types, but modify existing primitive types like
int, char, float, etc.

Modifier Purpose / Effect


signed Specifies that a variable can hold both positive and negative values
unsigned Specifies that a variable can hold only non-negative values (0 or positive)
short Reduces the storage size of an int (usually 2 bytes)
Increases the storage size of int or double
long
(usually 8 bytes for long double, 4–8 bytes for long int)
Integer Data Type Chart:

Data Usage
Size Range Format
Type
(Bytes) (Typical 32-bit) Specifier

 Used to store integer


(whole number)
values (no decimal
–2,147,483,648 to
part).
2,147,483,647
int  By default, int is 4 %d
signed (can hold both
(–2³¹ to 2³¹–1)
positive and negative
values).

Used to store smaller integer –32,768 to 32,767


values, saving memory 2¹⁵ to 2¹⁵–1
short int 2 %hd

 Used when larger range


–2,147,483,648 to
of integers is needed.
2,147,483,647
 Especially useful in
long int 4 or 8 (32-bit) %ld
calculations needing
(–2³¹ to 2³¹–1)
big numbers.
Larger on 64-bit

 Explicitly states that


the variable is signed. –2,147,483,648 to
signed  Same as normal int 2,147,483,647
4 %d
int because int is signed by
default. (–2³¹ to 2³¹–1)

 Can store only positive


unsigned numbers
4 0 to 4,294,967,295 %u
int  (no negative values).

Floating-point Data Type:


Floating-point types are used to store real numbers (numbers with decimal parts).
Unlike integers, they follow the IEEE 754 standard, which represents numbers in scientific notation:
Floating point Data Type Chart:

Data Usage
Size Range Format
Type
(Bytes) (Typical 32-bit) Specifier

 Used for single %f or %e


precision floating-
point numbers. %f → Fixed-point
 Takes 4 bytes (32 notation
bits).
 6 decimal digits ~ 3.4 × 10⁻³⁸ to (e.g., 3.140000)
float precision 4
3.4 × 10³⁸ %e → Scientific
notation

(e.g., 3.140000e+00)

 Double precision
floating-point type.
 More accurate than ~ 1.7 × 10⁻³⁰⁸
float.
double
 15 decimal digits
8 to %lf or %le
precision 1.7 × 10³⁰⁸

 Used for extended


precision calculations.

 Size depends on ~ 3.4 × 10⁻⁴⁹³²


Long
double
compiler: 12-16 To %Le or % Lf
 Very high precision 1.1 × 10⁴⁹³²
(~18+ digits).

Character data type


 This data type is used to store characters.
 These characters are internally stored as integers known as ASCII code.
 Each character has an equivalent ASCII value eg: ´A´ has ASCII value 65

Format
Data Type Memory Size Range
Specifier

signed char 1 -128 to 127 (–2⁷ to 2⁷–1) %c

unsigned char 1 0 to 255 %c


void
 void is a special or empty data type in C.
 It does not store any value.
 Used mainly for functions, pointers, and function parameters.

In short, void means “nothing” or “no data”.

Uses of void

Void Function (No Return Value)

 A function that does not return any value is declared with void.

Syntax:

void function_name()
{
// code
}

Introduction to bool
 bool is used to store Boolean values — true or false.
 Unlike integers, it is specifically meant for logical operations.
 In C, bool is not a built-in keyword in older C standards; it was introduced in C99 via the
header <stdbool.h>.

Syntax

#include <stdbool.h>

bool flag; // declares a boolean variable

 true → 1
 false → 0

Properties of bool

Property Value / Explanation


Size 1 byte (typical)
Range 0 (false) or 1 (true)
Header File <stdbool.h>
Format Specifier %d (for 0 or 1)
Purpose Logical conditions and flags
Program:
#include <stdio.h>
#include <stdbool.h>

void main()
{
// Integer data types
int a = -100;
short int b = -20000;
long int c = 1234567890;
signed int d = -500;
unsigned int e = 40000;

// Floating-point data types


float f = 12.34;
double g = 1234.5678;
long double h = 123456.7890123L;

// Character data types


signed char i = -10;
unsigned char j = 97;

// Display values
printf("----- Integer Data Types -----\n");
printf("int: %d \n", a);
printf("short int: %d \n", b);
printf("long int: %ld \n", c);
printf("signed int: %d \n", d);
printf("unsigned int: %u \n", e);

printf("\n----- Floating Data Types -----\n");


printf("float: %f \n", f);
printf("double: %lf \n", g);
printf("long double: %Lf \n", h);
printf("\n----- Character Data Types -----\n");
printf("signed char: %d \n", i);
printf("unsigned char: %c \n", j);
printf("unsigned char: %d \n", j);

printf("flag1= %d \n",flag1);
printf("flag2= %d \n",flag2);
}

Output:
----- Integer Data Types -----
int: -100
short int: -20000
long int: 1234567890
signed int: -500
unsigned int: 40000

----- Floating Data Types -----


float: 12.340000
double: 1234.567800
long double: 123456.789012

----- Character Data Types -----


signed char: -10
unsigned char: a
unsigned char: 97

flag1= 1
flag2= 0
C - OPERATORS
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition between two operands.

C programming has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:

Operators in C programming
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Unary Operators
Special Operators

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and
multiplication on numerical values (constants and variables).

Operator Meaning of Operator


+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division( modulo division)

Example #1: Arithmetic Operators

// C Program to demonstrate the working of arithmetic operators


#include <stdio.h>
void main()
{
int a = 9, b = 4, c;

c = a+b;
printf("a+b = %d \n",c);

c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);

c=a/b;
printf("a/b = %d \n",c);

c=a%b;
printf("Remainder when a divided by b = %d \n",c);

Output

a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1

The operators +, - and * computes addition, subtraction and multiplication respectively as you
might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.

The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the


remainder is 1. The % operator can only be used with integers.

C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is = .

Operator Example Same as


= a=b 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
Example: Assignment Operators
// C Program to demonstrate the working of assignment operators
#include <stdio.h>
void main()
{
int a = 5, c;

c = a;
printf("c = %d \n", c);

c += a; // c = c+a
printf("c = %d \n", c);

c -= a; // c = c-a
printf("c = %d \n", c);

c *= a; // c = c*a
printf("c = %d \n", c);

c /= a; // c = c/a
printf("c = %d \n", c);

c %= a; // c = c%a
printf("c = %d \n", c);

Output

c = 5
c = 10
c = 5
c = 25
c = 5
c = 0

C Relational Operators
 A relational operator checks the relationship between two operands. If the relation is true,
it returns 1; if the relation is false, it returns value 0.
 Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0

Example: Relational Operators

// C Program to demonstrate the working of Relational operators

#include <stdio.h>

void main()

int a = 10, b = 20;

printf("a = %d, b = %d\n", a, b);


printf("a == b : %d \n", a == b);

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


printf("a > b : %d \n", a > b);

printf("a < b : %d \n", a < b);


printf("a >= b : %d \n", a >= b);
printf("a <= b : %d \n", a <= b);

Output

a = 10, b = 20
a == b : 0 // false
a != b : 1 // true
a > b : 0 // false
a < b : 1 // true
a >= b : 0 // false
a <= b : 1 // true
Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression
results true or false. Logical operators are commonly used in decision making in C programming.

Operator Meaning of Operator Example


Logical AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)
&&
operands are true && (d > 5)) equals to 0.
Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5)
||
one operand is true || (d > 5)) equals to 1.
Logical NOT. True only if the
! If c = 5 then, expression! (c == 5) equals to 0.
operand is 0

Example: Logical Operators

// C Program to demonstrate the working of logical operators

#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

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


printf("(a == b) && (c < b) equals to %d \n", result);

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


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);


printf("!(a == b) equals to %d \n", result);

result = !(a == b);


printf("!(a == b) equals to %d \n", result);

}
Output

(a == b) && (c > b) equals to 1


(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0

Bitwise Operators
Bitwise operators are used in C programming to perform bit-level operations. They
perform binary operations on operands.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

Bitwise AND
 The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.
 In C Programming, the bitwise AND operator is denoted by &.
I/P AND O/P
0 0 0
Let us suppose the bitwise AND operation of two integers 12 and 25.
0 1 0

1 0 0
12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 1 1 1

Bitwise AND Operation of 12 and 25


00001100
| 00011001
________
00001000 = 8 (In decimal)
Bitwise OR
 The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1.
 In C Programming, bitwise OR operator is denoted by | .

I/P OR O/P
12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 0 0 0
0 1 1
Bitwise OR Operation of 12 and 25
00001100 1 0 1
| 00011001
________ 1 1 1
00011101 = 29 (In decimal)

Bitwise XOR (exclusive OR) Operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It
is denoted by ^.

12 = 00001100 (In Binary) I/P X-OR


25 = 00011001 (In Binary) O/P
Bitwise XOR Operation of 12 and 25 0 0 0
00001100 0 1 1
^ 00011001
________ 1 0 1
00010101 = 21 (In decimal)
1 1 0

Shift Operators

There are two shift operators in C programming:

 Right shift operator

 Left shift operator.


Left Shift Operator

 Left shift operator shifts all bits towards left by certain number of specified bits.
 It is denoted by << .
 The bit positions that have been vacated by the left shift operator are filled with 0.
.
Expression Binary Decimal
a=5 00000101 5
a << 1 00001010 10
a << 2 00010100 20
a << 3 00101000 40

Each left shift (<< 1) = multiply by 2

Right Shift Operator

 Right shift operator shifts all bits towards right by certain number of specified bits.
 It is denoted by >>.
 The bit positions that have been vacated by the right shift operator are filled with 0.
 Each shift divides the number by 2 (integer division).

Expression Binary Decimal

a = 20 00010100 20
a >> 1 00001010 10

a >> 2 00000101 5

a >> 3 00000010 2
Complement operator
 Bitwise complement operator is a unary operator (works on only one operand).
 It changes 1 to 0 and 0 to 1. It is denoted by ~.

The bitwise complement (also called 1’s complement) operator .

Consider a= 5 ;

a= 5 0 1 0 1
Complement 1 0 1 0

Binary 1010 = 10 (unsigned)

But if we take it as signed 4-bit, that is a negative number (-6)

In signed binary (two’s complement),

 The first bit (leftmost) is the sign bit


o 0 → positive
o 1 → negative

Here, first bit = 1 → means negative number.

To find the value of a negative number (two’s complement form):

Write down the number: 1 0 1 0

Invert all bits again (to find magnitude): 0 1 0 1

Add 1:

0 1 0 1
+ carry 1
1
0 1 1 0

0110 = 6

Now attach the negative sign → -6

Whenever you apply ~ to a positive number:


~n = -(n + 1)
#include <stdio.h>

void main()
{
int a, b, result;

printf("Enter two numbers: ");


scanf("%d %d", &a, &b);

printf("\n--- Bitwise Operations ---\n");


printf("a & b = %d \n", a & b); // Bitwise AND
printf("a | b = %d \n", a | b ); // Bitwise OR
printf("a ^ b = %d \n", a ^ b ); // Bitwise XOR
printf("~a = %d \n", ~a); // Bitwise NOT (complement)
printf("a << 1 = %d \n", a << 1); // Left Shift
printf("a >> 1 = %d \n", a >> 1); // Right Shift

Output:

Enter two numbers: 5 3

--- Bitwise Operations ---


a&b =1
a|b =7
a^b =6
~a = -6
a << 1 = 10
a >> 1 = 2

Unary Operators
 Unary operators operate on only one variable (or operand).
 They’re mostly used to increment, decrement, negate, or get properties of a value.
Operator Meaning Example Explanation
+ Unary plus +a Indicates the number is positive
- Unary minus -a Changes the sign of the number
++ Increment ++a or a++ Increases the value by 1
-- Decrement --a or a-- Decreases the value by 1
! Logical NOT !a True → False, False → True
~ Bitwise NOT ~a Flips all bits (1 → 0, 0 → 1)
sizeof Size of a data type or variable sizeof(a) Returns number of bytes used

Increment and Decrement Operators


These operators are used to increase or decrease a variable’s value by 1.

Operator Description Example Effect


++ Increment Operator a++ or ++a Adds 1 to the variable
-- Decrement Operator a-- or --a Subtracts 1 from the variable

Two Types — Pre and Post Forms

When Increment/Decrement
Type Syntax Example
Happens

Pre-Increment ++a Value is increased first, then used If a=5, then b = ++a → a=6,
b=6

Post-Increment a++ Value is used first, then increased If a=5, then b = a++ → b=5,
a=6

Pre-Decrement --a Value is decreased first, then used If a=5, then b = --a → a=4,
b=4
Post- a-- Value is used first, then decreased If a=5, then b = a-- → b=5,
Decrement a=4
#include <stdio.h>

void main()
{
int a = 5, b;

printf("Initial value of a = %d \n", a);

b = ++a; // Pre-increment
printf("After ++a: a = %d, b = %d \n", a, b);

b = a++; // Post-increment
printf("After a++: a = %d, b = %d \n", a, b);

b = --a; // Pre-decrement
printf("After --a: a = %d, b = %d \n", a, b);

b = a--; // Post-decrement
printf("After a--: a = %d, b = %d \n", a, b);

Output:
Initial value of a = 5

After ++a: a = 6, b = 6

After a++: a = 7, b = 6

After --a: a = 6, b = 6

After a--: a = 5, b = 6

Special Operators
Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;
The sizeof operator

 The sizeof is an unary operator which returns the size of data (constant, variables, array,
structure etc).
 It is a compile time operator. Syntax: sizeof (data-type or variable)

Example : sizeof Operator

#include <stdio.h>
void main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %d bytes\n", sizeof(e));

Output

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Size of integer type array having 10 elements = 40 bytes

C Ternary Operator (?:) (Conditional Operator)


A conditional operator is also known as ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax

Conditional_Expression ? expression1 : expression2

The conditional operator works as follows:

 The first expression conditionalExpression is evaluated first. This expression evaluates to


1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.
Example : C conditional Operator
#include <stdio.h>
void main()
{
int a, b, max;

printf("Enter two numbers: ");


scanf("%d %d", &a, &b);

max = (a > b) ? a : b;

printf("Largest number is: %d\n", max);

Output:

Enter two numbers: 10 25


Largest number is: 25

Nested Ternary Operator ( largest of 3 numbers)

#include <stdio.h>

int main() {
int a, b, c, largest;

printf("Enter three numbers: ");


scanf("%d %d %d", &a, &b, &c);

largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

printf("Largest number is: %d\n", largest);

return 0;
}

Output:

Enter three numbers: 4 9 6


Largest number is: 9
Address Operator (&)
 The address-of operator & is used to get the memory address of a variable.
 It tells you where a variable is stored in memory. The address is displayed in hexadecimal
(base 16) format.

#include <stdio.h>
void main()
{
int a = 10;

printf("Value of a = %d \n", a);


printf("Address of a = %p \n", &a); // %p used to print address
}

Output:

Value of a = 10
Address of a = 0x7ffeeab3b68c

Value-at-Address Operator (*)


The indirection (dereference) operator * is used to access the value stored at a memory
address. This operator is used with pointers.

#include <stdio.h>
void main()
{
int a = 10;
int *p; // pointer variable declaration

p = &a; // store address of a into pointer p

printf("Value of a = %d \n", a);


printf("Address of a = %p \n", &a);
printf("Pointer p holds = %p \n", p);
printf("Value at address stored in p = %d\n", *p);
}

Value of a = 10
Address of a = 0x7ffeec3b68c
Pointer p holds = 0x7ffeec3b68c
Value at address stored in p = 10
Operator Precedence and Associativity

Precedence decides which operator is evaluated first in an expression when there are
multiple operators.

int a = 5 + 3 * 2;

Here:

 * (multiplication) has higher precedence than +


 So expression is evaluated as:
5 + (3 * 2) → 5 + 6 = 11

Associativity:
➡️ Associativity decides which direction (left or right) the expression is evaluated when
operators of same precedence appear together.

int a = 10 / 2 * 5;

 / and * have same precedence


 Associativity is left to right
 So evaluated as: (10 / 2) * 5 = 25

Precedence Operator Description Associativity


1 () Parentheses (highest) Left to Right
++, --, !, ~, + (unary), - (unary),
2 sizeof, &, * (pointer), () (function Unary operators Right to Left
call), [] (array)
Multiplication, Division,
3 *, /, % Left to Right
Modulus
4 +, - Addition, Subtraction Left to Right
5 <<, >> Bitwise shift Left to Right
6 <, <=, >, >= Relational Left to Right
7 ==, != Equality Left to Right
8 & Bitwise AND Left to Right
9 ^ Bitwise XOR Left to Right
10 | ` Bitwise OR Left to Right

11 && Logical AND Left to Right


Left to Right
12 || Logical OR
`
Precedence Operator Description Associativity

13 ?: Conditional (Ternary) Right to Left

14 =, +=, -=, *=, /=, etc. Assignment Right to Left

15 , Comma (lowest) Left to Right

------- ---------------------------------- -----------------------

Type Conversion
Type Conversion means changing one data type into another while performing operations or
assignments.
There are two main types of type conversion in C:

Type Performed By Also Called Example


1. Implicit Type
Compiler automatically Type Promotion int + float → float
Conversion
2. Explicit Type Done manually by the
Type Casting (float)a / b
Conversion programmer

Implicit Type Conversion (Type Promotion)


In this case, the compiler automatically converts the smaller data type to a larger data type to
prevent data loss. This is called Type Promotion.

#include <stdio.h>
void main( )
{
int a = 5;
float b = 2.5;
float result = a + b; // a (int) → float automatically

printf("Result = %.2f \n", result);

Output: Result = 7.50

Here, int → float (type promotion).


Example 2:
char c = 'A'; // ASCII = 65
float x = 2.5;
printf("%f", c + x); // char → int → float → result = 67.5

Type Promotion Hierarchy in C


Here is the hierarchy used during promotion:

bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float ->
double -> long double

Explicit Type Conversion (Type Casting)


When programmers manually convert one type to another using a cast operator (type).
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:

(data_type) expression;

where, data_type is any valid c data type, and expression may be constant, variable or expression.

For example,

// C program to demonstrate explicit type casting


#include<stdio.h>

void main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

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


}

Output: sum = 2
Example 2:

#include <stdio.h>
void main()
{
int a = 7;
int b = 2;
float c;

c = a / b; // Implicit conversion: result is int → 3.0


printf("Without casting: %.2f\n", c);

c = (float)a / b; // Explicit conversion: 7.0 / 2 = 3.5


printf("With casting: %.2f\n", c);

Output:
Without casting: 3.00
With casting: 3.50

------------------------------------------------- -------------------------------- ----------------------------------


INTRODUCTION TO PROGRAMMING
Unit-1 Question Bank

Short Answer Questions:


1. Define Algorithm. Write the characteristics of an algorithm.
2. Define Keyword and Constant.
3. Define Variable. Write rules for defining variables.
4. What are the basic steps involved in writing a computer program?
5. Define Flowchart. How it is useful in writing the programs.
6. Write differences between Compiler and Interpreter.
7. Write the function of Sizeof operator.
8. Define Time complexity and Space Complexity.
9. Write an algorithm for calculating Area of Equilateral Triangle.
10. Determine the values of the following C expression.
int a = 7, b, c;
b = a++ + 2;
c = ++a + 3;
printf("%d %d %d", a, b, c);

Long Answer Questions:


1. Define Flowchart. Explain different symbols used in flowchart.
Develop a flowchart for calculating Area of Circle. (A = π R2 ) .
2. Give the block diagram of a computer? Explain functionality of each component.
3. Write general Structure of ‘C’ program with example program.
4. What are the different data types available in C? Explain with suitable examples
and memory usage.
5. Define Operator? Explain various category of operators in ‘C’? Give examples.
6. Explain the features of following
a. Machine Language b. Assembly Language c. High Level Language.
7. Write Short notes on
a. Top down Approach b. Bottom up Approach.
8. Explain Type Conversion Concept with Suitable Example.
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Control Statements in C

Control statements in C are the statements that control the flow of execution of a
program — i.e., they decide which part of the code should be executed and when.

They allow the program to make decisions, repeat actions, and jump from one part of
the program to another.

Control statements in C programming language are divided into two types.


1. Selection/ Branching statements (also called Decision making statements) and
2. Iteration/ Looping statements (also called Repetitive statements).

Branching is deciding what actions to take and


Looping is deciding how many times to take a certain action.

Selection/ Branching statements are again divided into two types.


1. Conditional statements:(if, if-else, nested if-else, else-if ladder, switch and
conditional expression/conditional operator)
2. Unconditional statements or Jump Statements (break, continue, goto and
exit)

Iteration/ Looping(Repetitive) statements are as follows: There are three types of loops
in C
programming:
1. while loop
2. do..while loop
3. for loop
Specifying Test Condition for Selection and Iteration
• A test condition used for selection and iteration is expressed as a test
expression.
• If an expression evaluates to true, it is given the value of 1.
• If a test expression evaluates to false, it is given the value of 0.

Relational and Logical operators are available to specify the test condition
used in the control statements of C.

Relational operators are used to specify individual test expression.

Logical operators are used to connect more than one test expression.

1
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Q1. Explain various selection statements available in C language with


examples

Selection/ Branching statements

The simple if
This is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used
in conjunction with an expression. It takes the following form:

Syntax: Flowchart

if(test expression )
{
statement-block;
}
statement - x;

• .If the test expression is true then the statement-block will be executed;
otherwise the statement block will be skipped and the execution will jump
to the statement-x.
• Remember, when the condition is true both the statement-block and the
statement-x are executed in sequence.

Ex 1: Write a program to check whether the given number is +ve or –ve using
simple if statement.

#include<stdio.h>
void main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)

printf(“%d is a positive number\n”, num);


}
}

Output:
Enter a number: 9
9 is a positive number.

2
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The if..else statement


The if..else statement is an extension of the simple if statement.
The general form is:

Syntax Flowchart

if (test-expression)
{
statement block - 1;
}
else
{
statement block - 2;
}
statement-x;

• If the test expression is true, then statement block – 1 is executed and


statement block-2 is skipped.
• Otherwise, the statement block-2 is executed.
• In both the cases, the control is transferred subsequently to the statement-
x.

Ex 2: Write a program to check whether the given number is even or odd using
if..else statement.
#include<stdio.h>
void main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
if(num%2==0)
{
printf("%d is even number\n",num);
}
else
{
printf("%d is odd number\n",num);
}

Output:
Enter a number: 8
8 is even number.

3
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex 3: Write a program to check whether the given year is leap or not using
if..else statement.
#include<stdio.h>
int main()
{
int year;
printf("Enter any year:");
scanf("%d",&year);
if(year%4==0)
printf("%d is leap year\n", year);
else
printf("%d is non leap year\n", year);
return 0;
}

Output:
Enter any year: 1996
1996 is leap year.

Nested if..else statement


When a series of decisions are involved, we may have to use more than one
if..else statement in nested form. Nested if means one if statement with in
another if statement.

Syntax: Flowchart:
if (test expression 1)
{
if (test expression 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

If the test expression1 is false, the statement-3 will be executed; otherwise


it continues to perform the second test. If the test expression-2 is true, the
statement-1 will be executed. Otherwise the statement-2 will be executed and
then the control is transferred to the statement-x.

4
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex 4: Write a C program to find the biggest among three numbers using


nested-if statement.
#include<stdio.h>
main()
{
int a, b, c;
printf("Enter a,b,c values:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is the big\n",a);

else
printf("%d is the big\n",c);
}

else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
}

Output:
Enter a, b, c values: 9 5 17
17 is the big

Multi-way Branching statements


A multi-way branching statement allows the program to choose one among
many possible paths of execution based on the value of an expression or
condition.

In simple terms —

Multi-way branching = “one condition, many choices”.

5
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The if..else..if/Ladder if statement

This is the multi-way selection statement (i.e. used to test multiple


conditions). The syntax is:
if (test-expression 1)
{
statements block-1;
}
else if (test-expression 2)
{
statements block-2;
}
.....................
.....................
else if (test- expression N)
{
statement block-N;
}
else
{
default statements;
}

• All the conditions are evaluated one by one starting from top to bottom, if
any one of the condition evaluating to true then statement group
associated with it are executed and skip other conditions.
• If none of expression is evaluated to true, then the statement or group of
statement associated with the final else is executed.

Flowchart

6
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The following program demonstrates a legal if-else if statement: In this


program we assign grades to students according to the marks they obtained,
using else-if ladder statement.

Ex 5: Write a C program to display student grades using else..if statement.

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

if(marks >= 90)


printf("Grade A");
else if(marks >= 80)
printf("Grade B");
else if(marks >= 70)
printf("Grade C");
else if(marks >= 60)
printf("Grade D");
else
printf("Grade F");
}

Ex: Largest of three numbers

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if(a > b && a > c)


printf("%d is largest", a);
else if(b > c)
printf("%d is largest", b);
else
printf("%d is largest", c);
}

7
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex: Write a C program to calculate the electricity bill based on the number of
units consumed according to the following conditions:

Units Consumed Rate per Unit


0 – 100 units ₹2 per unit
101 – 200 units ₹3 per unit
Above 200 units ₹5 per unit

Input: Number of units consumed


Output: Total electricity bill amount

Program:
#include <stdio.h>
void main()
{
int units;
float amount;

printf("Enter total units consumed: ");


scanf("%d", &units);

if(units <= 100)


{
amount = units * 2.0;
}

else if(units <= 200)


{
amount = (100 * 2.0) + ((units - 100) * 3.0);
}

else
{
amount = (100 * 2.0) + (100 * 3.0) + ((units - 200) * 5.0);
}

printf("Total Electricity Bill = %.2f", amount);


}

Output:
Enter total units consumed: 250
Total Electricity Bill = ₹1050.00

8
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex: Write a C program to find the roots of a quadratic equation of the form
ax² + bx + c = 0

#include <stdio.h>
#include <math.h> // for sqrt() function

void main()
{
float a, b, c, discriminant, root1, root2, realPart, imagPart;

printf("Enter coefficients a, b and c: ");


scanf("%f %f %f", &a, &b, &c);

discriminant = b * b - 4 * a * c;

if (discriminant > 0)
{
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\n");
printf("Root1 = %.2f and Root2 = %.2f", root1, root2);
}
else if (discriminant == 0)
{
// Real and equal roots
root1 = -b / (2 * a);
printf("Roots are real and equal.\n");
printf("Root1 = Root2 = %.2f", root1);
}

9
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

else
{
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary.\n");
printf("Root1 = %.2f + %.2fi and Root2 = %.2f - %.2fi",
realPart, imagPart, realPart, imagPart);
}

Outputs:

Enter coefficients a, b and c: 1 5 6


Roots are real and distinct.
Root1 = -2.00 and Root2 = -3.00

Enter coefficients a, b and c: 1 -2 1


Roots are real and equal.
Root1 = Root2 = 1.00

Enter coefficients a, b and c: 1 2 5


Roots are complex and imaginary.
Root1 = -1.00 + 2.00i and Root2 = -1.00 - 2.00i

10
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The switch statement


The switch statement in C is a multi-way branch statement that allows
a variable or expression to be tested for equality against a list of constant values.

It is a simplified version of if..else..if block that evaluates a single


variable.

The syntax of switch statement is:


switch(expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;

...
default:
// statements
}

• The expression inside the switch is evaluated once.


• Its result is compared with each case constant.
• When a match is found, the statements under that case execute.
• The break statement stops further checking and exits the switch.
• If no match is found, the default case (if present) executes.

.Flow Chart:

11
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex : Write a C program to implement simple calculator using switch


statement.

#include <stdio.h>
int main()
{
int choice;
float a, b, result;

printf("1.Add\n2.Subtract\n3.Multiply\n4.Divide\n");
printf("Enter choice: ");
scanf("%d", &choice);

printf("Enter two numbers: ");


scanf("%f %f", &a, &b);

switch(choice)
{
case 1:
result = a + b;
printf("Sum = %.2f", result);
break;
case 2:
result = a - b;
printf("Difference = %.2f", result);
break;
case 3:
result = a * b;
printf("Product = %.2f", result);
break;
case 4:
if(b != 0)
printf("Division = %.2f", a / b);
else
printf("Division by zero not allowed");
break;
default:
printf("Invalid choice");
}
}

12
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Output:

// case 1 addition
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 1
Enter two numbers: 5 7
Sum = 12.00

// case 2 subtraction
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 2
Enter two numbers: 10 4
Difference = 6.00

// Case 4 (Division by Zero)


Enter choice: 4
Enter two numbers: 8 0
Division by zero not allowed

13
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Q3. Explain various iterative statements available in C language with


examples.

Looping Structures
The programmer sometimes interested to repeat a set statements a number of
times. This is known as looping in a computer program.
A loop is a group of instructions that computer executes repeatedly
while some loop continuation conditions remains true.

Two ways of repetitions are possible:


1. Counter controlled loops
2. Sentinel controlled loops
Counter controlled loops are sometimes called definite loops because we know
in advance exactly how many times the loop will be executed.
Sentinel controlled loops are sometimes called indefinite loops because it is not
known in advance how many times the loop will be executed.

General Requirements for a Loop

Every loop — whether it’s a for, while, or do-while — needs three basic parts
to work correctly.

Part Purpose Example


int i =
1. Initialization Set the starting value 1;
2. Condition / Test Expression Decide whether to continue or stop i <= 5
3. Update / Increment or Change the loop variable to move toward i++
Decrement the end

C supports the following types of loops:


1. The while loop
2. The do..while loop
3. The for loop
Advantages
Reduce length of Code
Take less memory space.
Burden on the developer is reducing.
Time consuming process to execute the program is reduced.

14
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The While Loop


• The while loop is a pre-test or entry-controlled loop. A while loop is
used when you want to repeat a set of statements as long as a condition
is true.
• It uses test expression to control the loop.

syntax:
while (test expression)
{
body of the loop;
}
statement-x;

How while loop works?


• The test expression / condition is checked first.
• If it’s true, the loop body executes.
• After executing, it checks the condition again.
The loop continues until the condition becomes false. When the test
expression is false, the while loop is terminated.

Flowchart

Write a C program to print 1 to 10 numbers using while loop.


#include<stdio.h>
main( )
{
int n=1;
while(n<=10)
{
printf(“%d\t”,n);
n++;
}
}

Output: 1 2 3 4 5 6 7 8 9 10

15
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Step by Step Execution:

Step Value of i Condition (i ≤ 5) Action Output


1 1 true print 1 1
2 2 true print 2 2
3 3 true print 3 3
4 4 true print 4 4
5 5 true print 5 5
6 6 false stop —

Example 2: Sum of first 5 numbers

#include <stdio.h>

void main()
{
int i = 1, sum = 0;

while (i <= 5)
{
sum = sum + i;
i++;
}

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


}

Output: Sum = 15

do. while Statement


• do-while loop is similar to while loop,
• A do…while loop is a post-tested loop.
That means — the condition is checked after the loop body executes.
So, the loop will always run at least once, even if the condition is false.

16
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Syntax Flowchart

do
{
body of the loop;
}
while (expression);

statement -x;

How do-while loop works?

1. Execute the statements inside the do block first.


2. Then check the condition after the body.
3. If the condition is true, go back and repeat the body.
4. If the condition is false, the loop stops.

The following example illustrates the use of do-while loop.


#include<stdio.h>
main()
{
int num=1;
do
{
printf( “ %d\t”, num);
num++;
}while(num<=5);
}

Output: 1 2 3 4 5

17
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The For Statement

• It most general looping construct in C.


• The for loop is commonly used when the number of iterations are exactly
known. The syntax of a for loop is
• It combines initialization, condition, and update — all in a single line.

Syntax:
for(initialization; test expression; increment /decrement/ update)
{
body of the loop;
}

Flowchart

The loop header contains three parts:


o an initialization,
o a test condition, and
o incrementation(++) / decrementation(˗ ˗) /update.

Part Purpose Example

Initialization Sets the starting value int i = 1;

Condition Tests whether to continue or stop i <= 5

Update Changes the variable after each iteration i++

18
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

How for loop works?



First the loop initialization statement is executed.

Then, the test expression is evaluated. If the test expression is false, for
loop is terminated.

But if the test expression is true, codes inside the body of for loop is
executed and the update expression is executed. This process repeats until
the test expression becomes false.

Note: In for loop everything is optional but mandatory to place two semicolons
(; ;)

Example: Print numbers from 1 to 5

#include <stdio.h>

void main()
{
for (int i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
}
Output:
1
2
3
4
5

Example 2: Sum of first 5 numbers

#include <stdio.h>

void main()
{
int i, sum = 0;

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


{
sum = sum + i;
}

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


}

19
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Nested loops
A nested loop means one loop inside another loop.
The inner loop runs completely for every single iteration of the outer loop.

General syntax for nested for loops are:

for (initialization; test expression; updation) //outer loop


{
for (initialization; test expression; updation)
//inner loop
{
body of inner for loop;
}
}
Note: generally nested for loops are used to generate patterns.

Here is an example program that uses nested loops

#include <stdio.h>

int main()
{
int i, j;

for (i = 1; i <= 3; i++) { // Outer loop


for (j = 1; j <= 2; j++)
{
// Inner loop
printf("i = %d, j = %d\n", i, j);
}
}

return 0;
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2

20
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Example 2: Pattern Printing (Stars)

#include<stdio.h>
main()
{

int i,j,n;
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
}

Output:
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *

Q4. Explain various Unconditional statements available in C language


with examples

Unconditional branching statements

The break statement


The break statement is used to exit immediately from a loop or switch statement
— even if the condition is still true.

break;

21
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Following figure shows the sequences in break statements

The following example illustrates the use of break;

#include <stdio.h>
void main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
break; // loop stops when i = 5
printf("%d ", i);
}

}
Output
1 2

The continue statement

The continue statement skips the remaining code inside the current loop and
jumps to the next iteration of that loop.

continue;

Following figure shows the sequence of actions in continue statement

22
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The following example illustrates the use of continue;

#include <stdio.h>
void main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
continue; // loop stops when i = 5
printf("%d ", i);
}

Output

1 2 3 4 6 7 8 9 10

Difference Between break and continue Statements

Feature break continue

Used to terminate the loop or Used to skip the remaining statements of the
Purpose
switch completely. current iteration.
Control Transfers control outside the Transfers control to the beginning of the next
Transfer loop/switch. iteration of the loop.
Effect on The loop stops running The loop continues running, but skips the
Loop immediately. current iteration.
for, while, do-while, and for, while, and do-while loops only (not in
Usage In
switch statements. switch).

Common Use To exit when a condition is met. To ignore or skip a particular case/iteration.

Example
If i==5, loop prints up to 4 only. If i==5, loop skips 5 but prints the rest.
Output

23
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

The goto statement

• The goto statement is used to jump directly to another part of the


program. It transfers the program control to a labeled statement within
the same function.

. The syntax of goto statement is:

• label is an identifier followed by a colon :.

• When goto is executed, control jumps to the label directly.

The following example illustrates the use of goto;

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

if(num < 0)
goto negative;
printf("You entered a positive number.\n");

negative:
printf("You entered a negative number.\n");
return 0;
}

Output
Enter a number: -3
You entered a negative number.

24
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Exercise Programs
Ex : Write a C program to check whether the given number is prime or not.

Concept
A prime number is a number that is greater than 1 and divisible only by 1
and itself.
👉 Example: 2, 3, 5, 7, 11, 13, …

Non-prime numbers are called composite numbers (like 4, 6, 8, 9, 10…).

void main()
{
int num, i, count = 0;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1)
{
printf("Not a prime number.\n");

for (i = 2; i <= num / 2; i++)


{
if (num % i == 0)
{
count++;
break; // No need to check further
}
}

if (count == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
}

Output
Enter a number: 13
13 is Prime.

Enter a number: 22
22 is not a prime number.

25
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Program: Sum of the Digits of a Number

#include <stdio.h>
int main()
{
int num, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
while(num > 0)
{
digit = num % 10; // Get the last digit
sum = sum + digit; // Add it to sum
num = num / 10; // Remove the last digit
}
printf("Sum of digits = %d\n", sum);
return 0;
}

Output: Enter a number: 1234


Sum of digits = 10

26
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex: Write a C program to check whether the given number is Armstrong or


not.

What is an Armstrong Number?


A number is called an Armstrong number if the sum of cubes of its digits is
equal to the number itself.

Examples: 153 ,370

#include<stdio.h>
void main( )
{
int n,rem,sum=0,temp;
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(n != 0)
{
rem = n%10;
sum = sum+(rem*rem*rem);
n = n/10;
}
if(sum == temp)
printf("%d is Armstrong\n", temp);
else
printf("%d is not an Armstrong\n", temp);
}

Output
Enter a number: 153
153 is Armstrong

27
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex: Write a C program to print reverse of given number using while loop.

#include <stdio.h>
int main()
{
int num, reverse = 0, digit;

printf("Enter a number: ");


scanf("%d", &num);
while(num > 0)
{
digit = num % 10; // Get the last digit
reverse = reverse * 10 + digit; // Add digit to reverse
num = num / 10; // Remove last digit
}

printf("Reversed number = %d\n", reverse);


return 0;
}

Output
Enter a number: 5214
Reversed number = 4125
---------------------------

Write a C program to check the given number is palindrome number using


while loop.

What is a Palindrome Number?


👉 A number is called a palindrome if it reads the same backward and forward

#include <stdio.h>
int main()
{
int num, reverse = 0, digit,temp;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;

while(num > 0)
{
digit = num % 10; // Get the last digit
reverse = reverse * 10 + digit; // Add digit to reverse
num = num / 10; // Remove last digit
}

28
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

if (temp==reverse)
{
printf("%d is palindrome number",temp);
}
else
{
printf("%d is not palindrome number",temp);
}

return 0;
}

Output:
Enter a number: 258
258 is not palindrome number

Enter a number: 212


212 is palindrome number

Ex: Write a C program to print the factorial of a given number.

#include <stdio.h>
#include<stdio.h>
int main( )
{
int n,i;
long int fact=1;
printf("Enter a number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
fact = fact*i;
}
printf("Factorial of %d is %ld\n", n, fact);
return 0;
}

Output
Enter a number: 5
Factorial of 5 is 120

Enter a number:10
Factorial of 10 is 3628800

29
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Ex: Write a C program to print the following pattern

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

#include<stdio.h>
int main()
{
int n, i, j; //i and j represents rows and columns respectively
printf("Enter number of rows:" );
scanf("%d",&n);

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

Enter number of rows:5


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
---------------------------

Ex: Write a C program to print the Floyds triangle.


Floyd’s Triangle is a right-angled triangular pattern of numbers, where the numbers are
printed sequentially starting from 1.

Example (for 5 rows):


1
23
456
7 8 9 10
11 12 13 14 15

30
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

include <stdio.h>
int main()
{
int n, i, j, num = 1;

printf("Enter number of rows: ");


scanf("%d", &n);

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


{ // Outer loop for rows
for(j = 1; j <= i; j++)
{ // Inner loop for columns
printf("%d ", num); // Print the number
num++; // Increment number
}
printf("\n"); // Move to next line
}

return 0;
}

Enter number of rows: 5


1
23
456
7 8 9 10
11 12 13 14 15

Multiplication Table using for loop

#include <stdio.h>
void main()
{
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
printf("Multiplication Table of %d:\n", num);
for(i = 1; i <= 10; i++)
{
printf("%d x %d = %d\n", num, i, num * i);
}

}
31
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Enter a number: 5
Multiplication Table of 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

C Program: Check Perfect Number

A Perfect Number is a number that is equal to the sum of its proper divisors (excluding
the number itself).

Examples:

• 6 → Divisors = 1, 2, 3 → 1 + 2 + 3 = 6 → ✔ Perfect
• 28 → Divisors = 1, 2, 4, 7, 14 → 1 + 2 + 4 + 7 + 14 = 28 → ✔ Perfect
• 12 → Divisors = 1, 2, 3, 4, 6 → 1 + 2 + 3 + 4 + 6 = 16 → ❌ Not Perfect

#include <stdio.h>
int main()
{
int num, i, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
for(i = 1; i <= num / 2; i++)
{ // check divisors up to num/2
if(num % i == 0) // if i divides num
sum = sum + i; // add to sum
}

if(sum == num)
printf("%d is a Perfect Number.\n", num);
else
printf("%d is not a Perfect Number.\n", num);

return 0;
}

32
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML

Output:

Enter a number: 28
28 is a Perfect Number.

Enter a number: 25
25 is not a Perfect Number.

Comparison between for and do, while loops

Feature for loop while loop do-while loop


for(initialization;
do { ... }
Syntax condition; while(condition)
while(condition);
increment)
Done inside the loop Done before the
Initialization Done before the loop
header loop
Checked before each Checked before Checked after each
Condition Check
iteration each iteration iteration
0 (if condition is false 0 (if condition is 1 (body executes at
Minimum Iterations
initially) false initially) least once) ✅
When the number of When you want the
When the number of
When Used iterations is loop to run at least
iterations is known
unknown once
Increment/Decrement In header (compact) Inside the loop body Inside the loop body
Useful for menu-
Simple, but needs
Readability Most compact form driven or validation
setup before loop
tasks
do { ... }
Example for(i=1;i<=5;i++) while(i<=5)
while(i<=5);

Pre-test loop: The condition can be tested- At the beginning is called as pre-test
or entry- controlled loop. Example: while and for loops.

Post-test loop: The condition can be tested - At the end is called as post-test or
exit- controlled loop. Example: do-while loop.

33

You might also like