0% found this document useful (0 votes)
20 views44 pages

Module - 1 An Overview of C, Expressions, Console I - O

The document provides an overview of the C programming language, including its history, characteristics, and structure. It explains algorithms and flowcharts as program design tools, details the evolution of C through various standards, and compares compilers and interpreters. Additionally, it discusses C's role as a middle-level and structured language, emphasizing its efficiency, power, and relevance in modern programming.
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)
20 views44 pages

Module - 1 An Overview of C, Expressions, Console I - O

The document provides an overview of the C programming language, including its history, characteristics, and structure. It explains algorithms and flowcharts as program design tools, details the evolution of C through various standards, and compares compilers and interpreters. Additionally, it discusses C's role as a middle-level and structured language, emphasizing its efficiency, power, and relevance in modern programming.
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

Module - 1 An Overview of C, Expressions, Console I/O

Algorithm and Flowchart

Algorithm (Program design tools)


An Algorithm is a finite set of unambiguous instructions, which when executed, performs
a task correctly.
There are three characteristics features here:
●​ The number of steps required to perform the task should be finite.
●​ Each of the instructions in the algorithm should be unambiguous in nature; meaning
on the execution of each instruction, the outcome should be definite and predictable.
●​ Finally, the algorithm should solve the problem correctly (objective should be
fulfilled).

There are no defined rules to write an algorithm. However, most authors prefer to use
English-like statements to represent the instructions.

Flowchart
●​ The flowchart is also a tool to represent logic.
●​ A flowchart helps us graphically visualize the flow of control within the sequence of
statements.
●​ The flowchart uses some standard notation to graphically represent logic.

Name Description Symbol

Terminal Used to mark the beginning and end of the


flowchart.

Input/Output Used to represent input or output operations

Process Used to represent processing operations(logic


construct)

Decision Used to represent conditional statement constructs

Connector Used to transfer the flow of control from one point to


another within a page.

Arrowed lines These are used to show the sequence of flow from
one box to another.

Geetha N, Dept of CSE BMSCE


1.​ Develop an algorithm and a flowchart to find the average of three numbers taken as
input from the user.

Algorithm

Step 1: START
Step 2: INPUT x, y and z
Step 3: Calculate sum = x + y + z
​ ​ avg = sum / 3
Step 4: Display AVG
Step 5: STOP

Flowchart

2.​ Develop an algorithm and a flowchart to find the smallest of two numbers taken as input
from the user.

Algorithm

Step 0: START
Step 1: INPUT first number into variable A
Step 2: INPUT second number into variable B
Step 3: IF A > В THEN MAX = A ELSE MAX = В END IF
Step 4: DISPLAY MAX
Step 5: END

Geetha N, Dept of CSE BMSCE


3.​ Develop an algorithm and a flowchart to find the sum of the first N natural numbers
where N would be user input.

Algorithm

Step 1 : START
Step 2 : INPUT N
Step 3 : i = 1 and sum = 0
Step 4 : Repeat steps (a) - (b) until i <= N
(a)​ sum = sum + i (b) i = i + 1
Step 5 : Display sum
Step 6 : Stop

Geetha N, Dept of CSE BMSCE


A Brief History of C

C is a general-purpose procedural programming language initially developed by Dennis Ritchie in 1972


at Bell Laboratories of AT&T Labs. It was mainly created as a system programming language to write the
UNIX operating system.
C is a general-purpose procedural programming language developed by Dennis Ritchie in 1972 at Bell
Labs to build the UNIX operating system. It provides low-level memory access, high performance, and
portability, making it ideal for system programming. Over the years, C has evolved through standards like
ANSI C, C99, C11, and C23, adding modern features while retaining its simplicity.

Dennis Ritchie and Brian Kernighan published The C Programming Language, now referred to as the
"K&R" book. It established the de facto standard for the C language. In that book, Ritchie and Kernighan
defined C's syntax and semantics, also called "K&R C".
●​ ANSI C (C89/C90): In 1983 the American National Standards Institute (ANSI) committee
completed a final draft standard known as ANSI C. After the standard development the ANSI C was
approved as a standard in 1989 (C89), then in 1990 the ANSI C standard was approved by International
Organization for Standardization (ISO) as (C90). In addition to introducing function prototypes, and
standard libraries, the ANSI C standard introduced formal libraries and stricter requirements for type
checking.
●​ C99 (1999): C99 introduced a variety of constructs, including: inline functions, variable-length
arrays, complex numbers, and other improvements to floating-point operations. C99 also introduced the

Geetha N, Dept of CSE BMSCE


