0% found this document useful (0 votes)
17 views38 pages

Unit-I PPS

The document outlines the syllabus and key concepts of programming for problem solving, focusing on the C programming language. It covers topics such as compilers, algorithms, flowcharts, program design, data types, variables, and basic input/output operations. Additionally, it explains the structure of a C program, including various sections and examples of code implementation.

Uploaded by

mandershikan
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)
17 views38 pages

Unit-I PPS

The document outlines the syllabus and key concepts of programming for problem solving, focusing on the C programming language. It covers topics such as compilers, algorithms, flowcharts, program design, data types, variables, and basic input/output operations. Additionally, it explains the structure of a C program, including various sections and examples of code implementation.

Uploaded by

mandershikan
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

1

PPS Unit-I
Unit-I Programming for Problem Solving
Syllabus:
Introduction to Programming: Compilers, compiling and executing a program.
Representation of Algorithm, Flowchart/ Pseudocode with examples, Program design
and structure of C programming. Variables, Data types Operators, expressions and
precedence, Expression evaluation, Storage classes, type conversion. I/O: Simple input
and output with scanf and printf, formatted I/O, Introduction to stdin, stdout and stderr.
Conditional Branching: Branching with if, if-else, nested if-else, else-if ladder,
switchcase, goto.

Notes:
Compilers, Compiling and executing a program:
A compiler is a software that translates source code written in a high-level programming
language (like C,C++ or Java) into a lower-level language (such as machine code) that a
computer's central processing unit (CPU) can directly understand and execute.
Compiling means translating the C program into machine understandable format.
Execution of the program is dependent on the environment where we are working.

Representation of Algorithm, Flowchart/ Pseudocode with examples:


1. Algorithm:

An algorithm is a step-by-step procedure to solve a problem or perform a task. This is the


simplest and most common form. It uses plain English (or any human language) to
describe each step logically and clearly.

Example 1: Algorithm to find the sum of two numbers

Step 1: Start

Step 2: Read two numbers A and B

Step 3: Calculate SUM = A + B

Step 4: Display SUM

Step 5: Stop

Easy to understand but not precise for a computer to execute directly.

2. Pseudocode Representation

Pseudocode looks like a simplified programming language — it’s structured and close to
code, but not bound by syntax of any real programming language.

Example:

BEGIN

INPUT A, B
2
PPS Unit-I
SUM ← A + B

PRINT "Sum =", SUM

END

Readable by humans, easy to convert into a real program.

3. Flowchart Representation

A flowchart uses symbols and arrows to visually represent the flow of control in an
algorithm.

Common Flowchart Symbols:

Symbol Meaning

● Oval Start / Stop

⬛ Parallelogr Input / Output


am
▢ Rectangle Process / Calculation

● Diamond Decision (Yes/No, True/False)


⬛ Arrow Flow direction

Example: Flowchart for Sum of Two Numbers

Example 2: Find the Largest of Two Numbers

1. Algorithm (Step-by-Step Form)

Step 1: Start

Step 2: Read two numbers A and B

Step 3: If A > B, then

Print "A is largest"


3
PPS Unit-I
Else

Print "B is largest"

Step 4: Stop

2. Pseudocode Representation

BEGIN

INPUT A, B

IF A > B THEN

PRINT "A is largest"

ELSE

PRINT "B is largest"

ENDIF

END

3. Flowchart Representation

Program Design and structure of C Program:


Program design means planning and organizing the steps of a program before writing
actual code. It helps you write clear, error-free, and efficient programs.
4
PPS Unit-I

Steps in Program Design

Step Description

1. Problem Definition Clearly understand what the program must do.

2. Analysis Identify input, process, and output.

Write a step-by-step method (algorithm or


3. Algorithm Design
pseudocode).

4. Flowchart Creation Draw a flowchart for better understanding.

5. Coding Write the program in C language.

6. Compilation and
Compile (check for errors) and run the program.
Execution

7. Testing and Debugging Verify correctness and remove errors.

8. Documentation Comment and explain code for readability.

Structure of a C Program

A C program has a well-defined structure consisting of several sections.

1. Documentation Section

2. Link Section

3. Definition Section

