Fundamentals of Computer Programming - Unit I
Fundamentals of Computer Programming - Unit I
UNIT-1
Introduction to C - Introduction to C 12 Hours Overview of C - Introduction - Character set - C tokens -
keyword & Identifiers - Constants - Variables - Data types - Declaration of variables - Assigning values to
variables - Defining Symbolic Constants - Arithmetic, Relational, Logical, Assignment, Conditional,
Bitwise, Special, Increment and Decrement operators - Arithmetic Expressions - Evaluation of expression -
precedence of arithmetic operators - Type conversion in expression – operator precedence & associativity -
Mathematical functions - Reading & Writing a character - Formatted input and output.
UNIT-II
Decision Making and Branching: Introduction – If, If….Else, nesting of If …Else statements- Else If
ladder – The Switch statement, The ?: Operator – The Go to Statement. Decision Making and Looping:
Introduction- the While statement-the do statement – the for statement-jumps in loops. Arrays - Character
Arrays and Strings.
UNIT-III
C++ - Introduction to C++ - key concept s of Object-oriented Programming– Advantages–Object Oriented
Languages–I/O in C++- C++Declarations. Functions in C++-inline functions– Function Overloading.
Classes and Objects: Declaring Objects–Defining Member Functions– Static Member variables and
functions– array of objects–friend functions–Overloading member functions– Bit fields and classes –
Constructor and destructor with static members.
UNIT-IV
Inheritance - Operator Overloading: Overloading unary, binary operators – Overloading Friend functions –
type conversion Inheritance: Types of Inheritance– Single, Multilevel, Multiple, Hierarchal, Hybrid,
Multipath inheritance –Virtual base Classes– Abstract Classes
UNIT-V
Pointers & Files - Pointers–Declaration–Pointer to Class, Object–this pointer– Pointers to derived classes
and Base classes–Arrays– Characteristics–array of classes. Files–File stream classes–file modes–
Sequential Read/Write operations– Binary and ASCII Files –Random Access Operation–Templates–
Exception Handling– Miscellaneous functions.
Text Book
1. E Balagurusamy: Computing Fundamentals & C Programming – Tata McGraw-Hill, Second Reprint
2008
Unit-1
COMPUTER
A computer is an electronic device that manipulates information, or data. It has the ability
to store, retrieve, and process data. You may already know that you can use a computer to type
documents, send email, play games, and browse the Web. You can also use it to edit or
create spreadsheets, presentations, and even videos.
Hardware vs. software
Before we talk about different types of computers, let's talk about two things all computers have in
common: hardware and software.
Hardware is any part of your computer that has a physical structure, such as the keyboard or
mouse. It also includes all of the computer's internal parts, which you can see in the image below.
Software is any set of instructions that tells the hardware what to do and how to do it. Examples
of software include web browsers, games, and word processors.
A computer is an electronic device wherein we need to input raw data to be processed with a set of
programs to produce a desirable output.
Computers have the ability to store, process, and manipulate data.
The term “computer” is derived from the Latin word “computare,” which means “to calculate.”
A computer is made to run programs and apps by using both hardware and software.
It also has a memory to store data, programs,
Characteristics of Computer
Computers are now an integral part of our daily lives, from managing student records in schools to
handling patient records in hospitals.
They have significantly simplified our tasks.
Now, we can quickly access stored data and solve complex problems in just seconds. Some of the
characteristics of Computers are listed below-
Saves Time: A computer saves time by completing tasks quicker and more efficiently. For
example, it can solve big complex problems within seconds which can save many minutes of
ours.
Internet: Computers connect us to the internet which can help us to know important
information from around the world, it can connect us with people from around the world
through social networking sites, etc.
Storage: The computer gives us enough storage space that can be used to store a large
amount of data including your projects, ebooks, documents, movies, pictures, songs, etc.
Entertainment: Computers are also a big source of entertainment as you can play games,
listen to songs, watch movies, and can also use social networking sites.
Organized Data: It not only stores the data for you for also organizes the data for you. You
can create different folders for different types of data and can easily access them when
required.
Features of Computer
We have discussed a few points that will highlight the different features of computers. These
features collectively contribute to the versatility and functionality of computers.
Processing Power: Computers can execute instructions and perform calculations quickly.
Storage Capacity: They can store vast amounts of data, from documents to multimedia files.
Memory (RAM): Temporary storage used for actively running programs and processes.
Input Devices: Keyboards, mouse, and other peripherals allow users to input data.
Output Data: Monitors, printers, and speakers display or produce results.
Upgradability: Components like RAM, storage, and graphics cards can be upgraded.
Portability: Laptops and tablets offer mobility compared to desktop computers.
User Interface: Graphical user interfaces (GUIs) or command-line interfaces for interaction.
Security Features: Passwords, firewalls, and antivirus tools protect against unauthorized
access.
Power Management: Features to optimize energy consumption.
INTRODUCTION TO C
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other. For
example, if we want to teach someone, we need a language that is understandable by both
communicators.
Operating structures
Web browsers
Mobile apps
Desktop packages
Video games
General Software program
Business-related software programs
Embedded structures
Low-level language is machine-dependent (0s and 1s) programming language. The processor runs
low- level programs directly without the need of a compiler or interpreter, so the programs written in
low-level language can be run very fast.
i. Machine Language
Machine language is a type of low-level programming language. It is also called as machine code or
object code. Machine language is easier to read because it is normally displayed in binary or
hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to execute the programs faster
than the high-level programming language.
Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-understandable
form. It uses an assembler to convert the assembly language to machine language.
The advantage of assembly language is that it requires less memory and less execution time to
execute a program.
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective
C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.
Procedural Oriented Programming (POP) language is derived from structured programming and
based upon the procedure call concept. It divides a program into small procedures called routines or
functions.
The advantage of POP language is that it helps programmers to easily track the program flow and
code can be reused in different parts of the program.
Object-Oriented Programming (OOP) language is based upon the objects. In this programming
language, programs are divided into small parts called objects. It is used to implement real-world
entities like inheritance, polymorphism, abstraction, etc in the program to makes the program
resusable, efficient, and easy-to-use.
The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.
Natural language is a part of human languages such as English, Russian, German, and Japanese. It
is used by machines to understand, manipulate, and interpret human's language. It is used by
developers to perform tasks such as translation, automatic summarization, Named Entity
Recognition (NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any subject and
directly respond within seconds.
Middle-level programming language lies between the low-level programming language and high-
level programming language. It is also known as the intermediate programming language and
pseudo-language.
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
C programming is a versatile and powerful language that has played a significant role in shaping the
world of computer programming.
It was developed at Bell Laboratories by Dennis Ritchie in the early 1970s. Over the decades, C
has evolved and remains one of the most widely used programming languages in the world.
In this article, we will explore the essence of C programming, its fundamental features, basic
syntax, various applications, and many more.
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is known
as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the
programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being used
in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language
C is a procedural language. In C, variables and function prototypes must be declared before being
used.
In the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.
C is considered as a middle-level language because it supports the feature of both low-level and
high-level languages. C language program is converted into assembly code, it supports pointer
arithmetic (low-level), but it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent,
fast to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.
C Program
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
HISTORY OF C LANGAUGE
History of C language is interesting to know. Here we are going to discuss a brief history of the c
language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features
of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
1. C is the widely used language. It provides many features that are given below.
2. Simple
3. Machine Independent or Portable
4. Mid-level programming language
5. Structured programming language
6. Rich Library
7. Memory Management
8. Fast Speed
9. Pointers
10. Recursion
11. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.
Unlike assembly language, c programs can be executed on different machines with some machine specific
changes. Therefore, C is a machine independent language.
C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.
5) Rich Library
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and
hence the lesser overhead.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
INTRODUCTION
C CHARACTER SET
What is Character Set in C?
In C, a character set refers to a predefined collection of characters recognized by the language.
This set typically includes the alphabet (both lowercase and uppercase), digits, special symbols, and
control characters.
The most commonly used character set in C is ASCII (American Standard Code for Information
Interchange), which assigns numeric codes to characters.
These codes are used to represent characters in memory and facilitate operations involving
characters, such as input/output operations, string manipulation, and comparison.
Use of Character Set in C
It is used to specify the acceptable characters that can be inserted into the source code or interpreted
while the programme is executing.
In C, the character set is applied in the following ways:
Character representation: The character set represents characters in the source programme. The ASCII
code 65, for instance, is used to represent the letter A.
To represent special symbols: In the source programme, special symbols are represented by the character
set. For instance, addition in C is denoted by the symbol +.
To create words and phrases: In the source programme, words and expressions are created using the
character set. For instance, the letters h, e, l, and o combine to make the word hello.
Digits
The C programming language also supports digits for building numeric expressions.
Digits: 0-9 (10 characters)
Special Characters
Certain special characters are used in C programs in arithmetic expressions, punctuation marks, conditional
operators, etc. These characters can also be used in defining the attributes of a program in a better way.
Special Characters: ` ~ @ ! $ # ^ * % & ( ) [ ] { } < > + = _ – | / \ ; : ‘ “ , . ?
White spaces
The white space characters in C refer to vertical and horizontal spaces in the source code.
White spaces: Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab, null
Special Characters in C
In C programming, special characters are often used to represent control characters or to format output. Here
are some commonly used special characters:
o \n: Represents a newline character.
o \t: Represents a tab character.
o \b: Represents a backspace character.
o \r: Represents a carriage return character.
o \: Represents a backslash character.
o ': Represents a single quote character.
o ": Represents a double quote character.
The various character sets that can be used with the C language are shown in the following table:
Uppercase
A-Z (26 characters)
Alphabets
Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab,
White spaces
null
Tokens in C
A token in C can be defined as the smallest individual element of the C programming language that
is meaningful to the compiler.
It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program.
Since keywords are referred names for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.
You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using C
preprocessor directives.
C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Note: The number of keywords may change depending on the version of C you are using. For example,
keywords present in ANSI C are 32 while in C11, it was increased to 44. Moreover, in the latest c23, it is
increased to around 54.
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and arrays.
These are user-defined names consisting of an arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use.
Once declared, you can use the identifier in later program statements to refer to the associated value.
A special identifier called a statement label can be used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,
main: method name.
a: variable name.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal variables but with the difference
that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;
4. C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null character
indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character is
enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The data
items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified as
follows:
Unary Operators: Those operators that require only a single operand to act upon are known as unary
operators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the
ternary operator. Conditional Operator(?) is also called the ternary operator.
CONSTANTS
C Constants are like a variable, except their value never changes during execution once defined. This
tutorial describes C Constants.
C Constant is the most fundamental and essential part of the C programming language. Constants in
C are the fixed values used in a program, and their value remains the same during the entire program
execution.
Constants are also called literals.
Constants can be any of the data types.
It is considered best practice to define constants using only upper-case names.
Constant Definition in C
Syntax:
const type constant_name;
const keyword defines a constant in C.
Example:
#include<stdio.h>
void main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq. units", SIDE, area);
}
Program Output:
Putting const either before or after the type is possible.
Constant Types in C
Constants are categorized into two basic types, each of which has subtypes/categories. These are:
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer Constant
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
The numbers containing fractional parts like 99.25 are called real or floating points constant.
It simply contains a single character enclosed within ' and ' (a pair of the single quote). It is to be noted that
the character '8' is not the same as 8. Character constants have specific integer values known as ASCII
(American Standard Code for Information Interchange).
Example:
These are a sequence of characters enclosed in double quotes, and they may include letters, digits, special
characters, and blank spaces. Note that "G" and 'G' are different - because "G" represents a string as it is
enclosed within a pair of double quotes, whereas 'G' means a single character.
Example:
C supports some character constants having a backslash in front of it. The lists of backslash characters have
a specific meaning known to the compiler. They are also termed "Escape Sequences".
Example:
Constants Meaning
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0 null
Secondary Constant
Array
Pointer
Structure
Union
Enum
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. Each data type requires different amounts of memory and has some
specific operations which can be performed over it. The data type is a collection of data with values having
fixed values, meaning as well as its characteristics.
The data types in C can be classified as follows:
Types Description
Primitive Data Primitive data types are the most basic data types that are used for representing
Types simple values such as integers, float, characters, etc.
The data types that are derived from the primitive or built-in datatypes are referred
Derived Types
to as Derived Data Types.
The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
float 4 byte
double 8 byte
Integers are entire numbers without any fractional or decimal parts, and the int data type is used to represent
them.
It is frequently applied to variables that include values, such as counts, indices, or other numerical numbers.
The int data type may represent both positive and negative numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2 billion
and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256 characters that
can be represented by a single char, which takes up one byte of memory. Characters such as 'A', 'b',
'5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent fractional units
or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be very precise. It
can store values with an accuracy of about 6 decimal places and a range of about 3.4 x 1038 in 4 bytes of
memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed, such as in
scientific calculations or financial applications, it provides greater accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields larger
values. C treats floating point numbers as doubles by default if no explicit type is supplied.
In the example above, we declare four variables: an int variable for the person's age, a char variable for the
student's grade, a float variable for the temperature reading, and two variables for the number pi.
Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions. These data types give programmers the ability to handle heterogeneous data, directly
modify memory, and build complicated data structures.
Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It provides
a mechanism for joining multiple targets of the same data under the same name.
The index is used to access the elements of the array, with a 0 index for the first entry. The size of the array
is fixed at declaration time and cannot be changed during program execution. The array components are
placed in adjacent memory regions.
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When a pointer is
declared, the data type it refers to is stated first, and then the variable name is preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by specifying the memory
address of the variable. Pointers are commonly used in tasks such as function pointers, data structures,
and dynamic memory allocation.
Output:
Value of num: 42
Structure:
A structure is a derived data type that enables the creation of composite data types by allowing the grouping
of many data types under a single name. It gives you the ability to create your own unique data structures by
fusing together variables of various sorts.
1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.
1. struct Person {
2. char name[50];
3. int age;
4. float height;
5. };
Union:
A derived data type called a union enables you to store various data types in the same memory address. In
contrast to structures, where each member has a separate memory space, members of a union all share a
single memory space. A value can only be held by one member of a union at any given moment. When you
need to represent many data types interchangeably, unions come in handy. Like structures, you can access
the members of a union by using the dot (.) operator.
1. union NumericValue {
2. int intValue;
3. float floatValue;
4. char stringValue[20];
5. };
Enumeration Data Type
A set of named constants or enumerators that represent a collection of connected values can be defined in C
using the enumeration data type (enum). Enumerations give you the means to give names that make sense
to a group of integral values, which makes your code easier to read and maintain.
1. enum DaysOfWeek {
2. Monday,
3. Tuesday,
4. Wednesday,
5. Thursday,
6. Friday,
7. Saturday,
8. Sunday
9. };
Void Data Type
The void data type in the C language is used to denote the lack of a particular type. Function return types,
function parameters, and pointers are three situations where it is frequently utilized.
A void return type function does not produce a value. A void function executes a task or action and ends
rather than returning a value.
Example:
Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a method for
working with pointers to ambiguous or atypical types.
Example:
1. void* dataPtr;
The void data type is helpful for defining functions that don't accept any arguments when working with
generic pointers or when you wish to signal that a function doesn't return a value. It is significant to note that
while void* can be used to build generic pointers, void itself cannot be declared as a variable type.
Here is a sample of code that shows how to utilize void in various situations:
1. #include <stdio.h>
2. // Function with void return type
3. void printHello() {
4. printf("Hello, world!\n");
5. }
6. // Function with void parameter
7. void processInput(void) {
8. printf("Processing input...\n");
9. }
10.
11. int main() {
12. // Calling a void function
13. printHello();
14.
15. // Calling a function with void parameter
16. processInput();
17.
18. // Using a void pointer
19. int number = 10;
20. void* dataPtr = &number;
21. printf("Value of number: %d\n", *(int*)dataPtr);
22. return 0;
23. }
Output:
Hello, world!
Processing input...
Value of number: 10
VARIABLES
Variables in C
A variable is the name of the memory location. It is used to store information. Its value can be altered and
reused several times. It is a way to represent memory location through symbols so that it can be easily
identified.
Variables are key building elements of the C programming language used to store and modify data in
computer programs. A variable is a designated memory region that stores a specified data type value. Each
variable has a unique identifier, its name, and a data type describing the type of data it may hold.
Syntax:
1. data_type variable_name;
Here,
o data_type: It represents the type of data the variable can hold. Examples of data types in C
include int (integer), float (a floating-point number), char (character), double (a double-precision
floating-point number),
o variable_name: It is the identifier for the variable, i.e., the name you give to the variable to access
its value later in the program. The variable name must follow specific rules, like starting with
a letter or underscore and consisting of letters, digits, and underscores.
1. int age;
It declares an integer variable named age without assigning it a specific value. Variables can also be
initialized at the time of declaration by assigning an initial value to them. For instance:
1. int count = 0;
Syntax:
1. type variable_list;
1. int a;
2. float b;
3. char c;
Here, a, b, and c are variables. The int, float, and char are the data types.
In C, Variable names must follow a few rules to be valid. The following are the rules for naming variables
in C:
o Allowed Characters:
Variable names include letters ( uppercase and lowercase ), digits, and underscores. They must start with
a letter (uppercase or lowercase) or an underscore.
o Case Sensitivity:
C is a case-sensitive programming language. It means that uppercase and lowercase letters are considered
distinct.
For example, myVar, MyVar, and myvar are all considered different variable names.
o Keywords:
Variable names cannot be the same as C keywords (reserved words), as they have special meanings in the
language.
For example, you cannot use int, float, char, for, while, etc., as variable names.
o Length Limitation:
There is no standard limit for the length of variable names in C, but it's best to keep them reasonably short
and descriptive.
o Reserved Identifiers:
While not strictly a rule, it is advisable to avoid specific patterns or identifiers common in libraries or
standard usage.
For example, variables starting with __ (double underscores) are typically reserved for system or compiler-
specific usage.
1. int age;
2. float salary;
3. char _status;
4. double average_score;
5. int studentCount;
Following these rules ensures that your variable names are valid and conform to the C language's syntax
and conventions. Choosing meaningful and descriptive names for variables is essential to enhance the
readability and maintainability of your code.
DECLARATION OF VARIABLES
Let us explain the three aspects of defining a variable: variable declaration, variable definition, and
variable initialization, along with examples.
1. Variable Declaration:
The process of telling the compiler about a variable's existence and data type is known as variable
declaration. It notifies the compiler that a variable with a specific name and data type will be used in the
program. Still, no memory for the variable is allocated at this moment. It is usually seen at the start of a
function or block before the variable is utilized.
1. data_type variable_name;
1. #include <stdio.h>
2. int main() {
3. // Variable declaration
4. int age;
5. float salary;
6. char initial;
7. return 0;
8. }
2. Variable Definition:
The process of reserving memory space for the variable to keep its contents during program execution is
known as a variable definition. It is based on the data type and connects the variable name with a particular
memory address of sufficient size.
A variable in C can be declared and defined in the same statement, although they can also be separated if
necessary.
1. #include <stdio.h>
2. int main() {
3. // Variable definition
4. int age = 25;
5. float salary = 2500.5;
6. char initial = 'J';
7. return 0;
8. }
3. Variable Initialization:
Variable declaration is the act of informing the compiler about the existence and data type of a variable. It
informs the compiler that a variable with a specific name and data type will be used in the program, but that
memory for the variable still needs to be allocated.
Not explicitly initialized variables will contain garbage/random data that may result in unexpected program
behavior.
In the example above, we have variable age, salary, and initial declarations. After that, we define these
variables and initialize them with initial values (e.g., age = 25). Later in the program, we can modify the
values of these variables (e.g., age = 30).
A variable is a name given to a storage area that our programs can manipulate. Each variable in C# has a
specific type, which determines the size and layout of the variable's memory the range of values that can be
stored within that memory and the set of operations that can be applied to the variable.
To assign values to a variable, add the value after the equal operator −
int a = 10;
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int a;
a = 100;
Console.WriteLine("a = {0}", a);
Console.ReadLine();
}
}
}
Output
a = 100
Symbolic Constants in C
Identifiers are used to represent fixed values in programs using symbolic constants in the C programming
language. These parameters are frequently used to increase the readability, maintainability,
and modifiability of code, which may be numerical or not. The C language's "#define" command is used to
declare symbolic constants.
Syntax:
In this example, the symbolic constant "MAX_V" is specified to have a value of 100. It indicates that
the number 100 will be substituted for "MAX_V" wherever it appears in the code at compilation time.
For example:
Additionally, macros, which are essentially functions that are expanded at compile time, can be defined
using symbolic constants.
For example:
In this example, the macro "CUBE" is defined to accept a single input "x" and return the cube of that
argument. It can be helpful for defining additional little functions that are regularly utilized throughout a
program or for carrying out simple computations.
OPERATORS
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of operations
like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Special Operator
o Increment and Decrement Operators
Arithmetic Operators:
Arithmetic operators carry out fundamental mathematical operations. The arithmetic operators in C are as
follows:
Addition Operator (+): The addition operator adds two operands together.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
3. int result = a + b;
Output:
result = 8
Subtraction Operator (-): The second operand is subtracted from the first operand via the subtraction
operator.
Syntax:
Example:
1. int a = 8;
2. int b = 3;
3. int result = a - b;
Output:
result = 5
Multiplication Operator (*): This operator is used to multiply the two operands.
Syntax:
Example:
1. int a = 4;
2. int b = 5;
3. int result = a * b;
Output:
result = 20
Division Operator (/): The first operand and the second operand are divided using the division operator.
Syntax:
Example:
1. int a = 10;
2. int b = 2;
3. int result = a / b;
Output:
result = 5
Modulus Operator (%): The modulus operator determines the remainder of the division between two
operands.
Syntax:
Example:
1. int a = 10;
2. int b = 3;
3. int result = a % b;
Output:
result = 1
Relational Operators:
Relational operators assess the relationship between values by comparing them. They return either true
(1) or false (0). The relational operators in C are as follows:
Equality Operator (==): If two operands are equal, the equality operator verifies this.
Syntax:
Example:
1. int a = 5;
2. int b = 5;
3. int result = a == b;
Output:
result=1 (true)
Inequality Operator (!=): The inequality operator determines whether two operands are equal or not.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
3. int result = a != b;
Output:
result=1 (true)
Greater than Operator (>): The greater than operator determines if the first operand exceeds the second
operand.
Syntax:
Example:
1. int a = 7;
2. int b = 4;
3. int result = a > b;
Output:
result=1 (true)
Less than Operator (<): The less-than operator determines if the first operand less is than the second
operand.
Syntax:
Example:
1. int a = 2;
2. int b = 6;
3. int result = a < b;
Output:
result=1 (true)
Greater than or Equal to Operator (>=): The greater than or equal to operator determines if the first
operand is more than or equal to the second operand.
Syntax:
Example:
1. int a = 5;
2. int b = 5;
3. int result = a >= b;
Output:
result=1 (true)
Less than or Equal To Operator (<=): The less than or equal to operator determines if the first operand
must be less than or equal to the second operand.
Syntax:
Example:
1. int a = 3;
2. int b = 6;
3. int result = a <= b;
Output:
result=1 (true)
Shift Operators:
A binary number's bits can be moved to the left or right using shift operators. The C shift workers are listed
below:
Left Shift Operator (<<): The left shift operator moves the bits of the first operand to the left by the
number of places indicated by the second argument.
Syntax:
Example:
Output:
Right Shift Operator (>>): The right shift operator shifts the bits of the first operand to the right by the
number of positions specified by the second operand.
Syntax:
Example:
Output:
Logical operators perform logical operations on boolean values and return either true (1) or false (0). Here
are the logical operators in C:
Logical AND Operator (&&): The logical AND operator returns true if both operands are true.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > 3) && (b < 5);
Output:
result = 1 (true)
Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true.
Syntax:
Output:
result = 1 (true)
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.
Syntax:
1. result = !operand;
Example:
1. int a = 5;
2. int result = !(a > 3);
Output:
result = 0 (false)
Bitwise Operators:
Bitwise operators perform operations on individual bits of the operands. Here are the bitwise operators in C:
Bitwise AND Operator (&): The bitwise AND operator performs a bitwise AND operation on the
corresponding bits of the operands.
Syntax:
Example:
Output:
result = 1 // 0000 0001 in binary
Bitwise OR Operator (|): The bitwise OR operator performs a bitwise OR operation on the corresponding
bits of the operands.
Syntax:
Example:
Output:
Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR operation on the
corresponding bits of the operands.
Syntax:
Example:
Output:
Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.
Syntax:
1. result = ~operand;
Example:
Output:
Ternary or Conditional Operator: The ternary or conditional operator allows you to assign a value
based on a condition.
Syntax:
Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > b) ? a : b;
Output:
result = 5
Assignment Operator:
Assignment operators are used to assign values to variables. Here is some of the assignment operator in C:
Simple Assignment Operator (=): The simple assignment operator assigns the value from the right side
operands to the left side operands.
Syntax:
1. variable = value;
Example:
1. int a;
2. a = 5;
Output:
In the C programming language, special operators are used to perform specific operations that cannot be
done with normal arithmetic or logical operators. These operators are special because they have their own
unique syntax and functionality. In this blog post, we will explore some of the most used special operators in
C, including the ternary, bitwise, and comma operators.
Ternary Operator
The ternary operator is also referred to as the conditional operator. It is used to determine whether a
condition is true or false. If the condition is true, it returns one result, and if it is false, it returns
a different value.
Syntax:
Example:
Here's an example that uses the ternary operator to determine whether a number is even or odd:
1. #include <stdio.h>
2. int main() {
3. int num = 7;
4. printf("%d is %s\n", num, num % 2 == 0 ? "even" : "odd");
5. return 0;
6. }
Output
7 is odd
Explanation:
In this example, the condition num % 2 == 0 is evaluated. If it is true (i.e., num is even), the value "even" is
returned. If it is false (i.e., num is odd), the value "odd" is returned.
Bitwise Operators
Bitwise operators are utilized to conduct operations on individual bits within a number. There are six
bitwise operators in C: AND (&), OR (|), XOR (^), left shift (<<), right shift (>>), and complement (~).
Example:
Here's an example that demonstrates how to use the bitwise AND operator to clear a bit in a number:
1. #include <stdio.h>
2. int main() {
3. int num = 13; // binary: 00001101
4. int bit = 2; // bit to clear
5. num &= ~(1 << bit); // clear the bit
6. printf("The new value of num is %d\n", num); // binary: 00001001
7. return 0;
8. }
Output
Explanation:
In this example, the bitwise AND operator (&) is used to clear the second bit in the number num. To do this,
we first shift the value 1 left by bit positions (i.e., 2), resulting in the value 4 (binary: 00000100). After that,
we take the complement of this value using the bitwise complement operator (~), resulting in the value -
5 (binary: 11111011). Finally, we use the AND operator (&) with num to clear the second bit.
Comma Operator
The comma operator is utilized to evaluate multiple expressions and return the value of the last expression.
Syntax:
Example:
Here's an example that demonstrates how to use the comma operator to increment two variables:
1. #include <stdio.h>
2. int main() {
3. int a = 2, b = 3;
4. a++, b++;
5. printf("a = %d, b = %d\n", a, b);
6. return 0;
7. }
Output
a = 3, b = 4
Increment and Decrement Operators in C
C - Increment and Decrement Operators
The increment operator (++) increments the value of a variable by 1, while the decrement operator (--)
decrements the value.
Increment and decrement operators are frequently used in the construction of counted loops in C (with
the for loop). They also have their application in the traversal of array and pointer arithmetic.
The ++ and -- operators are unary and can be used as a prefix or posfix to a variable.
Example of Increment and Decrement Operators
The following example contains multiple statements demonstrating the use of increment and decrement
operators with different variations −
#include <stdio.h>
int main() {
int a = 5, b = 5, c = 5, d = 5;
return 0;
}
Output
When you run this code, it will produce the following output −
a=6
b=6
c=4
d=4
Types of Increment Operator
There are two types of increment operators – pre increment and post increment.
In an expression, the pre-increment operator increases the value of a variable by 1 before the use of the value
of the variable.
Syntax
++variable_name;
Example
In the following example, we are using a pre-increment operator, where the value of "x" will be increased by
1, and then the increased value will be used in the expression.
Open Compiler
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + ++x;
return 0;
}
When you run this code, it will produce the following output −
x = 11, y = 21
In an expression, the post-increment operator increases the value of a variable by 1 after the use of the value
of the variable.
Syntax
variable_name++;
Example
In the following example, we are using post-increment operator, where the value of "x" will be used in the
expression and then it will be increased by 1.
Open Compiler
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + x++;
return 0;
}
When you run this code, it will produce the following output −
x = 11, y = 20
Types of Decrement Operator
There are two types of decrement operators – pre decrement and post decrement.
Syntax
--variable_name;
Example
In the following example, we are using a pre-decrement operator, where the value of "x" will be decreased
by 1, and then the decreased value will be used in the expression.
Open Compiler
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + --x;
return 0;
}
When you run this code, it will produce the following output −
x = 9, y = 19
In an expression, the post-decrement operator decreases the value of a variable by 1 after the use of the value
of the variable.
Syntax
variable_name--;
Example
In the following example, we are using post-decrement operator, where the value of "x" will be used in the
expression and then it will be decreased by 1.
Open Compiler
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + x--;
When you run this code, it will produce the following output −
x = 9, y = 20
Expressions
C Expressions
An expression is a formula in which operands are linked to each other by the use of operators to compute a
value. An operand can be a function reference, a variable, an array element or a constant.
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of a
particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An arithmetic
expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer expression when it
contains only real operands, it is known as pure real expression, and when it contains both integral and real
operands, it is known as mixed mode expression.
The expressions are evaluated by performing one operation at a time. The precedence and associativity of
operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
o When both the operands are of type integer, then arithmetic will be performed, and the result of the
operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part is
ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of the
operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic will
be performed. In this case, the first operand is converted into a real operand, and then arithmetic is
performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is
converted into 6.0 and then arithmetic is performed to produce 3.0.
Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the zero value is
equivalent to a false and non-zero value is equivalent to true.
Relational Description
Expression
a+b = = x+y It is used to check whether the expression "a+b" is equal to the
expression "x+y".
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }
Output
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.
Logical Description
Expressions
( x > 4 ) && ( x < It is a test condition to check whether the x is greater than 4 and x is less than 6.
6) The result of the condition is true only when both the conditions are true.
x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 11.
The result of the test condition is true if either of the conditions holds true value.
! ( x > 10 ) && ( y It is a test condition used to check whether x is not greater than 10 and y is equal
==2) to 2. The result of the condition is true if both the conditions are true.
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
o A conditional operator is also known as a ternary operator.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }
Output
Type Conversion in C
Last Updated : 10 Apr, 2023
Type conversion in C is the process of converting one data type to another. The type conversion is only
performed to those data types where conversion is possible. Type conversion is performed by a compiler. In
type conversion, the destination data type can’t be smaller than the source data type. Type conversion is
done at compile time and it is also called widening conversion because the destination data type can’t be
smaller than the source data type. There are two types of Conversion:
1. Implicit Type Conversion
Implicit type conversion is also called automatic type conversion. Some of its few occurrences are
mentioned below:
Conversion Rank
Conversions in Assignment Expressions
Conversion in other Binary Expressions
Promotion
Demotion
Example of Type Implicit Conversion
Example no 1
C
Output
x = 107, z = 108.000000
2. Explicit Type Conversion
This process is also called type casting and it is user-defined. Here the user can typecast the result to make it
of a particular data type. The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.
Example no 2
C
int main()
{
double x = 1.2;
return 0;
}
Output
sum = 2
Example no 3
C
#include <stdio.h>
int main() {
float a = 1.5;
int b = (int)a;
printf("a = %f\n", a);
printf("b = %d\n", b);
return 0;
}
Output
a = 1.500000
b=1
Type safety: Type conversions can be used to ensure that data is being stored and processed in the
correct data type, avoiding potential type mismatches and type errors.
Improved code readability: By explicitly converting data between different types, you can make the
intent of your code clearer and easier to understand.
Improved performance: In some cases, type conversions can be used to optimize the performance of
your code by converting data to a more efficient data type for processing.
Improved compatibility: Type conversions can be used to convert data between different types that are
not compatible, allowing you to write code that is compatible with a wider range of APIs and libraries.
Improved data manipulation: Type conversions can be used to manipulate data in various ways, such
as converting an integer to a string, converting a string to an integer, or converting a floating-point
number to an integer.
Improved data storage: Type conversions can be used to store data in a more compact form, such as
converting a large integer value to a smaller integer type, or converting a large floating-point value to a
smaller floating-point type.
Loss of precision: Converting data from a larger data type to a smaller data type can result in loss of
precision, as some of the data may be truncated.
Overflow or underflow: Converting data from a smaller data type to a larger data type can result in
overflow or underflow if the value being converted is too large or too small for the new data type.
Unexpected behavior: Type conversions can lead to unexpected behavior, such as when converting
between signed and unsigned integer types, or when converting between floating-point and integer types.
Confusing syntax: Type conversions can have confusing syntax, particularly when using typecast
operators or type conversion functions, making the code more difficult to read and understand.
Increased complexity: Type conversions can increase the complexity of your code, making it harder to
debug and maintain.
Slower performance: Type conversions can sometimes result in slower performance, particularly when
converting data between complex data types, such as between structures and arrays.
Precedence of Operators in C
Operator Precedence and Associativity in C
The concept of operator precedence and associativity in C helps in determining which operators will be
given priority when there are multiple operators in the expression. It is very common to have multiple
operators in C language and the compiler first evaluates the operater with higher precedence. It helps to
maintain the ambiguity of the expression and helps us in avoiding unnecessary use of parenthesis.
In this article, we will discuss operator precedence, operator associativity, and precedence
table according to which the priority of the operators in expression is decided in C language.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the associativity for each of
the operators:
Operator
Precedence Description Associativity
* Dereference Operator
12 || Logical OR Left-to-Right
= Assignment
Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC
where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R = Relational, E = Equality, B
= Bitwise, L = Logical, T = Ternary, A = Assignment and C = Comma
Operator Precedence in C
Operator precedence determines which operation is performed first in an expression with more than one
operator with different precedence.
Example of Operator Precedence
Let’s try to evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table, the * has
higher precedence than + so, the first evaluation will be
10 + (20 * 30)
int main()
{
// printing the value of same expression
printf("10 + 20 * 30 = %d", 10 + 20 * 30);
return 0;
}
Output
10 + 20 * 30 = 610
As we can see, the expression is evaluated as,10 + (20 * 30) but not as (10 + 20) * 30 due to *
operator having higher precedence.
Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an expression.
Associativity can be either from Left to Right or Right to Left.
Example of Operator Associativity
Let’s evaluate the following expression,
100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation will be
decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left to Right. So,
(100 / 5) % 2
int main()
{
// Verifying the result of the same expression
printf("100 / 5 % 2 = %d", 100 / 5 % 2);
return 0;
}
Output
100 / 5 % 2 = 0
Operators Precedence and Associativity are two characteristics of operators that determine the evaluation
order of sub-expressions.
Example of Operator Precedence and Associativity
In general, the concept of precedence and associativity is applied together in expressions. So let’s consider
an expression where we have operators with various precedence and associativity
exp = 100 + 200 / 10 - 3 * 10
Here, we have four operators, in which the / and * operators have the same precedence but have higher
precedence than the + and – operators. So, according to the Left-to-Right associativity of / and *, / will be
evaluated first.
exp = 100 + (200 / 10) - 3 * 10
= 100 + 20 - 3 * 10
int main()
{
// getting the result of the same expression as the
// example
int exp = 100 + 200 / 10 - 3 * 10;
printf("100 + 200 / 10 - 3 * 10 = %d", exp);
return 0;
}
Output:
100 + 200 / 10 – 3 * 10 = 90
C Programming allows us to perform mathematical operations through the functions defined in <math.h>
header file. The <math.h> header file contains various methods for performing mathematical operations
such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header file are
given below.
No Function Description
.
1) ceil(number) rounds up the given number. It returns the integer value which is greater than or
equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less than or
equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
We can read and write a character on screen using printf() and scanf() function but this is not applicable
in all situations. In C programming language some function are available which is directly read a
character or number of character from keyboard.
getchar
This is a predefined function in C language which is available in stdio.h header file. Using this function
we can read a single character from keyboard and store in character variable. When we want to read a
number of character form keyboard the store all the data in a character array.
Example
char ch;
ch=getch();
gets
This is a predefined function in C language which is available in stdio.h header file. This function is used
to read a single string from keyboard.
Example
gets(string);
putchar
putchar function is a same as getchar but is function is used for display a character value of screen or
console. This function must be take one parameters.
Example
char ch='A';
putchar (ch);
puts
puts is same as gets function but this is used to display a string on screen or console. This function takes
single arguments.
Example
puts(str);
S
Format Specifier Type Description
NO.
5 %ld long int Used for I/O long signed integer value
C
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Declaring an int type variable
int a;
return 0;
}
Output
20
Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
Example:
C
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string
scanf():
scanf() function is used in the C program for reading or taking any value from the keyboard by the user,
these values can be of any data type like integer, float, character, string, and many more. This function is
declared in stdio.h(header file), that’s why it is also a pre-defined function. In scanf() function we use
&(address-of operator) which is used to store the variable value on the memory location of that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
Example:
C
// C program to implement
// scanf() function
#include <stdio.h>
// Driver code
int main()
{
int num1;
// Printing a message on
// the output screen
printf("Enter a integer number: ");
return 0;
}
Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56
sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this function prints the
string into a character array instead of printing it on the console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);
Example:
C
// C program to implement
// the sprintf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8;
Output
2 and 8 are even number
sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads data
from the string or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);
Example:
C
// C program to implement
// sscanf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;
Output
c = 2 and d = 8