long long data type and the nature of single-line comments (//).
●​ C11 (2011): C11 introduced many new features and addressed safety and concurrency. The most
notable is Generic type-generic programming, threading support (threads.h), and Unicode.
●​ C17/C18 (2017): The C17/C18 standard is a minor revision of C11. The standard also fixed bugs
in C11, and dependencies might change or clarify ambiguities left in C11, with no notable additions.
●​ C23 (2023): C23 is the latest standard, which added features such as nullptr, binary literals, and
more advanced support for modern hardware architecture.

C Is a Middle-Level Language

Yes, C is considered a middle-level programming language because it blends features of both low-level
and high-level languages, bridging the gap between machine-level instructions and human-readable code.

Why C is a middle-level language:


●​ Low-level features: C provides direct memory access and hardware interaction through features
like pointer arithmetic.

Direct memory access:​


C allows the use of pointers, which can directly access and manipulate memory addresses—something
usually possible only in assembly language.
Bitwise operations:​
C supports bitwise operators (&, |, ^, <<, >>) that help in hardware-level programming (e.g., controlling
devices, drivers, etc.).​
System-level programming:​
C can be used to write operating systems, compilers, and embedded software, which require low-level
hardware interaction.
●​ High-level features: It offers high-level constructs such as functions, loops, and conditional
statements, making programs easier to write and understand compared to pure assembly language.
●​ Flexibility: This combination allows programmers to write efficient and powerful programs,
similar to assembly, but with the added benefits of high-level language structures and portability.
●​ Versatility: C is used for both system-level programming (e.g., writing operating systems) and
application programming (e.g., developing user applications).
●​ Portability: C programs can be ported to different platforms because of their high-level language
features, making them more machine-independent than pure low-level languages.

C Is a Structured Language

C is a structured programming language because it allows programmers to break down complex


problems into smaller, manageable units called functions or procedures. This modular approach,
supported by control flow structures like if-else statements and loops (for, while), enhances code
readability, maintainability, and debugging by promoting logical organization and preventing unintended

Geetha N, Dept of CSE BMSCE


side effects between different parts of the program.

How C enables structured programming:


●​ Functions: C uses functions as the fundamental building blocks to perform specific tasks. A
large problem is divided into smaller, independent functions, making the overall program easier to
understand and develop.
●​ Modular Design: By segmenting code into distinct functions, C promotes modularity, where
each module handles a specific responsibility and can be developed and tested independently.
●​ Control Structures: C provides structured control statements, such as if-else for
decision-making and for, while, and do-while loops for repetition, allowing for logical and sequential
execution of tasks.
●​ Scope and Local Variables: Functions in C utilize local variables, which are confined to the
scope of the function they are defined in. This prevents unintended interference with other parts of the
program, making the code more robust.
●​ Code Reusability: Structured programming in C facilitates code reuse, as functions written once
can be called multiple times to perform their specific tasks, reducing redundancy and development time.
●​ Improved Readability and Maintenance: The structured approach makes programs easier to
read, understand, and maintain over time, as the logical organization of code into functions and control
structures clarifies the program's flow.

C Is a Programmer's Language

Surprisingly, not all computer programming languages are for programmers. Consider the classic
examples of nonprogrammer languages, COBOL and BASIC. COBOL was designed not to better
the programmer's lot, not to improve the reliability of the code produced, and not even to improve
the speed with which code can be written. Rather, COBOL was designed, in part, to enable
nonprogrammers to read and to understand the program. BASIC was created essentially to allow
nonprogrammers to program a computer to solve relatively simple problems. In contrast, C was
created, influenced, and field-tested by working programmers.

C for Programmers
●​ C was designed by and for professional programmers
●​ It provides what programmers want:​

○​ Few restrictions​

○​ Block structure​

○​ Stand-alone functions​

○​ Compact set of keywords


●​ Combines efficiency of assembly with structure of Pascal or Modula-2.

Power and Efficiency

Geetha N, Dept of CSE BMSCE


●​ C can often replace assembly language for system-level tasks.
●​ Assembly is fast and flexible but hard to debug and unstructured.
●​ Assembly programs are not portable between different CPUs.
●​ C overcomes these issues while maintaining efficiency and flexibility.

Early Use and Popularity


●​ Initially used for systems programming (e.g., operating systems, compilers, editors).
●​ Gained popularity for all types of programming due to its portability and speed.
●​ Programmers liked using C because it was powerful and efficient.

C’s Longevity and Relevance


●​ With the arrival of C++, some expected C to fade, but it did not.
●​ Reasons:
1.​ Many applications (like embedded systems) don’t need object-oriented features.
2.​ A large amount of existing code is still in C and continues to be maintained.
3.​ The C99 standard shows that C is still evolving and innovating.

Legacy of C
●​ C is the foundation of C++ and many modern languages.
●​ Still recognized as one of the greatest and most influential programming languages.

Compilers Vs. Interpreters

Parameter Compiler Interpreter

Program Compilers scan the entire program in one The program is interpreted/translated one
scanning go. line at a time.

Error detection As and when scanning is performed, all One line of code is scanned, and errors
the errors are shown in the end together, encountered are shown.
not line by line.

Object code Compilers convert the source code to Interpreters do not convert the source
object code. code into object code.

Execution The execution time of the compiler is less, It is not preferred due to its slow speed.
time hence it is preferred. Usually, interpreters are slow, and hence
takes more time to execute the object
code.

Need of source Compiler doesn't require the source code It requires the source code for execution
code for execution later. later.

Geetha N, Dept of CSE BMSCE


Programming Programming languages that use Programming languages that uses
languages compilers include C, C++, C#, etc.. interpreters include Python, Ruby, Perl,
MATLAB, etc.

Size Compilers are larger in size. Interpreters are smaller in size.

Efficiency Compilers are more efficient. Interpreters are less efficient.

The Form of a C Program

1.​ Document / Comment section

Documentation having details like author, date, program definition to know about the code and it is
optional.
/* Author: Authors details……..
Date: ………….. —----------> Multi-line comment
Program Definition: ………………….. */
// Author : …………………. —---------------> Single-line comment

2.​ Link section (header files)


●​ A header file is a file with extension .h which contains C function declarations to be shared
between source files.
●​ All the lines that start with # (hash) are processed by a preprocessor which is a program
invoked by the compiler.
●​ Examples: #include<stdio.h> → defines core input and output functions
#include<stdlib.h> → defines numeric conversion functions, memory allocations
#include<string.h> → defines string handling functions
#include<math.h> → defines common mathematical functions.

3.​ Definition section


●​ Defines all symbolic constants, called macro definitions
●​ #define PI 3.14
●​ #define MAX 100
●​ When PI with value 3.14 is used 20 times in a program, we can simply assign PI in all that
places.
●​ In the 2nd case, if the max value is changed to 100, then changing the value in only one place
is enough rather than modifying it in all 10 places.
4.​ Global declaration section
●​ Variables are declared globally and can be used everywhere in the program.
●​ int max = 100;

Geetha N, Dept of CSE BMSCE


void main( ){
int max1 = 10;
}

5.​ Main section


●​ The next part of a C program is to declare 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 value returned by the main indicates the status of the program termination.
6.​ Sub program section
●​ Will have a user defined function.

The Library and Linking

●​ A C program is composed of preprocessor commands, a global declaration section, and one or


more functions.
●​ The preprocessor directives contain special instructions that include how to prepare the
program for compilation.
●​ The most commonly used preprocessor command is include which tells the compiler that to
execute the program, some information is needed from the specified header file.
●​ A C program contains one or more functions, where a function is defined as a group of C
statements that are executed together.
●​ The statements in a C program function are written in a logical sequence to perform a specific
task.

●​ The main( ) function is the most important function and is a part of every C program. The
execution of a C program begins at this function.
●​ All functions (including main( ) ) are divided into 2 parts – the declaration section and the
statement section.

Geetha N, Dept of CSE BMSCE


●​ The declaration section is used to describe the data that will be used in the function, the data that
is declared within the function are known as the local declaration as that data will be visible only
within that function.
●​ The statement declaration in function contains the code that manipulates the data to perform a
specific task.
●​ We can conclude that a C program can have any number of functions depending on the tasks that
have to be performed and each function can have any number of statements arranged according to
specific meaningful sequence.

Compiling a C Program

Separate Compilation

C is a compiled language. So once a C program is written, you must run it through a C compiler that can
create an executable file to be run by the computer.

While the C program is human-readable, the executable, on the other hand, is a machine-readable file
available in an executable form. The mechanical part of running a program begins with one or more
program source files, and ends with an executable file, which can be run on a compiler. The compiler
translates the source code into an object code. The object code contains the machine instructions for the
CPU, and calls to the operating system API. However, even the object is processed with another special
program called a linker. The output of the linker is an executable or runnable file. In C language programs,
there are two kinds of source files. In addition to the main( .c ) source file, which contains executable
statements there are also header (.h) source files. Since all input and output in a C program is done through
library functions, every C program therefore uses standard header files. These header files should be
written as part of the source code for modular C programs.

In modular programming, the source code is divided into two or more source files. All these source files
are compiled separately thereby producing multiple object files. These object files are combined by the
linker to produce an executable file.

C's Memory Map

The memory layout of a program refers to how the program’s data is stored in the computer memory
during its execution. Understanding this layout helps developers manage memory more efficiently and
avoid issues such as segmentation faults and memory leaks.
A C program's memory is organized into specific regions (segments) as shown in the below image, each
serving distinct purposes for program execution.

Geetha N, Dept of CSE BMSCE


Different Segments in C Program's Memory

1. Text Segment
The text segment (also known as code segment) is where the executable code of the program is stored. It
contains the compiled machine code of the program's functions and instructions. This segment is usually
read-only and stored in the lower parts of the memory to prevent accidental modification of the code while
the program is running.
The size of the text segment is determined by the number of instructions and the complexity of the
program.
2. Data Segment
The data segment stores global and static variables that are created by the programmer. It is present just
above the code segment of the program. It can be further divided into two parts:
A. Initialized Data Segment - As the name suggests, it is the part of the data segment that contains
global and static variables that have been initialized by the programmer. For example, The variables a and b
will be stored in the Initialized Data Segment.
// Global variable
int a = 10;
// Static variable
static int b = 20;
B. Uninitialized Data Segment (BSS) – Uninitialized data segment often called the "bss" segment,
named after an ancient assembler operator, that stood for "Block Started by Symbol" contains global and
static variables that are not initialized by the programmer. These variables are automatically initialized to
zero at runtime by the operating system. For example, the below shown variables will be stored in this
segment:
int a; // Global variable
static int b; // Static variable

3. Heap Segment
Heap segment is where dynamic memory allocation usually takes place. The heap area begins at the end of
the BSS segment and grows towards the larger addresses from there. It is managed by functions such as

Geetha N, Dept of CSE BMSCE


malloc(), realloc(), and free() which in turn may use the brk and sbrk system calls to adjust its size.
The heap segment is shared by all shared libraries and dynamically loaded modules in a process. For
example, the variable pointed by ptr will be stored in the heap segment:

4. Stack Segment
The stack is a region of memory used for local variables and function call management. Each time a
function is called, a stack frame is created to store local variables, function parameters, and return
addresses. This stack frame is stored in this segment.
The stack segment is generally located in the higher addresses of the memory and grows opposite to heap.
They adjoin each other so when stack and heap pointer meet, free memory of the program is said to be
exhausted.
The Basic Data Types

A variable in C must be a specified data type, and you must use a format specifier inside the printf()
function to display it: The data type specifies the size and type of information the variable will store.

Data Size Description Example Format


Type Specifier

int 2 or 4 Stores whole numbers, without 1 %d


bytes decimals

float 4 Stores fractional numbers, containing 1.99 %f


bytes one or more decimals. Sufficient for
storing 6-7 decimal digits

double 8 Stores fractional numbers, containing 1.99 %lf


bytes one or more decimals. Sufficient for
storing 15 decimal digits

char 1 byte Stores a single character/letter/number, 'A' %c


or ASCII values

void 0 The void data type in C signifies the - -


absence of a specific type or value

%s Used for strings (sequence of text)

Geetha N, Dept of CSE BMSCE


int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

Output:

5​
5.990000​
D

Modifying the Basic Types

Modifying the Basic Types Except type void, the basic data types may have various modifiers preceding
them. A type modifier alters the meaning of the base type to more precisely fit a specific need. The list of
modifiers: signed, unsigned, long and short. The modifiers are keywords which are used to change size
and/or range of the primary datatypes. We can divide them into: Size modifiers and sign
modifiers

Size modifiers
They are used to modify the size of the datatype. We have following size modifiers
i) short : it can be used with int datatype, size of short int is 1 byte.
ii) long : it can be used with int and double datatype. The size of long int is 4 bytes and size of long double
is 16 bytes.