4. Global Declaration Section

5. main() Function Section

6. Subprogram Section (User Functions)

Let’s go through each

1. Documentation Section

 Includes comments that describe what the program does.

 Helps others understand your code.

/* Program: Sum of Two Numbers

Author : ABC

Date : 05-Oct-2025
5
PPS Unit-I
Purpose: To add two numbers entered by user */

2. Link Section

 Includes header files using #include.

 These provide access to built-in functions (like printf, scanf, etc.).

#include <stdio.h>

3. Definition Section

 Defines constants and macros using #define.

#define PI 3.14159

#define MAX 100

4. Global Declaration Section

 Declares global variables and function prototypes accessible to all functions.

int total; // global variable

void display(void); // function prototype

5. main() Function Section

 Every C program must have one main() function.

 It is the entry point where execution begins.

int main() {

int a, b, sum;

printf("Enter two numbers: ");

scanf("%d%d", Ca, Cb);

sum = a + b;

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

return 0;

6. Subprogram Section (User-defined Functions)

 Functions defined by the user for modular programming.

void display(void) {

printf("\nThis is a user-defined function.");

}
6
PPS Unit-I
Example Program:

#include <stdio.h>

int main()

// This prints "Hello World"

printf("Hello World");

return 0;

Output

Hello World

Header Files Inclusion - Line 1 [#include <stdio.h>]

The first component is the Header files in a C program. A header file is a file with
extension .h which contains C function declarations and macro definitions to be shared
between several source files. All lines that start with # are processed by a preprocessor
which is a program invoked by the compiler. In the above example, the preprocessor
copies the preprocessed code of stdio.h to our file. The .h files are called header files in
C.
Some of the C Header files:

 stddef.h - Defines several useful types and macros.

 stdint.h - Defines exact width integer types.

 stdio.h - Defines core input and output functions

 stdlib.h - Defines numeric conversion functions, pseudo-random number


generator, and memory allocation

 string.h - Defines string handling functions

 math.h - Defines common mathematical functions.

Main Method Declaration - [int main()]

The next part of a C program is the main() function. It is the entry point of a C program and
the execution typically begins with the first line of the main(). The empty brackets indicate
that the main doesn't take any parameter. The int that was written before the main
indicates the return type of main(). The value returned by the main indicates the status of
program termination.

Body of Main Method [enclosed in {}]

The body of the main method in the C program refers to statements that are a part of the
main function. It can be anything like manipulations, searching, sorting, printing, etc. A
7
PPS Unit-I
pair of curly brackets define the body of a function. All functions must start and end with
curly brackets.

Comment - [// This prints "Hello World"]

The comments are used for the documentation of the code or to add notes in your
program that are ignored by the compiler and are not the part of executable program .

Statement - [printf("Hello World");]

Statements are the instructions given to the compiler. In C, a statement is always


terminated by a semicolon (;). In this particular case, we use printf() function to instruct
the compiler to display "Hello World" text on the screen.

Return Statement - [return 0;]

The last part of any C function is the return statement. The return statement refers to the
return values from a function. This return statement and return value depend upon the
return type of the function. The return statement in our program returns the value from
main(). The returned value may be used by an operating system to know the termination
status of your program. The value 0 typically means successful termination.

Variables:
A variable in C is a named piece of memory which is used to store data and access it
whenever required. It allows us to use the memory without having to memorize the exact
memory address.

To create a variable in C, we have to specify a name and the type of data it is going to
store in the syntax.

data_type name;

C provides different data types that can store almost all kinds of data. For example, int,
char, float, double, etc.

int num;

char letter;

float decimal;

In C, every variable must be declared before it is used. We can also declare multiple
variables of same data type in a single statement by separating them using comma as
shown:

data_type name1, name2, name3, ...;

Rules for Naming Variables in C

We can assign any name to a C variable as long as it follows the following rules:

 A variable name must only contain letters, digits, and underscores.


8
PPS Unit-I
 It must start with an alphabet or an underscore only. It cannot start with a digit.

 No white space is allowed within the variable name.

 A variable name must not be any reserved word or keyword.

 The name must be unique in the program.

C Variable Initialization

Once the variable is declared, we can store useful values in it. The first value we store is
called initial value and the process is called Initialization. It is done using assignment
operator (=).

int num;

num = 3;

It is important to initialize a variable because a C variable only contains garbage value


when it is declared. We can also initialize a variable along with declaration.

int num = 3;

Note: It is compulsory that the values assigned to the variables should be of the same
data type as specified in the declaration.

Accessing Variables

The data stored inside a C variable can be easily accessed by using the variable's name.

Example:

#include <stdio.h>

int main() {

// Create integer variable

int num = 3;

// Access the value stored in variable

printf("%d", num);

return 0;

Output

Changing Stored Values

We can also update the value of a variable with a new value whenever needed by using
the assignment operator =.
9
PPS Unit-I
Example:

#include <stdio.h>

int main() {

// Create integer variable

int n = 3;

// Change the stored data

n = 22;

// Access the value stored in variable

printf("%d", n);

return 0;

Output

22

60

Memory Allocation of C Variables

When a variable is declared, the compiler is told that the variable with the given name
and type exists in the program. But no memory is allocated to it yet. Memory is allocated
when the variable is defined.

The size of memory assigned for variables depends on the type of variable. We can check
the size of the variables using sizeof operator.

Example:

#include <stdio.h>

int main() {

int num = 22;

// Finding size of num

printf("%d bytes", sizeof(num));

return 0;

Output

4 bytes

Scope of Variables in C
10
PPS Unit-I
A variable can be accessed using its name anywhere in a specific region of the program
called its scope. It is the region of the program where the name assigned to the variable
is valid.

A scope is generally the area inside the {} curly braces.

Example:

// num cannot be accessed here

int main() {

// num cannot be accessed here

// Variable declaration

int num;

// Cannot be accessed here either

return 0;

Constants in C

C also provides some variables whose value cannot be changed. These variables are
called constants and are created simply by prefixing const keyword in variable
declaration.

Syntax:

const data_type name = value;

Constants must be initialized at the time of declaration.

Data Types in C

Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc.

Example:

int number;

The above statement declares a variable with name number that can store
integer values.

C is a statically typed language where each variable's type must be specified at the
declaration and once specified, it cannot be changed.
11
PPS Unit-I

Integer Data Type

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

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

 Size: 4 bytes

 Format Specifier: %d

Format specifiers are the symbols that are used for printing and scanning values of given
data types.

Example:

We use int keyword to declare the integer variable:

int val;

We can store the integer values (literals) in this variable.

#include <stdio.h>

int main() {

int var = 22;

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

return 0;

Output

var = 22

A variable of given data type can only contains the values of the same type. So, var can
only store numbers, not text or anything else.
12
PPS Unit-I
The integer data type can also be used as:

1. unsigned int: It can store the data values from zero to positive numbers, but it
can’t store negative values

2. short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.

3. long int: Larger version of the int datatype so can store values greater than int.

4. unsigned short int: Similar in relationship with short int as unsigned int with int.

Note: The size of an integer data type is compiler dependent. We can use sizeof operator
to check the actual size of any data type. Here, we are discussing the sizes according to
c4-bit compilers.

Character Data Type

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

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

 Size: 1 byte

 Format Specifier: %c

Example:

#include <stdio.h>

int main() {

char ch = 'A';

printf("ch = %c", ch);

return 0;

Output

ch = A

Float Data Type

In C programming, float data type is used to store single precision floating-point values.
These values are decimal and exponential numbers.

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

 Size: 4 bytes

 Format Specifier: %f
13
PPS Unit-I
Example:

#include <stdio.h>

int main() {

float val = 12.45;

printf("val = %f", val);

return 0;

Output

val = 12.450000

Double Data Type

The double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It can easily accommodate about 16 to 17 digits after or
before a decimal point.

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

 Size: 8 bytes

 Format Specifier: %lf

Example:

#include <stdio.h>

int main() {

double val = 1.4521;

printf("val = %lf", val);

return 0;

Output

val = 1.452100

Void Data Type

The void data type in C is used to indicate the absence of a value. Variables of void data
type are not allowed. It can only be used for pointers and function return type and
parameters.

Example:
14
PPS Unit-I
void fun(int a, int b){

// function body

where function fun is a void type of function means it doesn't return any value.

Size of Data Types in C

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

Example

#include <stdio.h>

int main(){

// Use sizeof() to know size the data types

printf("The size of int: %d\n",sizeof(int));

printf("The size of char: %d\n",sizeof(char));

printf("The size of float: %d\n",sizeof(float));

printf("The size of double: %d",sizeof(double));

return 0;

Output

The size of int: 4

The size of char: 1

The size of float: 4

The size of double: 8

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

Format
Data Type Size (bytes) Range Specifier

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


15
PPS Unit-I
Format
Data Type Size (bytes) Range Specifier

unsigned short int 2 0 to 65,535 %hu

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

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

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

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

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

unsigned long long 0 to


8 %llu
int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

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

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

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

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

Literals in C
16
PPS Unit-I
In C, literals are constant values assigned to variables. They represent fixed values that
cannot be changed. Literals occupy memory but do not have references like variables.
Often, the terms constants and literals are used interchangeably.

Operators in C
1. Arithmetic Operators

Used for mathematical operations.

Operator Meaning Example (a=10, b=5) Result

+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division (quotient) a/b 2

% Modulus (remainder) a % b 0

++ Increment by 1 a++ 11

-- Decrement by 1 b-- 4

2. Relational Operators

Used to compare two values, return 1 (true) or 0 (false).

Operator Meaning Example (a=10, b=5) Result

== Equal to a == b 0

!= Not equal to a != b 1

> Greater than a>b 1

< Less than a<b 0

>= Greater than or equal a >= b 1

<= Less than or equal a <= b 0

3. Logical Operators

Used in decision making.


17
PPS Unit-I
Operator Meaning Example (a=1, b=0) Result

CC Logical AND a CC b 0

|| Logical Or A || b 1

! Logical NOT !a 0

4. Bitwise Operators

Work on bits (0 and 1).

Operator Meaning Example (a=6 (0110), b=3 (0011)) Result

C Bitwise AND a C b → 0110 C 0011 2 (0010)

| Bitwise OR Bitwise OR 7(0111)

^ Bitwise XOR a ^ b → 0110 ^ 0011 5 (0101)

~ Bitwise NOT ~a -7

<< Left shift a << 1 12

>> Right shift a >> 1 3

5. Assignment Operators

Used to assign or update values.

Operator Example (a=10) Equivalent to

= a=5 Assign 5

+= a += 5 a=a+5

-= a -= 5 a=a-5

*= a *= 5 a=a*5

/= a /= 5 a=a/5

%= a %= 5 a=a%5

6. Conditional (Ternary) Operator

Shorthand for if-else.


18
PPS Unit-I
(a > b) ? a : b; // returns the greater number

7. Special Operators

Operator Description

sizeof Returns size (in bytes) of a datatype/variable

C Address-of operator (gives memory address)

* Pointer dereference (value at address)

. Access structure/union member

-> Access structure/union member via pointer

, Comma operator (evaluates multiple expressions)

Operator Precedence s Associativity in C

Precedence (Highest
Operators Associativity
→ Lowest)

1 (highest) (), [], ->, ., ++, -- (postfix) Left to Right

++, -- (prefix), + (unary), - (unary), !, ~, *


2 (dereference), C (address), sizeof, type cast Right to Left
(type)

3 *, /, % Left to Right

4 +, - Left to Right

5 <<, >> Left to Right

6 <, <=, >, >= Left to Right

7 ==, != Left to Right

8 C (bitwise AND) Left to Right

9 ^ (bitwise XOR) Left to Right

10 | (bitwise OR) Left to Right

11 CC (logical AND) Left to Right


19
PPS Unit-I
Precedence (Highest
Operators Associativity
→ Lowest)

12 || (logical OR) Left to Right

13 ?: (ternary conditional) Right to Left

14 =, +=, -=, *=, /=, %= , <<=, >>=, C=, ^=, ` Right to Left

15 (lowest) , (comma operator) Left to Right

Expression Evaluation:
Example 1: Arithmetic Expression

int a = 10, b = 5, c = 2;

int result = a + b * c;

printf("%d", result);

Evaluation:

= 10 + 5 * 2

= 10 + 10

= 20

Output: 20

Example 2: With Parentheses

int result = (a + b) * c;

Evaluation:

= (10 + 5) * 2

= 15 * 2

= 30

Output: 30

Example 3: Mixed Expression

int x = 4, y = 3, z = 2;

int result = x + y * z / x;

Evaluation Steps:

1. y * z = 3 * 2 = 6
20
PPS Unit-I
2. 6 / x = 6 / 4 = 1 (integer division)

3. x + 1 = 4 + 1 = 5

Output: 5

Example 4: Relational C Logical Expression

int a = 5, b = 10, c = 15;

int result = (a < b) CC (b < c);

printf("%d", result);

Evaluation:

(a < b) → 1 (true)

(b < c) → 1 (true)

1 CC 1 → 1

Output: 1

Example 5: Conditional Expression

int a = 25, b = 40;

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

printf("Max = %d", max);

Evaluation:

(a > b) → false

So, max = b = 40

Output: Max = 40

Example 6: Increment/Decrement

int x = 5;

int y = ++x + x++;

Evaluation:

1. ++x → Pre-increment → x = 6, use 6

2. x++ → Post-increment → use 6, then x = 7

3. y = 6 + 6 = 12

Final: x = 7, y = 12

* Example of Associativity
˛
C
21
PPS Unit-I
int a = 5, b = 10, c = 15;

int result = a < b < c;

Left to Right:

a<b→1

1 < c → 1 (true)

Output: 1
Example : Assignment Operators

int a, b, c;

a = b = c = 10;

= has right-to-left associativity.

Evaluation:

a = (b = (c = 10))

So,

c = 10

b = 10

a = 10

Output: a = 10, b = 10, c = 10

Storage classes:
A storage class in C defines the scope, lifetime, and visibility of a variable or function
that is, where it can be accessed and how long it exists in memory.

Types of Storage Classes

Storage Memory
Keyword Default Value Scope Lifetime
Class Location

Garbage Until function


Automatic auto Stack Local
(undefined) ends

CPU Register / Garbage Until function


Register register Local
Stack (undefined) ends

Local or Till program


Static static Data Segment 0
Global ends

Till program
External extern Data Segment 0 Global
ends
22
PPS Unit-I

1. Automatic Storage Class (auto)

 Default storage class for all local variables.

 Stored in stack memory.

 Created when the function is called, destroyed when it ends.

#include <stdio.h>

void test() {

auto int a = 10; // or simply int a = 10;

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

int main() {

test();

return 0;

Output:

a = 10

You can omit auto since it’s the default for local variables.

2. Register Storage Class (register)

 Suggests that the variable be stored in a CPU register instead of RAM (for faster
access).

 Used for frequently accessed variables (like loop counters).

#include <stdio.h>

int main() {

register int i;

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

printf("%d ", i);

return 0;

Output:

12345
23
PPS Unit-I
The compiler may ignore register if no registers are available.

3. Static Storage Class (static)

(a) Static Local Variable

 Retains its value between function calls.

 Initialized only once.

 Scope → Local to the function.

 Lifetime → Entire program.

#include <stdio.h>

void counter() {

static int count = 0;

count++;

printf("Count = %d\n", count);

int main() {

counter();

counter();

counter();

return 0;

Output:

Count = 1

Count = 2

Count = 3

Unlike automatic variables, static variables keep their previous values.

(b) Static Global Variable

 Scope limited to the same file.

 Used to restrict variable access across files.

static int x = 10; // accessible only in this file

4. External Storage Class (extern)

 Declares a global variable defined in another file or later in the same file.
24
PPS Unit-I
 Used to share variables between multiple files.

File 1: main.c

#include <stdio.h>

extern int x; // Declaration (tells compiler variable exists)

int main() {

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

return 0;

File 2: data.c

int x = 50; // Definition (creates the variable)

Output (after compiling both):

x = 50

Difference Between static and extern

Feature static extern

Scope Within same file Across multiple files

Lifetime Entire program Entire program

Default Value 0 0

Usage Keeps variable private Makes variable public

Type conversion:
Typecasting in C is the process of converting a variable or value from one data type to
another. This can be done either implicitly (automatically by the compiler) or explicitly
(manually by the programmer).

1. Implicit Type Conversion (Type Coercion):

This occurs automatically when the compiler converts a data type to another compatible
data type without any explicit instruction from the programmer. This usually happens
during assignments or when performing operations involving different data types. For
example, assigning an int to a float will implicitly convert the int to float.

#include <stdio.h>
int main() {
int num_int = 10;
25
PPS Unit-I
float num_float;
num_float = num_int; // Implicit conversion from int to ffoat
printf("Implicit conversion: %f\n", num_float);
return 0;
}

2. Explicit Type Conversion (Type Casting):


This is performed by the programmer using the cast operator (type_name). It explicitly
instructs the compiler to convert a value to a specific data type. This is often necessary
when an implicit conversion would lead to data loss or incorrect results, such as in
integer division where a floating-point result is desired.

#include <stdio.h>
int main() {
int numerator = 15;
int denominator = 2;
float result;

// Without typecasting, integer division would result in 7


result = numerator / denominator;
printf("Result without typecasting: %f\n", result); // Output: 7.000000

// With explicit typecasting, one operand is converted to ffoat


result = (float)numerator / denominator;
printf("Result with typecasting: %f\n", result); // Output: 7.500000

return 0;
}

Key Points:

 Syntax for Explicit Typecasting: (target_data_type) expression

 Data Loss: Explicitly casting a higher-precision data type (like float or double) to
a lower-precision one (like int) can lead to data loss (e.g., truncation of decimal
places).

Input s Output in C
Simple input and output with scanf and printf and formatted I/O:
 printf() → Used to display (output) text or values on the screen.

 scanf() → Used to take (input) values from the user.

◆ Example 1: Input and Output of Integers

#include <stdio.h>
26
PPS Unit-I
int main() {

int num;

printf("Enter a number: "); // output

scanf("%d", Cnum); // input (read integer)

printf("You entered: %d\n", num); // output

return 0;

Here:

 %d → format specifier for int.

 Cnum → gives the address of variable num where input is stored.

Example 2: Multiple Inputs

#include <stdio.h>

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", Ca, Cb); // read two integers

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

return 0;

Example 3: Input/Output of Different Data Types

#include <stdio.h>

int main() {

int age;

float height;

char grade;

printf("Enter age, height, and grade: ");

scanf("%d %f %c", Cage, Cheight, Cgrade);

printf("Age: %d\n", age);

printf("Height: %.2f\n", height); // %.2f → 2 decimal places

printf("Grade: %c\n", grade);


27
PPS Unit-I
return 0;

Common format specifiers in C:

Data Type Format Specifier

int %d

float %f

double %lf

char %c

string (char array) %s

Format Specifiers in C

Data Type Format Specifier Example (Input/Output)

scanf("%d", Ca); → 10
int (decimal) %d
printf("%d", a); → 10

short int %hd scanf("%hd", Cs);

long int %ld scanf("%ld", Cl);

unsigned int %u scanf("%u", Cu);

unsigned long int %lu scanf("%lu", Cul);

scanf("%f", Cf); → 12.34


float %f
printf("%.2f", f); → 12.34

double %lf scanf("%lf", Cd);

long double %Lf scanf("%Lf", Cld);

scanf("%c", Cch); → A
char %c
printf("%c", ch); → A

scanf("%s", str); → Hello


string (char array) %s
printf("%s", str); → Hello

unsigned char %c (same as char) scanf("%c", Cuch);

pointer (address) %p printf("%p", ptr);


28
PPS Unit-I

◆ Notes:

 For scanf(), always use s before variable name (except for strings).

 scanf("%d", Ca); // correct

 scanf("%s", str); // no C needed for string

 For floating-point numbers:

o %.2f → prints up to 2 decimal places

o %.3f → prints up to 3 decimal places

Example:

#include <stdio.h>

int main() {

int age;

float marks;

char grade;

char name[20];

printf("Enter name, age, marks, grade: ");

scanf("%s %d %f %c", name, Cage, Cmarks, Cgrade);

printf("Name: %s\n", name);

printf("Age: %d\n", age);

printf("Marks: %.2f\n", marks);

printf("Grade: %c\n", grade);

return 0;

printf — flags, width, precision (examples)

Syntax: %[flags][width][.precision][length]specifier

Flags:

 - left-justify

 + always show sign


29
PPS Unit-I
 (space) prepend space for positive numbers

 0 zero-pad

 # alternate form (e.g., 0x for hex, force decimal point)

Examples:

printf("%8d", 123); // " 123" width 8, right-justified

printf("%-8d", 123); // "123 " left-justified

printf("%08d", 123); // "00000123" zero-padded

printf("%+d", 123); // "+123" always show sign

printf("%.2f", 3.14159);// "3.14" precision 2 for floats

printf("%10.2f", 3.14159);// " 3.14" width 10, precision 2

printf("%#.0f", 3.0); // "3." alternate form forces decimal point

Introduction to stdin, stdout and stderr:


C provides three standard I/O streams that are automatically opened when a program
starts running. They are defined in the <stdio.h> header file.

1. stdin (Standard Input)

 Used for input operations.

 By default, it is connected to the keyboard.

Example using scanf()

#include <stdio.h>

int main() {

int age;

printf("Enter your age: ");

scanf("%d", Cage); // reads from stdin (keyboard)

printf("You entered: %d\n", age);

return 0;

Explanation:

 When you type a value, it’s read from the standard input stream → stdin.

2. stdout (Standard Output)

 Used for normal output operations.


30
PPS Unit-I
 By default, it is connected to the screen (console).

 Functions like printf() and puts() write data to stdout.

Example:

#include <stdio.h>

int main() {

printf("Hello, World!\n"); // written to stdout (screen)

return 0;

Explanation:

 Whatever you print using printf() is sent to stdout.

3. stderr (Standard Error)

 Used for error messages or diagnostic output.

 By default, it is also connected to the screen, but it’s a separate stream from
stdout.

 This separation helps distinguish normal output from error output (useful in
debugging).

Example using fprintf()

#include <stdio.h>

int main() {

FILE *file = fopen("data.txt", "r");

if (file == NULL) {

fprintf(stderr, "Error: Could not open file!\n");

return 1;

fclose(file);

return 0;

⬛ Explanation:

 The error message is printed to stderr, not stdout.

 So even if normal output is redirected to a file, the error message still appears on
the screen.
31
PPS Unit-I
Conditional Branching:
or
Decision Making in C (if , if..else, Nested if, if-else-if )
In C, programs can choose which part of the code to execute based on some condition.
This ability is called decision making and the statements used for it are called
conditional statements. These statements evaluate one or more conditions and make
the decision whether to execute a block of code or not.

Types of Conditional Statements in C

1. if in C

The if statement is the simplest decision-making statement. It is used to decide whether


a certain statement or block of statements will be executed or not i.e., if a certain
condition is true then a block of statements is executed otherwise not.

A condition is any expression that evaluates to either a true or false (or values convertible
to true or flase).

Example

#include <stdio.h>

int main() {

int i = 10;

// If statement
32
PPS Unit-I
if (i < 18) {

printf("Eligible for vote");

Output

Eligible for vote

The expression inside () parenthesis is the condition and set of statements inside {}
braces is its body. If the condition is true, only then the body will be executed.

If there is only a single statement in the body, {} braces can be omitted.

2. if-else in C

The if statement alone tells us that if a condition is true, it will execute a block of
statements and if the condition is false, it won’t. But what if we want to do something else
when the condition is false? Here comes the C else statement. We can use
the else statement with the if statement to execute a block of code when the condition
is false. The if-else statement consists of two blocks, one for false expression and one for
true expression.

Example

#include <stdio.h>

int main() {

int i = 10;

if (i > 18) {

printf("Eligible for vote");

else {

printf("Not Eligible for vote");

return 0;

Output

Not Eligible for vote

The block of code following the else statement is executed as the condition present in
the if statement is false.
33
PPS Unit-I
3. Nested if-else in C

A nested if in C is an if statement that is the target of another if statement. Nested if


statements mean an if statement inside another if statement. Yes, C allow us to nested if
statements within if statements, i.e, we can place an if statement inside another if
statement.

Example

#include <stdio.h>

int main(){

int i = 10;

if (i == 10) {

if (i < 18)

printf("Still not eligible for vote");

else

printf("Eligible for vote\n");

else {

if (i == 20) {

if (i < 22)

printf("i is smaller than 22 too\n");

else

printf("i is greater than 25");

return 0;

Output

Still not eligible for vote

4. if-else-if Ladder in C

The if else if statements are used when the user has to decide among multiple options.
The C if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of
34
PPS Unit-I
the C else-if ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed. if-else-if ladder is similar to the switch statement.

Example

#include <stdio.h>

int main() {

int i = 20;

// If else ladder with three conditions

if (i == 10)

printf("Not Eligible");

else if (i == 15)

printf("wait for three years");

else if (i == 20)

printf("You can vote");

else

printf("Not a valid age");

return 0;

Output

You can vote

5. switch Statement in C

The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the switch
statement. The switch block consists of cases to be executed based on the value of the
switch variable.

Example

#include <stdio.h>

int main() {

// variable to be used in switch statement

int var = 18;

// declaring switch cases

switch (var) {
35
PPS Unit-I
case 15:

printf("You are a kid");

break;

case 18:

printf("Eligible for vote");

break;

default:

printf("Default Case is executed");

break;

return 0;

Output

Eligible for vote

Note: The switch expression should evaluate to either integer or character. It cannot
evaluate any other data type.

6. Conditional Operator in C

The conditional operator is used to add conditional code in our program. It is similar to
the if-else statement. It is also known as the ternary operator as it works on three
operands.

Example:

#include <stdio.h>

int main() {

int var, flag = 0;

// using conditional operator to assign the value to var according to the value of flag

var = flag == 0 ? 25 : -25;

printf("Value of var when flag is 0: %d\n", var);

return 0;

Output

Value of var when flag is 0: 25


36
PPS Unit-I
7. Jump Statements in C

These statements are used in C for the unconditional flow of control throughout the
functions in a program. They support four types of jump statements:

A) break

This loop control statement is used to terminate the loop. As soon as the break statement
is encountered within a loop, the loop iterations stop there, and control returns from the
loop immediately to the first statement after the loop.

Example

#include <stdio.h>

int main() {

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

int key = 3, size = 6, i;

for (i = 0; i < size; i++) {

if (arr[i] == key) {

printf("Element found at position: %d", (i + 1));

break;

return 0;

Output

Element found at position: 3

B) continue

This loop control statement is just like the break statement. The continue statement is
opposite to that of the break statement, instead of terminating the loop, it forces to
execute the next iteration of the loop. As the name suggests the continue statement
forces the loop to continue or execute the next iteration. When the continue statement is
executed in the loop, the code inside the loop following the continue statement will be
skipped and the next iteration of the loop will begin.

Example:

#include <stdio.h>

int main() {
37
PPS Unit-I
int i;

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

// If i is equals to 6, continue to next iteration without printing

if (i == 6)

continue;

else

printf("%d ", i);

return 0;

Output

1 2 3 4 5 7 8 9 10

C) goto

The goto statement in C also referred to as the unconditional jump statement can be
used to jump from one point to another within a function.

Examples:

#include <stdio.h>

int main() {

int n = 1;

label:

printf("%d ", n);

n++;

if (n <= 10)

goto label;

return 0;

Output

1 2 3 4 5 6 7 8 9 10

D) return

The return in C returns the flow of the execution to the function from where it is called.
This statement does not mandatorily need any conditional statements. As soon as the
38
PPS Unit-I
statement is executed, the flow of the program stops immediately and returns the control
from where it was called. The return statement may or may not return anything for a void
function, but for a non-void function, a return value must be returned.

Example:

#include

<stdio.h> int

sum(int a, int b) {

int s1 = a + b;

return s1;

int main()

int num1 = 10, num2 = 10;

int sumOf = sum(num1,

num2); printf("%d", sumOf);

return 0;

Output

20

You might also like