CPPM
UNIT 2
Input/Output Statements and Operators
By Om Pandey
CPPM
About this Unit
This unit introduces the basics of input and output operations in C programming,
using functions like printf() for displaying output and scanf() for taking user
input. It explains the role of header files such as <stdio.h> (for standard
input/output) and <conio.h> (for console-based input/output, mostly in Turbo
C). The concept of preprocessor directives is covered, which are special
instructions processed before actual compilation. Key directives like #include
(to include libraries or files) and #define (to define constants or macros) are
discussed. The unit emphasizes how these tools make code modular, reusable,
and manageable, helping the programmer avoid redundancy. Real-life analogies
like toolkits and vending machines make these abstract ideas easier to
understand.
2.1 Concepts of Header Files (STDIO,CONIO)
Header files in C are files that contain definitions of functions and macros that can be
shared between multiple source files. They typically have a ’.h’ extension and are
included in a program using the #include preprocessor directive.
Header Files
Header files are files that typically have a .h extension and contain declarations
of functions, macros, constants, and data types. They do not contain the actual
implementation of functions; instead, they provide a way to share function
prototypes and definitions across multiple source files.
Think of a header file as a recipe card. The recipe card lists the ingredients and the
steps to prepare a dish, but it does not contain the actual dish. Similarly, a header file
provides the necessary information (function prototypes and macros) that other source
files need to use the functions defined elsewhere.
By Om Pandey
CPPM
Purpose of Header Files
1. Code Reusability: Header files allow you to define functions and macros once
and use them in multiple source files without rewriting the code.
2. Modularity: By separating declarations from implementations, header files
promote modular programming. This makes it easier to manage large code files.
3. Organization: Header files help organize code by grouping related functions and
definitions together, making it easier to navigate and maintain.
4. Encapsulation: Header files can hide implementation details from the user,
exposing only the necessary interfaces.
Some of the common header files are as follows :-
1. <stdio.h>: This is the standard input-output header file in C. It contains
declarations for functions like printf, scanf, and file handling functions
also.
2. <conio.h>: This header file is used in some compilers (like Turbo C) for
console input and output functions, such as getch() and clrscr(). Note
that <conio.h> is not part of the C standard library and is not available in
all compilers.
And many more will be discussed in the future.
By Om Pandey
CPPM
How to use Header Files?
To use a header file in your program, you include it at the beginning of your
source file using the #include preprocessor directive. There are two ways to
include header files:
● Standard Library Header Files: Use angle brackets (<>) to include
standard library headers.
● User -defined Header Files: Use double quotes ("") to include your own
header files.
In this example, the #include <stdio.h> directive allows the program to use the
printf function, which is defined in the standard input-output library.
By Om Pandey
CPPM
2.1.1 Concepts of Pre-Compiler/Pre-Processor Directives.
Pre-compiler directives are special commands in C and C++ that are processed
by the preprocessor before the actual compilation of the code begins. They are
not part of the C/C++ language itself but serve as instructions to the compiler.
Understanding pre-compiler directives is crucial for effective programming in C
and C++, as they help manage code, control compilation, and facilitate modular
programming.
Pre-compiler directives are lines in the code that begin with the # symbol. They
are not executed as part of the program but are interpreted by the preprocessor,
which runs before the compiler. The preprocessor handles these directives to
modify the source code before it is compiled
Analogy: Think of pre-compiler directives as instructions given to a director
before a movie is filmed. The director sets the stage, decides on the scenes, and
prepares the actors, but these instructions are not part of the actual movie.
Similarly, pre-compiler directives prepare the code for compilation without being
part of the final executable.
By Om Pandey
CPPM
2.1.2 Use of #include and #define
1) #include: This directive is used to include the contents of a file (usually a
header file) into the program. It allows you to use functions and definitions
from other files.
2) #define: This directive is used to define macros, which are essentially
placeholders for code or values that can be reused throughout the
program. Macros can take parameters, making them similar to functions.
Example -
#include <stdio.h> // use of #include pre-processor and
header file
#include <conio.h>
#define PI 3.14159 //#define pre-processor
int main() {
float radius, area; //declaration of variables
clrscr();
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = PI * radius*radius; //use of #define
printf("Area of the circle: %.2f\n", area);
getch();
return 0;
}
By Om Pandey
CPPM
2.2 Input and Output Statements
For any process in programming it is must to have some inputs hence only
on the basis of inputs we will be able to get outputs. Hence, in
programming we must work with various Inputs and output statements
which will help us in making the flow of the program very easy. In C there
are no in-built I/O statements, in C we use scanf, printf and many more for
input and output operations which are basically the part of different I/O
libraries such as stdio.h and conio.h.
So, let us start the discussion first with the Input Statements
2.2.1 Input Statements/Functions
1) scanf()
scanf() is a function which is basically derived from pre-processor
directives which is mainly used to take input from the user during
runtime. It reads formatted data from the standard input device
(usually keyboard) and stores it in the specified variable(s). It is
defined in the <stdio.h> (Standard Input Output) header/library file.
Syntax -
scanf("format_specifier", &variable);
- Here format specifiers are like %d, %f, %c etc
- For taking input for a variable we have to write ‘&’ before the
variable name.
By Om Pandey
CPPM
2) getc()
getc() is also a standard input function which is only used for reading
a single character from an input stream such as a keyboard or a file.
This is also defined in <stdio.h> Header file/Library.
Syntax -
int getc(FILE *stream);
- Here stream refers to the input source like stdin for keyboard or a
file pointer for File.
- It returns the ASCII value of the read character, which means the
return type is I
For taking inpntut from keyboard -
char ch;
ch = getc(stdin); // Reads a single character from keyboard
By Om Pandey
CPPM
3) getch()
getch() is also a function which is the part of conio.h library which is
mainly used for reading a single character directly from the keyboard.
It does not echo the character on screen which means it doesn’t
display what you type using your keyboard, this is commonly used in
Turbo C and C++ and windows based compiler.
Syntax -
char ch;
printf("Press any key: ");
ch = getch();
- It doesn’t take any argument, and returns the character you typed.
- It reads the character immediately, without waiting for the Enter
key.
Where we can use getch()?
- Password input (when you don't want typed characters to be visible)
- Menu-based programs where you wait for a keypress
And many more..
Imagine you press a key on an ATM keypad—it takes your input instantly
and doesn't display it on screen for privacy.
That’s how getch() behaves!
By Om Pandey
CPPM
4) getchar()
getchar() is also a function which is the part of the <stdio.h> header
file. It is also used for reading a single character.
Syntax -
char name;
name = getchar();
- It takes no arguments.
- It returns the ASCII value of the character typed.
- Unlike getch(), it waits for the Enter key after the user types a
character.
- It echoes (shows) the character on the screen when typed
By Om Pandey
CPPM
5) gets()
gets() is a function used to read a full line of text (including spaces)
from the standard input (keyboard) until the user presses Enter.
● It stores the input string in a character array.
● It automatically adds a \0 (null character) at the end to mark the
string’s termination.
Syntax -
char str[100];
gets(str);
By Om Pandey
CPPM
Code for scanf() as we are going to use this only -
#include <stdio.h>
#include <conio.h>
int main() {
int age;
clrscr();
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered age: %d\n", age);
getchar();
return 0;
When you will run this code then the prompt will first show a print statement
- Enter Your age:
Then you should start typing the input in the specified data type only
(Note - The input statement will only take the input as per the type of format specifier
you have mentioned in the input statement and the specifiers are also according to the
data type of the variable that you have created, for ex - if it “int age” the your specifier
will be “%d” in input and if you have to print in output then also you have to use “%d”)
By Om Pandey
CPPM
2.2.2 Output Statements/Functions
1) printf()
The printf() function is used to print formatted output to the
console. It allows for a wide range of formatting options, including
specifying the number of decimal places for floating-point numbers,
padding, and alignment.
Example - printf("Hello, World!");
2) putc()
The putc() function is used to write a single character to the
specified output stream. It is often used for writing characters to files
or standard output.
Example - putc('A', stdout)
3) puts()
The puts() function is used to write a string to the standard output
followed by a newline character. It automatically appends a newline at
the end of the output.
Example - puts("Hello, World!");
By Om Pandey
CPPM
4) putchar()
The putchar() function is used to write a single character to the
standard output. It is similar to putc(), but it always writes to
stdout.
Example - putchar('A');
By Om Pandey
CPPM
2.2.3 Type specifiers (formatting strings)
1) %d
The %d format specifier is used to print integer data types onlu in
decimal (base 10) format. It is suitable for variables of type int.
Example-
int num = 42;
printf("The number is: %d\n", num);
2) %ld
The %ld format specifier is used to print long integers in decimal
format. It is suitable for variables of type long int.
Use %ld when you need to display a long integer, which can hold
larger values than a standard integer.
Example -
long int bigNum = 1234567890L;
printf("The long number is: %ld\n", bigNum);
By Om Pandey
CPPM
3) %f
The %f format specifier is used to print floating-point numbers in
decimal format. By default, it displays six digits after the decimal
point.
Example -
float pi = 3.14159f;
printf("The value of pi is: %f\n", pi);
4) %c
The %c format specifier is used to print a single character. It is
suitable for variables of type char.
Example -
char letter = 'A';
printf("The letter is: %c\n", letter);
5) %lf
The %lf format specifier is used to print double-precision
floating-point numbers. It is specifically for variables of type double.
Example -
By Om Pandey
CPPM
double e = 2.718281828459;
printf("The value of e is: %lf\n", e);
Code -
#include <stdio.h>
int main() {
int age = 25;
long int population = 7800000000L;
float height = 5.9f; // in feet
char initial = 'J';
char name[] = "John";
double pi = 3.141592653589793;
// Using combined format specifiers
printf("Name: %s\n", name);
printf("Initial: %c\n", initial);
printf("Age: %d years\n", age);
printf("Height: %.1f feet\n", height);
printf("Population: %ld\n", population);
printf("Value of Pi: %lf\n", pi);
return 0;
}
By Om Pandey
CPPM
2.3 Operators
Operators are symbols that tell the compiler to perform specific
mathematical, logical operations on variables and values. There are
different types of operators such as -
1) Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulus etc.
They are as follows :-
1.1) “+” - Addition
This operator adds two numbers.
Example -
By Om Pandey
CPPM
1.2) “-” - Subtraction
It subtracts the second number from the first.
Example -
1.3) “*” - Multiplication
It multiplies two values.
Example -
By Om Pandey
CPPM
1.4) “/” - Division
Divides the numerator by the denominator and gives the quotient.
Important: If both operands are integers, result will also be an integer (fraction is
discarded).
By Om Pandey
CPPM
1.5) “%” - Modulus
Gives the remainder of integer division. Only works with int type.
1.6) “++” - Increment
Increases the value of a variable by 1.
Pre-increment (++a): Increments before using the value.
Post-increment (a++): Uses value first, then increments.
By Om Pandey
CPPM
1.7) “--” - Decrement
Decreases the value by 1.
Pre-decrement (--a): Decrements first, then uses the value.
Post-decrement (a--): Uses value first, then decrements.
Important points -
- Arithmetic operations follow the BODMAS rule (Brackets, Orders,
Division/Multiplication, Addition/Subtraction).
- Use correct data types (int, float) for precise results.
- Modulus % cannot be used with float or double.
By Om Pandey
CPPM
By Om Pandey
CPPM
2) Logical Operators
Logical Operators are used to perform logical operations—mostly with conditional
statements like if, while, etc. They return either true (1) or false (0) based on
the logic.
2.1) Logical AND (&&)
Returns true (1) only when both conditions are true
Returns false (0) if any one is false
Syntax - (condition1 && condition2)
By Om Pandey
CPPM
2.2) Logical OR (||)
Returns true (1) if any one condition is true.
Returns false (0) only when both are false.
Syntax - (condition1 || condition2)
By Om Pandey
CPPM
2.3) Logical NOT (!)
Reverses the condition:
If true → false and If false → true
Syntax - !(condition)
Truth Table -
By Om Pandey
CPPM
By Om Pandey
CPPM
3) Relational Operators
Relational operators are used to compare two values or variables.
They return a boolean result:
● 1 (true) if the relation is correct
● 0 (false) if the relation is incorrect
3.1) Greater Than (>)
By Om Pandey
CPPM
3.2) Less Than (<)
3.3) Greater Than or Equal To (>=)
By Om Pandey
CPPM
3.4) Less Than or Equal To (<=)
3.5) Equal To (==)
*Be careful: a = b will assign b to a, not compare.
By Om Pandey
CPPM
3.6) Not Equal To (!=)
By Om Pandey
CPPM
4) Assignment operators
Assignment operators are used to assign values to variables.
They can also combine assignment with arithmetic operations (like +=, -=
etc.).
4.1) Simple Assignment (=)
Assigns a value to a variable.
4.2) Add and Assign (+=)
By Om Pandey
CPPM
4.3) Subtract and Assign (-=)
4.4) Multiply and Assign (*=)
By Om Pandey
CPPM
4.5) Divide and Assign (/=)
4.6) Modulus and Assign (%=)
By Om Pandey
CPPM
5) Bitwise operators
Bitwise operators perform operations on individual bits (0s and 1s) of
integer values.
These are different from logical operators (&&, ||, !) because:
- Logical works on boolean logic (true/false)
- Bitwise works on each bit
5.1) Bitwise AND (&)
This compares each bit, and it will give the result 1 if both the bits are 1.
5.2) Bitwise OR (|)
It will give output as 1, if any one bit is 1.
By Om Pandey
CPPM
5.3) Bitwise XOR (^)
Will give 1 as the output, if bits are different.
By Om Pandey
CPPM
6) Ternary Operator and use of sizeof() function
- The ternary operator is a shortcut for if-else statements. It takes
three operands, which is why it’s called ternary.
Syntax - condition ? expression_if_true : expression_if_false;
Which means -
If condition is true → run expression_if_true, Else → run
expression_if_false
Code :
Example 1 -
By Om Pandey
CPPM
Example 2 -
When to use ternary operator?
● When condition is simple
● To write short if-else in one line
By Om Pandey
CPPM
Use of sizeof() operator in C
The sizeof() operator tells the memory size (in bytes) of:
● any data type (int, float, char…)
● variables
● arrays
● Structures
Syntax -
sizeof(data_type) - To check the memory occupation of a type
sizeof(variable) - To check the memory occupation of a variable
Code -
Example 1 -
Output - 4 bytes, 4 bytes and 1 bytes. But this may vary due to system
configurations.
By Om Pandey
CPPM
Example 2 -
double d = 25.0;
→ This declares a variable d of type double and assigns it the value 25.0
sizeof(d)
→ This tells how many bytes the variable d occupies in memory
On most systems (like 64-bit machines), the size of a double is 8 bytes.
By Om Pandey
CPPM
2.4 Important Built-in functions
There are some built in functions which are mainly used for performing
certain tasks. These functions are present in the header files only which
you need to include when ever you want to use these functions.
2.4.1) Use of : ( strlen, strcmp, strcpy, strcat,strrev)
These are basically some important string functions. In C, strings are
handled using character arrays, and <string.h> provides many built-in
functions to perform common operations like comparing, copying, and
measuring strings.
To use these functions, include the header:
Without including this header file you won’t be able to use built in string
functions.
Some important string functions are as follows.
By Om Pandey
CPPM
1) strlen()
Returns the length of a string (number of characters excluding the
null \0 character).
Example -
By Om Pandey
CPPM
2) strcmp()
This helps in comparing the strings.
Example -
By Om Pandey
CPPM
3) strcpy()
Copies the content of one string into another.
Example -
By Om Pandey
CPPM
4) strcat()
This function joins one string to the end of another
5) strrev()
This helps in reversing the string.
By Om Pandey
CPPM
2.4.2) Use of : (abs(), floor(), round(), ceil(), sqrt(), exp(), log(), sin(),
cos(), tan(), pow() and trunc())
These set of function are those which basically performs mathematical
operations such as roundoff, sin, cos, log etc.
To use these function you must always include :-
#include <math.h>
1) abs() – Absolute Value (for int only)
By Om Pandey
CPPM
2) floor() – Round down to nearest integer
3) ceil() – Round up to nearest integer
By Om Pandey
CPPM
4) round() – Round to nearest integer
5) sqrt() – Square Root
By Om Pandey
CPPM
6) exp() – Exponential (e^x)
7) log() – Natural Logarithm (base e)
By Om Pandey
CPPM
8) sin(), cos(), tan() – Trigonometric functions
*Angle must be in radians, not degrees.
9) pow() – Power function (x^y)
By Om Pandey
CPPM
10) trunc() – Truncate decimal part
By Om Pandey
CPPM
THANK YOU
By Om Pandey