Sign modifiers
They are used to specify whether a data type allows us to store both negative and positive values or only
positive values.
i) signed : by default all the datatypes are signed
ii) unsigned : it can be used with int and char types.

Declaration Sign Type Example Range (16-bit)

int signed (default) -32,768 to +32,767

signed int​ signed -32,768 to +32,767

unsigned int unsigned 0 to 65,535

Geetha N, Dept of CSE BMSCE


Identifiers

Identifiers, as the name suggests, helps us to identify data and other objects in the program. Identifiers are
basically the names given to program elements such as variables, arrays and functions. Identifiers may
consist of a sequence of letters, numbers, numerals or underscores.

Rules for forming Identifier names:

Geetha N, Dept of CSE BMSCE


●​ Identifiers cannot include any special characters or punctuation marks ( like #, $, ^, ?, ., ,etc ) except
underscore ‘_’.
●​ There cannot be two successive underscores.
●​ Keywords cannot be used as identifiers. (keywords : set of reserved words that have a fixed meaning,
all keywords must be in lowercase letter)
●​ They are case sensitive (FIRST, first, First are all different)
●​ Identifiers must begin with a letter or an underscore. —-- However , use of underscore as the first
character must be avoided because several compiler-defined identifiers in the standard C library have
underscore as the first letter. Hence, duplicate names may cause definition conflicts.
●​ Identifiers can be of any reasonable length. They can actually be more than 31, but the compiler looks
at only the first 31 characters of the name.

Valid Identifiers: roll_num, marks, DA, RollNo, Emp_no, Dept_code_num

Invalid Identifiers: 23_student, %marks, @name, [Link], -DA, for , int

Variables

A variable is defined as a meaningful name given to a data storage location in computer memory. When
using a variable, we actually refer to the address of the memory where the data is stored. All variables
must be declared before they can be used. The general form of declaring a variable is:

datatype variable_list;

Here, datatype must be a valid datatype plus any modifier, and variable_list may consist of one or more
identifier names separated by commas. Here are some declarations:

int emp_num, marks;


char grade;
float salary, temp_celcius;
double balance_amt;
unsigned short int acc_no;

While declaring variables, we can also initialize them with some value. For example:

int emp_num = 7l;


char grade = ‘A’;
float salary = 900800.35;
Where variables are declared – Variables can be declared in three places: inside functions, in the
definition of function parameters and outside of all functions. These positions correspond to local variables,
formal parameters, and global variables, respectively.

Geetha N, Dept of CSE BMSCE


Local Variables

In C language, a variable declared within a function or a block of code is called a local variable. Local
variables are frequently used to temporarily store data in a defined scope where they can be accessed and
manipulated. They are stored in the memory stack, Once the function or block of code in which the local
variable is declared finishes executing. The variable is automatically removed from the memory.

Example of Local Variable

void main()
{
int a=10; // local variable declaration
}

Before a local variable can be used, it is necessary first to initialize the variable with a value.

1. Function Scoped Local Variables

The local variable is only accessible inside the function or block of code in which it is declared. A
variable's scope specifies where it can be used and accessible within a program.
// C Program to demonstrate Function Scoped Local Variables
#include <stdio.h>
// Function declared
void main()
{
int localVar = 10; // localVar is a local variable of main function
printf("The value of localVar is %d\n", localVar);
}

Output
The value of localVar is 10
Explanation: In the above code, When the main function is called, it prints the value of localVar as 10. If
you try to access it outside of its scope will result in a compilation error: 'localVar' undeclared”. This is
referred to as being out of scope.

2. Block Scoped Local Variables – Variables have a specified region or context in which they are valid
and can be manipulated. After a variable goes beyond its scope, it can no longer be accessed or modified.

// C Program to demonstrate Block Scoped Local variables


#include <stdio.h>

// Driver Function

Geetha N, Dept of CSE BMSCE


int main()
{
// declaration of x variable outside the block
int x = 15;

// Block is defined here
{
// Block scoped variable "x"
int x = 25;
printf("x was declared in the block: %d \n", x);
}

// prints 15 that was declared outside
printf("x outside the block: %d", x);
return 0;
}

Output
x was declared in the block: 25
x outside the block: 15
Explanation: Outside of the block, the program defines the variable "x" with a value of 15. Another
variable, 'x,' is defined inside the block with a value of 25. The variable "x" inside the block is printed
with a value of 25. We are unable to access the block-defined variable "x" outside of the block.

Formal parameters

Information can be passed to functions as a parameter. Parameters act as variables inside the
function. Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma:

returnType functionName(parameter1, parameter2, parameter3) {

// code to be executed

If a function is to use arguments, it must declare variables that will accept the values of the arguments.
These variables are called the formal parameters of the function. They behave like any other local
variables inside the function. As shown in the following program fragment, their declarations occur
after the function name and inside parentheses.
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

Geetha N, Dept of CSE BMSCE


int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Output:
Hello Liam. You are 3 years old.
Hello Jenny. You are 14 years old.
Hello Anja. You are 30 years old.

Here, char name[] and int age are the formal parameters of the function myFunction.

They represent:
●​ name → a character array (string) that will store a person’s name​

●​ age → an integer that will store that person’s age


When the function is called, each function call passes actual values (called actual parameters or
arguments) to the function:

Formal parameters: Declared in the function definition (char name[], int age)

Actual parameters: Passed during function call ("Liam", 3)

The formal parameters receive the values of the actual parameters when the function is executed.

Global variables

The Declaration of a global variable is very similar to that of a local variable. The only difference is
that the global variable is declared outside any function. We can take an example by assuming that we
have a chair at our house and one in our school/college then we can say that the chair at our home can
only be accessed by the people living inside the home but the chair in our college can be used by any
student or faculty.
Example:
#include <stdio.h>
int x = 5; // global variable
int main() {
int y = 10; // local variable
return 0;
}

Global variables do not stay limited to a specific function, which means that one can use any

Geetha N, Dept of CSE BMSCE


given function to access and modify the global variables. The initialization of these variables
occurs automatically to 0 during the time of declaration. Also, we generally write the global
variables before the main() function.
Example:
// C program to update global variables
#include <stdio.h>

int a, b; // global variables

void add()
{ // we are adding values of global a and b i.e. 10+15
printf("%d", a + b);
}

int main()
{
// we are now updating the values of global variables as you can see we don't need to redeclare a
//and b again
a = 10;
b = 15;
add();
return 0;
}

Output
25

The Four C Scopes

The terms local and global are used to describe in a general way the difference between
identifiers that are declared within a block and those declared outside all blocks. However, these
two broad categories are more finely subdivided by C. Standard C defines four scopes that
determine the visibility of an identifier. They are summarized here:
Scope Meaning

File scope Starts at the beginning of the file (also called a


translation unit) and ends with the end of the
file. It refers only to those identifiers that are
declared outside of all functions. File scope
identifiers are visible throughout the entire
file. Variables that have file scope are global.

Block scope Begins with the opening { of a block and ends


with its associated closing }. However, block

Geetha N, Dept of CSE BMSCE


scope also extends to function parameters in a
function definition. That is, function
parameters are included in a function's block
scope. Variables with block scope are local to
their block.

Function prototype scope Identifiers declared in a function prototype;


visible within the prototype.

Function scope Begins with the opening { of a function and


ends with its closing }. Function scope applies
only to labels. A label is used as the target of a
goto statement, and that label must be within
the same function as the goto.

Type Qualifiers in C
Type qualifiers tell the compiler how a variable’s value can be accessed or modified. C89
defines two of these qualifiers: const and volatile. The type qualifiers must precede the type
names that they qualify for.

1. const — Constant Variables


What it does:
●​ A const variable cannot be changed after it’s initialized.
●​ The compiler ensures your program does not modify it.
●​ You can still read or use it in calculations.​

Example 1: Basic const variable


#include <stdio.h>
int main() {
const int a = 10; // 'a' is constant
printf("a = %d\n", a);

// a = 20; //
return 0;
❌ This will cause a compile-time error
}

Explanation:
●​ a is read-only.
●​ Any attempt to change a will result in an error.​

2. volatile — Variable That Can Change Unexpectedly


What it does:
●​ A volatile variable tells the compiler:​

Geetha N, Dept of CSE BMSCE


“Don’t optimize this variable; its value can change at any time.”
●​ Used when a variable is modified outside the program, e.g., by hardware, an interrupt,
or another thread.​

Example: Simulating a hardware counter


#include <stdio.h>

volatile int counter = 0;

int main() {
while(counter == 0) {
// waiting for counter to change (e.g., by hardware)
}
printf("Counter changed!\n");
return 0;
}

Explanation:
●​ Normally, the compiler might optimize while(counter==0) assuming the counter never
changes.
●​ volatile prevents this, so the program keeps checking the actual value.

3. const volatile — Read-Only but Externally Changed


What it does:
●​ const → Program cannot change it
●​ volatile → Value can change outside the program​

Example: Hardware input port


#include <stdio.h>
const volatile int *port = (const volatile int *)0x30; // memory-mapped hardware

int main() {
int value = *port; // read value from hardware port
printf("Port value: %d\n", value);

// *port = 10; //
return 0;
❌ cannot write to port, read-only
}

Explanation:
●​ The program cannot modify the port (const).
●​ The hardware can change the value at any time (volatile).

Qualifier Can Program Can Value Change Outside Example Use Case
Change? Program?

const ❌ No ✅ Yes (by hardware) Read-only


function args
constants,

Geetha N, Dept of CSE BMSCE


volatile ✅ Yes ✅ Yes Hardware
interrupt flags
registers,

const ❌ No ✅ Yes Read-only


inputs
hardware
volatile

Storage Class Specifiers

C supports four storage class specifiers:


●​ extern
●​ static
●​ register
●​ auto

1.​ extern
In C, the extern keyword is used to declare a variable or a function whose definition is present in
some other file. Basically, it extends the visibility of the variables and functions in C to multiple
source files. Generally, the variables and functions defined inside a C source file are only used
inside that file. But in large projects where code is split across multiple files (or translation unit),
users may need the data, or a part of code defined in another translation unit into the current one.
This can be done with the help of extern keywords.
The usage syntax of extern is a multistep process. In the file, where we want to use the
variable/function, we have to provide extern declaration:
extern var_type var_name;​
extern ret_type func_name (arg_types .... );

The above declarations tell the compiler that the var_name variable and func_name function are
defined in some other translation unit. The next step is to compile both translation units together so
that the compiler can find the definition of it.
The variables/functions being declared must have external linkage i.e. they must be defined
globally. Local and static variables/functions have internal linkage and cannot be linked by the
compiler if they are declared as extern.
The following examples demonstrate the use of extern keyword in C:

Access Global Variables Across Multiple Files

First create a file that contains the definition of a variable. It must be global variable,
src.c
// Definition of a variable
int ext_var = 22;
Create an extern declaration of this variable in the file where we want to use it.
main.c

Geetha N, Dept of CSE BMSCE


#include <stdio.h>

// Extern declaration that will prompt compiler to search for the variable ext_var in other files
extern int ext_var;

void printExt() {
printf("%d", ext_var);
}
int main() {
printExt();
return 0;
}
Then we compile them together.
Output 22

Access Functions Across Multiple Files

First define the function inside the src.c file.


src.c
#include <stdio.h>

void func() {
printf("Hello");
}
Functions are extern by default, so we have a choice to use extern keyword here:
main.c
void func();

int main() {
func();
return 0;
}
Compile both of the files together and the output will be as shown.
Output
Hello
Applications of extern in C
Following are the primary applications of extern in C:
●​ Sharing global variables across multiple files
●​ extern plays a key role in linking with external libraries by declaring the functions and
variables they provide in the header files.
●​ extern promotes modularity by allowing different parts of a program to interact with
each other.
●​ By facilitating the sharing of variables and functions across files, extern enables code
reuse

Geetha N, Dept of CSE BMSCE


2. Static Variables
In C programming, a static variable is declared using a static keyword and has the property of retaining
their value between multiple function calls. It is initialized only once and is not destroyed when the
function returns a value. It extends the lifetime of the variable till the end of the program.
Syntax
The static variable can be simply declared by prefixing the static keyword before the normal variable
declaration.
static dataType variableName;
The static keyword in C can be applied to global or local variables, but it behaves differently in each
case.

1. Static Local Variables

What it does:

●​ Normally, a local variable is created when a function is called and destroyed when the function
ends.
●​ If you declare a local variable as static, it persists between function calls.
●​ Its value is retained instead of resetting each time the function is called.

Why it’s useful:

●​ Allows a function to remember past values without using a global variable.


●​ Reduces risk of conflicts with other global variables.

Example 2: Static local variable


#include <stdio.h>
int series(void) {
static int series_num = 100; // initialized only once
series_num = series_num + 23;
return series_num;
}

int main() {
printf("%d\n", series()); // 123
printf("%d\n", series()); // 146
printf("%d\n", series()); // 169
return 0;
}
Explanation:
●​ series_num keeps its value between function calls.
●​ First call → 123, second call → 146, third call → 169.
●​ If it were a normal local variable, it would reset to 100 each time → every call would return
123.

Static Global Variables


What it does:
●​ Normally, a global variable is visible to all files in a program.

Geetha N, Dept of CSE BMSCE


●​ If you declare a global variable as static, it becomes visible only in the file where it is
declared.
●​ This is called internal linkage.
●​ Other files cannot access or modify it, which prevents accidental changes.​

Why it’s useful:


●​ Keeps the variable safe from unwanted changes by other parts of the program.
●​ Helps manage large programs by hiding implementation details.

Example 1: Static global variable


#include <stdio.h>
static int series_num; // visible only in this file

void series_start(int seed) {


series_num = seed; // initialize series
}
int series(void) {
series_num = series_num + 23; // generate next number
return series_num;
}
int main() {
series_start(10); // start series at 10
printf("%d\n", series()); // prints 33
printf("%d\n", series()); // prints 56
return 0;
}
Explanation:
●​ series_num is global but hidden from other files.
●​ Functions series() and series_start() can access it.
●​ Other files cannot see or modify series_num.

3. Registers
Registers are faster than memory to access, so the variables which are most frequently used in a C
program can be put in registers using the register keyword. The keyword register hints to the compiler
that a given variable can be put in a register. It's the compiler's choice to put it in a register or not.
Generally, compilers themselves do optimizations and put the variables in a register.
1. If you use & operator with a register variable then the compiler may give an error or warning
(depending upon the compiler you are using), because when we say a variable is a register, it may be
stored in a register instead of memory and accessing the address of a register is invalid.
2. register keyword can be used with pointer variables. Obviously, a register can have the address of a
memory location. There would not be any problem with the below program.
// C program that demonstrates register keyword can be used with pointer variables

#include <stdio.h>
int main()

Geetha N, Dept of CSE BMSCE


{
// Declaring an integer variable 'i' and initializing it
// with 10
int i = 10;
// Declaring a register pointer variable 'a' and
// assigning the address of 'i' to it
register int* a = &i;
printf("%d", *a);
getchar();
return 0;
}

Output 10

3. Register is a storage class, and C doesn't allow multiple storage class specifiers for a variable. So, the
register can not be used with static.
4. Register can only be used within a block (local), it can not be used in the global scope (outside main).
5. There is no limit on the number of register variables in a C program, but the point is compiler may put
some variables in the register and some not.

4. auto
This is the default storage class for all the variables declared inside a function or a block. Auto variables
can be only accessed within the block/function they have been declared and not outside them (which
defines their scope).
Properties of auto Variables
●​ Scope: Local
●​ Default Value: Garbage Value
●​ Memory Location: RAM
●​ Lifetime: Till the end of its scope

Example:
#include <stdio.h>
int main() {
// auto is optional here, as it's the default storage class
auto int x = 10;
printf("%d", x);
return 0;
}
Output
10
Explanation: The auto keyword is used to declare a local variable with automatic storage. However, in

Geetha N, Dept of CSE BMSCE


C, local variables are automatically auto by default, so specifying auto is optional.
auto keyword is not used in front of functions as functions are not limited to block scope.

Operations in C
An operator is a symbol that specifies the mathematical, logical, or relational operation to be
performed. It is categorized into the following major groups:

●​ Arithmetic operators​

●​ Relational operators​

●​ Equality operators​

●​ Logical operators​

●​ Unary operators​

●​ Conditional operators​

●​ Bitwise operators​

●​ Assignment operators​

●​ Comma operator​

●​ sizeof operator​

(1) Arithmetic Operators


Consider three variables declared as:​
int a = 9, b = 3, result;

Operation Operator Syntax Comment Result

Multiply * a*b result = a * b 27

Divide / a/b result = a / b 3

Addition + a+b result = a + b 12

Subtraction - a-b result = a - b 6

Modulus % a%b result = a % b 0

Geetha N, Dept of CSE BMSCE


(2) Relational Operators

A relational operator, also known as a comparison operator, is an operator that compares two values.

●​ Used to determine relationship between the operands.


●​ Relational operators return true or false value, depending on whether the condition (relationship) of
2 operands holds or not.
●​ Evaluated from left to right.
●​ Characters are considered valid operands since they are represented by numeric values in the
computer system.​
So, if we say 'A' < 'B', where A = 65 and B = 66, then the result would be 1 as 65 < 66.
●​ When arithmetic expressions are used on either side of a relational operator, then first the
arithmetic expression will be evaluated, and then the result will be compared.​
This is because arithmetic operators have a higher priority over relational operators.
●​ However, relational operators should not be used for comparing strings, as this will result in
comparing the address of the string and not their contents.

Relational Operators Table

Operator Meaning Syntax Example Result

< Less than a<b 10 < 20 1

> Greater than a>b 10 > 20 0

<= Less than or equal to a <= b 10 <= 20 1

>= Greater than or equal to a >= b 10 >= 20 0

(3) Equality Operations

●​ C supports 2 kinds of equality operations to compare the operands for strict equality or inequality.
●​ They are equal to (==) and not equal to (!=) operators.

Operator Meaning

== Returns 1 if both operands are equal, 0 otherwise

!= Returns 1 if operands do not have the same value, 0 otherwise

( 4) Logical Operations

●​ Supports three logical operators: logical AND (&&), logical OR (||), and logical NOT (!).

Geetha N, Dept of CSE BMSCE


●​ Evaluated from left to right.

Logical AND (&&)

●​ Logical AND is a binary operator, which simultaneously evaluates two values or relational
expressions.
●​ If both the operands are true, then the whole expression evaluates to true.
●​ If either of the operands is false, then the whole expression evaluates to false.

A B A && B

0 0 0

0 1 0

1 0 0

1 1 1

For example:

●​ (a < b) && (b < c)


●​ (5 < 7) && (7 > 3) = 1 (true)
●​ (3 < 5) && (5 > 7) = 0 (false)

Logical OR (||)

●​ Returns a false value if both the operands are false; otherwise, it returns a true value.

| A | B | A || B |​
|---|---|--------|​
| 0 | 0 | 0 |​
| 0 | 1 | 1 |​
| 1 | 0 | 1 |​
|1|1|1|

For example:

●​ (a < b) || (b < c)
●​ (5 < 3) || (5 > 2) = 1 (true)
●​ (3 < 5) || (2 > 5) = 1 (true)

Logical NOT (!)

●​ Takes a single expression and negates the value of the expression.


●​ That is, logical NOT produces a 0 if the expression evaluates to a non-zero value and produces a 1 if
the expression produces a zero.

For example:

int a = 10, b;

Geetha N, Dept of CSE BMSCE


b = !a; // The value of b = 0

( 5) Increment Operator (++) and Decrement Operator (--)


●​ The increment operator increases the value of its operand by 1. Similarly, the decrement operator
decreases the value of its operand by 1. --x is equivalent to x = x - 1.
●​ The increment/decrement operations have two variants —​
prefix and postfix.
●​ When postfix ++ or -- is used with a variable, then the expression is evaluated first using the
original value of the variable and then the variable is incremented or decremented by one.
●​ Similarly, when prefix ++ or -- is used with a variable or an expression, then the variable is first
incremented or decremented and then the expression is evaluated using the new value of the variable.

int x = 10, y;
y = x++; // is equivalent to writing
// y = x;
// x = x + 1;
y = ++x; // is equivalent to writing
// x = x + 1;
// y = x;

The same principle applies to unary decrement operators.

Example:
int a=25;
printf(“a++ = %d \n”, a++);
printf(“a-- = %d \n”, a--);
printf(“++a = %d \n”, ++a);
printf(“--a = %d \n”, --a);
Output:
25
26
26

25

(6) Conditional/Ternary Operator


The conditional operator in C is kind of similar to the if-else statement as it follows the same
algorithm as the if-else statement but the conditional operator takes less space and helps to write
the if-else statements in the shortest way possible. It is also known as the ternary operator in C
as it operates on three operands.

Geetha N, Dept of CSE BMSCE


Syntax of Conditional/Ternary Operator in C
The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Or the syntax can also be in this form variable = (condition) ? Expression2 : Expression3;
Or syntax can also be in this form
(condition) ? (variable = Expression2) : (variable = Expression3);

It can be visualized into an if-else statement as:


if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator '?:' takes three operands to work, hence they are also called
ternary operators.
Note: The ternary operator have third most lowest precedence, so we need to use the expressions
such that we can avoid errors due to improper operator precedence management.

Working of Conditional/Ternary Operator in C


The working of the conditional operator in C is as follows:
●​ Step 1: Expression1 is the condition to be evaluated.
●​ Step 2A: If the condition(Expression1) is True then Expression2 will be executed.
●​ Step 2B: If the condition(Expression1) is false then Expression3 will be executed.
●​ Step 3: Results will be returned.

Example 1: C Program to Store the greatest of the two Numbers using the ternary operator
// C program to find largest among two numbers using ternary operator

Geetha N, Dept of CSE BMSCE



#include <stdio.h>
int main()
{
int m = 5, n = 4;

(m > n) ? printf("m is greater than n that is %d > %d",
m, n)
: printf("n is greater than m that is %d > %d",
n, m);
return 0;
}
Output
m is greater than n that is 5 > 4
OR

#include <stdio.h>
int main()
{
int m = 5, n = 4, large;

large = (m > n) ? m : n ;
printf("larger number is %d", large);
return 0;
}

Output
larger number is 5

(7) Bitwise operators

In C, bitwise operators are used to perform operations directly on the binary representations of
numbers. These operators work by manipulating individual bits (0s and 1s) in a number.
The following 6 operators are bitwise operators (also known as bit operators as they work at the
bit-level). They are used to perform bitwise operations in C.
1.​ The & (bitwise AND) in C takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.
2.​ The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of
two numbers. The result of OR is 1 if any of the two bits is 1.
3.​ The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every
bit of two numbers. The result of XOR is 1 if the two bits are different.
4.​ The << (left shift) in C takes two numbers, the left shifts the bits of the first operand,
and the second operand decides the number of places to shift.
5.​ The >> (right shift) in C takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.
6.​ The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

Geetha N, Dept of CSE BMSCE


Bitwise operators allow precise manipulation of bits, giving you control over hardware
operations.

Let’s look at the truth table of the bitwise operators.

X Y X&Y X|Y X^Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
As mentioned in point 1, it works only if numbers are positive.
#include <stdio.h>
int main() {
int x = 19;
printf("x << 1 = %d\n", x << 1);
printf("x >> 1 = %d", x >> 1);
return 0;
}

Output
x << 1 = 38
x >> 1 = 9

(8) Assignment Operators (=)​


The assignment operator is responsible for assigning values to the variables.​
While the equal sign (=) is the fundamental assignment operator, C also supports other assignment
operators that provide a shorthand way to represent common value assignment.​
When an equal sign is encountered in an expression, the compiler processes the statement on the right side
of the sign and assigns the result to the variable on the left side.

Geetha N, Dept of CSE BMSCE


For example:​
int x = 10; → assigns the value 10 to variable x.

int x = 2, y = 3, sum = 0;
sum = x + y;

Expression would be evaluated and the result would be stored in the location denoted by the variable name.​
Then sum = 5.

The assignment operator has right-to-left associativity, so the expression​


a = b = c = 10;​
is evaluated as (a = (b = (c = 10))).

First 10 is assigned to c, then the value of c is assigned to b. Finally, the value of b is assigned to a.​
The operand to the left of the assignment operator must always be a variable name.

Assignment operations​
a += b ⇒ variable += expression​
variable = variable + expression

For example a += b ⇒ a = a + b

Operator Syntax Equivalent to

/= a /= b a=a/b

*= a *= b a=a*b

+= a += b a=a+b

-= a -= b a=a-b

&= a &= b a=a&b

^= a ^= b a=a^b

<<= a <<= b a = a << b

>>= a >>= b a = a >> b

(9) Comma Operator

●​ The comma operator in C takes 2 operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the result of
the expression.

Example:

int a = 2, b = 3, x = 0;
x = (a + a, b + a);

Geetha N, Dept of CSE BMSCE


Now, x = 6

(10) sizeof Operator

●​ Unary operator used to calculate the size of data types.


●​ When using this operator, the keyword sizeof is followed by a type name, variable, or
expression.
●​ The operator returns size in bytes.​

Examples:

sizeof(int) → returns 2
sizeof(char) → returns 1

Evaluating Expressions
C operations have 2 properties: priority and associativity. When an expression has more than
one operator, then it is the priority of the operator that determines the order in which the
expression will be evaluated.​
Associativity indicates the order in which the operators of equal precedence in an expression are
evaluated.

Operator Associativity

()[] L–R

++, -- (postfix) R–L

++, -- (prefix) R–L

+, -, ! (unary) R–L

~ (Bitwise not) R–L

sizeof L–R

*/% L–R

+- L–R

<< >> (Bitwise shift) L–R

< > <= >= (Relational operator) L–R

== != (Equality) L–R

Geetha N, Dept of CSE BMSCE


& (Bitwise AND) L–R

^ (Bitwise XOR) L–R

| (Bitwise OR) L–R

&& (Logical AND) L–R

|| (Logical OR) L–R

? : (Ternary) R–L

= += -= *= /= %= &= ^= <<= >>= (Assignment) R – L

, (Comma) L–R

① x = 3 × 4 + 5 × 6​
= 12 + 30​
= 42

② x = 3 × (++5) × 6​
= 3 × 6 × 6​
= 3 × 36​
= 108

③ x = 3 × ((4 + 8)/2)​
= 3 × (12/2)​
= 3 × 6​
= 18

int a = 0, b = 1, c = -1;​
float x = 2.5, y = 0.0;

④ a + b - c × x = 10​
= a + (b - (c × 10))​
= a + (b - (-10))​
= a + (b = 11)​
= 0 + 11 = 11

⑤ a && b && c​
= 0 && 1 && -1 = 0

H.W problems

(for the above given values of a, b, c, x & y)

① -a × (5 + b) / 2 - c + x * b ② a * b < c ③ a || b || c ④ a < b && c < b​


⑤ b + c || !a ⑥ x * 5 && 5 || (b / c)

⑦ Write a program to print the ASCII value of a character.

Geetha N, Dept of CSE BMSCE


#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
printf("\nThe ASCII value of %c is: %d", ch, ch);
return 0;
}

Output:​
Enter any character: A​
The ASCII value of A is: 65

⑧ Write a program to read a character in uppercase and then print it in lowercase.

#include <stdio.h>
int main()
{
char ch;
printf("Enter any uppercase character: ");
scanf("%c", &ch);
​ printf("\n The character in lowercase is: '%c'", ch+32);
return 0;
Output:

Enter any uppercase character: A


The character in lowercase is: a

(1) Write a program to print the digit at ones place of a number.

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

digit_atones = num % 10;


printf("The digit at ones place is '%d' ", digit_atones);

return 0;
}
Output:
Enter any number: 123
The digit at ones place is 3

Geetha N, Dept of CSE BMSCE


(2) Write a program to swap 2 numbers using a temporary variable.

#include <stdio.h>
int main()
{
int n1, n2, temp;
printf("\n Enter the first number:");
scanf("%d", &n1);
printf("\n Enter the second number:");
scanf("%d", &n2);

temp = n1;
n1 = n2;
n2 = temp;

printf("\n The first number is '%d' ", n1);


printf("\n The second number is '%d' ", n2);
return 0;
}
Output:
Enter the first number: 3
Enter the second number: 5
The first number is 5
The second number is 3

Write a program to convert degrees Fahrenheit into degree Celsius.


#include <stdio.h>
int main()
{
float F, C;
printf("Enter temperature in F:");
scanf("%f", &F);

C = (0.56) * (F - 32);

printf("Temperature in C: %2f", C);


return 0;
}

Output:

Enter temperature in F: 32
Temperature in C: 0.0

(Calcius to Fahrenheit) F = ((C * (9/5)) + 32

Write a program to calculate the total amount of money in the piggybank, given the coins

Geetha N, Dept of CSE BMSCE


of Rs.10, Rs.5, Rs.2 and Rs.1
#include <stdio.h>
int main()
{
int total10, total5, total2, total1;
int total_amt;

printf("Enter number of Rs 10 coin:");


scanf("%d", &total10);

printf("Enter number of Rs 5 coin:");


scanf("%d", &total5);

printf("Enter number of Rs 2 coin:");


scanf("%d", &total2);

printf("Enter number of Rs 1 coin:");


scanf("%d", &total1);

total_amt = total10 * 10 + total5 * 5


+ total2 * 2 + total1 * 1;

printf("\nThe total amount in the piggybank = %d", total_amt);

return 0;
}

Output:

Enter number of Rs 10 coin: 10


Enter number of Rs 5 coin: 23
Enter number of Rs 2 coin: 45
Enter number of Rs 1 coin: 6

The total amount in the piggybank = 307

Type Conversion and Typecast


●​ Type conversion or typecasting of variables refers to changing a variable of one data type
into another.
●​ Type conversion is done implicitly, whereas typecasting has to be done explicitly by the
programmer.​

Type Conversion
●​ Type conversion is done when the expression has variables of different data types.
●​ To evaluate the expression, the data type is promoted from lower to higher level where
required.

Geetha N, Dept of CSE BMSCE


The hierarchy of data type can be given as:

double, float, long, int, short, and char.​


(From higher to lower)

Type conversion is done automatically when we assign an integer value to a floating point
variable.​
(This is known as promotion, when a lower level data type is promoted to a higher type.)

float x;
int y = 3;
x = y;

Now, x = 3.0, as automatically integer value is converted into its equivalent floating point
representation.

If any operand is double or long, the other operand is also converted to double or long
respectively.

Consider the following stmts:


float f = 3.5;
int i;
i = f;

i = f results in f to be demoted to type int, i.e., the fractional part of f will be lost and i will
contain 3, not 3.5.

This is known as demotion. (Higher level data type is converted into a lower type.)

Whenever demotion occurs, some information is lost.

Similarly, if we convert an int to a short int or a long int to int, or int to char, the compiler just
drops the extra bits.

Typecasting

Typecasting is also known as forced conversion. Changing a variable of one data type to
another is done explicitly.

float salary = 10000.00;


int sal;

sal = (int) salary;

●​ Floating point numbers are converted to integers – the digits after the decimal are truncated.
●​ Typecasting can be done by placing the destination data type in parentheses followed by the
variable name that has to be converted.

Geetha N, Dept of CSE BMSCE


(Examples of Type Casting in C):

int a = 500, b = 70;


float res;
res = (float) a / b;

res = (int) 9.5;


res = (int) 12.3 / (int) 4.2;
res = (int) a + b;
res = cos ((double) x);

Write a program to convert a floating point number into the corresponding integer.

#include <stdio.h>
int main()
{
float fnum;
int inum;
printf("Enter floating point number: ");
scanf("%f", &fnum);
inum = (int)fnum;
printf("The integer variant of %f is = %d", fnum, inum);
return 0;
}

Sample Output 1
Enter floating point number: 12.98
The integer variant of 12.980000 is = 12

Sample Output 2
Enter floating point number: -45.67
The integer variant of -45.670000 is = -45

●​ The statement inum = (int)fnum; typecasts the floating-point number to an integer.​

●​ This conversion truncates the decimal part (it does not round off).​

○​ Example:​
12.98 → 12​
-45.67 → -45

In C, there are many input and output for different situations, but the most commonly used
functions for Input/Output are scanf() and printf() respectively. These functions are part of the
standard input/output library <stdio.h>. scanf() takes user inputs (typed using keyboard) and
printf() displays output on the console or screen.
printf() — Basic Output in C
The printf() function is used to print formatted output to the standard output stdout (which is

Geetha N, Dept of CSE BMSCE


generally the console screen). It is one of the most commonly used functions in C.
Syntax – printf("formatted_string", variables/values);
Where,
●​ Formatted String: string defining the structure of the output and include format
specifiers
●​ variables/values: arguments passed to printf() that will replace the format specifiers
in the formatted string.

Examples

Printing Some Text


#include <stdio.h>
int main() {
// Prints some text
printf("First Print");
return 0;
}

Output
First Print

Explanation: The text inside "" is called a string in C. It is used to represent textual information.
We can directly pass strings to the printf() function to print them in console screen.
Printing Variables
#include <stdio.h>
int main() {
int age = 22;
// Prints Age
printf("%d\n", age);
return 0;
}

Output
22
Here, the value of variable age is printed. You may have noticed %d in the formatted string. It is
actually called format specifier which are used as placeholders for the value in the formatted
string. You may have also noticed '\n' character. This character is an escape sequence and is used
to enter a newline.
Printing Variables Along with String
#include <stdio.h>
int main() {
int age = 22;

Geetha N, Dept of CSE BMSCE


// Prints Age
printf("The value of the variable age is %d\n", age);
return 0;
}

Output
The value of the variable age is 22
The printf function in C allows us to format the output string to console. This type of string is called
formatted string as it allows us to format (change the layout the article).

scanf() — Basic Input in C


scanf() is used to read user input from the console. It takes the format string and the addresses of the
variables where the input will be stored.

Syntax – scanf("formatted_string", address_of_variables/values);

Remember that this function takes the address of the arguments where the read value is to be stored.

Reading an Integer

#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");

// Reads an integer
scanf("%d", &age);

// Prints the age


printf("Age is: %d\n", age);
return 0;
}

Output
Enter your age:
25 (Entered by the user)
Age is: 25
Explanation: %d is used to read an integer; and &age provides the address of the variable where the
input will be stored.
Reading a Character
#include <stdio.h>

int main() {

Geetha N, Dept of CSE BMSCE


char ch1, ch2;
printf("Enter a character: \n");

// Reads an Character
scanf("%c", &ch1);

// Prints the Character


printf("Entered character is: %c\n", ch1);
return 0;
}

Output
Enter a character:
a (Entered by the user)
Entered character is: a
Reading a string
The scanf() function can also be used to read string input from users. But it can only read single words.
#include <stdio.h>
int main() {
char str1[100], str2[100]; // Declare an array to hold the input string

printf("Enter a string: ");


scanf("%s", str1); // Reads input until the first space
printf("Enter second string: ");
gets(str2); // Reads input until the newline

puts(str1);
printf("You entered: %s\n", str2);

return 0;
}

Output:
Enter a String: hello
Enter second string: world
hello
world

The scanf() function can not handle spaces and stops at the first blank space. To handle this situation
we can use fgets() which is a better alternative as it can handle spaces and prevent buffer overflow.

Geetha N, Dept of CSE BMSCE

You might also like