0% found this document useful (0 votes)
7 views

Fundamentals of Computer Programming - Unit I

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Fundamentals of Computer Programming - Unit I

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

FUNDAMENTALS OF COMPUTER PROGRAMMING

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.

What is a Programming Language?


 A programming language is a computer language that is used by programmers (developers) to
communicate with computers. It is a set of instructions written in any specific language ( C, C++,
Java, Python) to perform a specific task.
 A programming language is mainly used to develop desktop applications, websites, and mobile
applications.

What is the need for programming languages?


 Several software packages are made using programming languages, together with:

 Operating structures
 Web browsers
 Mobile apps
 Desktop packages
 Video games
 General Software program
 Business-related software programs
 Embedded structures

Types of programming language

1. Low-level programming language

 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.

 Low-level language is further divided into two parts -

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.

ii. Assembly 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.

2. High-level programming language

 High-level programming language (HLL) is designed for developing user-friendly software


programs and websites. This programming language requires a compiler or interpreter to translate
the program into machine language (execute the 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.

 A high-level language is further divided into three parts -

i. Procedural Oriented 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.

 Procedural Oriented programming language is used by a software programmer to create a program


that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or
Microsoft Visual Studio.

 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.

 Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object -Oriented Programming language

 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.

 Example: C++, Java, Python, C#, etc.

iii. Natural language

 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.

3. Middle-level programming language

 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.

 Example: C, C++, language

INTRODUCTION & OVERVIEW OF C

 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.

 It can be defined by the following ways:

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.

2) C as a system programming language

 A system programming language is used to create system software. C language is a system


programming language because it can be used to do low-level programming (for example driver
and kernel). It is generally used to create hardware devices, OS, drivers, kernels, etc. For example,
Linux kernel is written in C.

 It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language

 A procedure is known as a function, method, routine, subroutine, etc. A procedural


language specifies a series of steps for the program to solve the problem.

 A procedural language

 C is a procedural language. In C, variables and function prototypes must be declared before being
used.

4) C as a structured programming language

 A structured programming language is a subset of the procedural language. Structure means to


break a program into parts or blocks so that it may be easy to understand.

 In the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.

5) C as a mid-level programming language

 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.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee


Features of 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.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different machines with some machine specific
changes. Therefore, C is a machine independent language.

3) Mid-level programming language

 Although, C is intended to do low-level programming. It is used to develop system applications


such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is
known as mid-level language.

4) Structured programming 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

 C provides a lot of inbuilt functions that make the development fast.

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.

8) Pointer ASCII value Context


32 space
 C provides the feature of
pointers. 48-57 0-9 We can directly interact with
the 65-90 A-Z memory by using the pointers.
We can use pointers for memory,
97-122 a-z structures, functions, array,
etc.

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

 C language is extensible because it can easily adopt new features.

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.

Types of Character set in C


 C programming language supports four types of characters:
 Alphabets
 Digits
 Special characters
 White space
Alphabets
The C programming language allows for all upper- and lower-case alphabets in its programs.
Lower Case alphabets: a-z (26 characters)
Upper case alphabets: A-Z (26 characters)

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:

Type of Character Description

Uppercase
A-Z (26 characters)
Alphabets

Lowercase Alphabets a-z (26 characters)

Digits 0-9 (10 characters)

Blank Spaces, Tab, Carriage Return, New Line, horizontal tab, vertical tab,
White spaces
null

Special Characters @!$#^*%&()[]{}<>+=_–|/\;:‘“,.?

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”;

5. C Token – Special Symbols


 The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references. These indicate single
and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code containing
more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating parameters in function
calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
 Assignment operator(=): It is used to assign values and for logical operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler
to transform your program before actual compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Bitwise One’s Complement Operator.

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.

Copy Codeint const SIDE = 10;


or
Copy Codeconst int SIDE = 10;

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

It refers to a sequence of digits. Integers are of three types viz:

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer

Example:

Copy Code15, -265, 0, 99818, +25, 045, 0X6


Real constant

The numbers containing fractional parts like 99.25 are called real or floating points constant.

Single Character Constants

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:

Copy Code'X', '5', ';'


String Constants

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:

Copy Code"Hello!", "2015", "2+1"


Backslash character constants

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:

\t is used to give a tab \n is used to give a new line

Constants Meaning

\a beep sound

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\' single quote

\" double quote

\\ 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.

User Defined Data


The user-defined data types are defined by the user himself.
Types

The data types that are derived from the primitive or built-in datatypes are referred
Derived Types
to as Derived Data Types.

Basic 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.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte


Int:

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.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

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.

Derived Data Type

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.

1. int numbers[5]; // Declares an integer array with a size of 5 elements


2. numbers[0] = 10;
3. numbers[1] = 20;
4. numbers[2] = 30;
5. numbers[3] = 40;
6. numbers[4] = 50;

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.

1. int num = 42; // An integer variable


2. int *ptr; // Declares a pointer to an integer
3. ptr = # // Assigns the address of 'num' to the pointer
4. // Accessing the value of 'num' using the pointer
5. printf("Value of num: %d\n", *ptr);

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.

A declaration and use of a structure is demonstrated here:

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.

Here is an example of a union being declared and used:

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.

Here is an example of how to define and use an enumeration in C:

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.

Function Return Type:

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:

1. void printHello() { printf("Hello, world!\n"); }

Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.

Example:

1. void processInput(void) { /* Function logic */ }

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:

The syntax for defining a variable in C is as follows:

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.

For example, to declare the integer variable age:

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;

Here, the variable count is declared an integer and initialized with 0.

Syntax:

Let us see the syntax to declare a variable:

1. type variable_list;

An example of declaring the variable is given below:

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.

We may also provide values while defining variables, as shown below:

1. int a=20,b=30;//declaring 2 variable of integer type


2. float f=20.9;
3. char c='A';

Rules for defining variables

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.

Some compilers may impose a maximum length for variable names.

o Spaces and Special Characters:

Variable names cannot contain spaces or special characters (such as !, @, #, $, %, ^, &, *, (, ), -, +, =, [, ], {,


}, |, \, /, <, >,., ?;, ', or ").

Underscores are the only allowed special characters in variable names.

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.

Valid examples of variable names:

1. int age;
2. float salary;
3. char _status;
4. double average_score;
5. int studentCount;

Invalid examples of variable names:

1. int 1stNumber; // Starts with a digit


2. float my-salary; // Contains a hyphen (-)
3. char int; // Same as a C keyword
4. int double; // Same as a C keyword
5. float my$var; // Contains an unsupported special character

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

The three components of declaring a variable

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.

The general syntax for variable declaration is

1. data_type variable_name;

Example of variable declaration:

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.

Example of variable definition:

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.

Example of variable initialization:

1. int age = 25;


2. float salary = 2500.5;
3. char initial = 'J';

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).

ASSIGNING VALUES TO VARIABLES


How to assign values to variables in C?

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;

Let us see how to assign values to a variable and print it

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:

Syntax for defining a symbolic constant in C:

#define MAX_V 100

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.

We may specify non-numerical values like strings using symbolic constants.

For example:

#define error "INVALID"


In this example, the text "INVALID" is declared as the symbolic constant "error". It can be helpful for
defining error messages or other strings that are frequently used throughout a program.

Additionally, macros, which are essentially functions that are expanded at compile time, can be defined
using symbolic constants.

For example:

#define CUBE(x) ((x)*(x)*(x))

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:

It has the following syntax:


1. result = operand1 + operand2;

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:

It has the following syntax:

1. result = operand1 - operand2;

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:

It has the following syntax:


1. result = operand1 * operand2;

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:

It has the following syntax:

1. result = operand1 / operand2;

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:

It has the following syntax:

1. result = operand1 % operand2;

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:

It has the following syntax:

1. result = operand1 == operand2;

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:

It has the following syntax:


1. result = operand1 != operand2;

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:

It has the following syntax:

1. result = operand1 > operand2;

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:

It has the following syntax:

1. result = operand1 < operand2;

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:

It has the following syntax:

1. result = operand1 >= operand2;

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:

It has the following syntax:

1. result = operand1 <= operand2;

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:

It has the following syntax:


1. result = operand1 << operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary


2. int result = a << 2;

Output:

result = 20 // 0001 0100 in binary

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:

It has the following syntax:

1. result = operand1 >> operand2;

Example:

1. unsigned int a = 20; // 0001 0100 in binary


2. int result = a >> 2;

Output:

result = 5 // 0000 0101 in binary


Logical Operators:

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:

It has the following syntax:

1. result = operand1 && operand2;

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:

It has the following syntax:

1. result = operand1 || operand2;


Example:
1. int a = 5;
2. int b = 3;
3. int result = (a > 3) || (b > 5);

Output:

result = 1 (true)

Logical NOT Operator (!): The logical NOT operator negates the value of the operand.

Syntax:

It has the following 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:

It has the following syntax:

1. result = operand1 & operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary


2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a & b;

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:

It has the following syntax:

1. result = operand1 | operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary


2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a | b;

Output:

result = 7 // 0000 0111 in binary

Bitwise XOR Operator (^): The bitwise XOR operator performs a bitwise exclusive OR operation on the
corresponding bits of the operands.

Syntax:

It has the following syntax:

1. result = operand1 ^ operand2;

Example:

1. unsigned int a = 5; // 0000 0101 in binary


2. unsigned int b = 3; // 0000 0011 in binary
3. int result = a ^ b;

Output:

result = 6 // 0000 0110 in binary

Bitwise NOT Operator (~): The bitwise NOT operator flips each bit of the operand.

Syntax:

It has the following syntax:

1. result = ~operand;

Example:

1. unsigned int a = 5; // 0000 0101 in binary


2. int result = ~a;

Output:

result = -6 // 1111 1001 in binary (assuming 8-bit representation)

Ternary or Conditional Operator: The ternary or conditional operator allows you to assign a value
based on a condition.

Syntax:

It has the following syntax:

1. result = condition ? value1 : value2;

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:

It has the following syntax:

1. variable = value;

Example:

1. int a;
2. a = 5;

Output:

No output. The value 5 is assigned to variable 'a'.


Special operator in C

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:

The syntax of the ternary operator is as follows:

1. condition ?value_if_true : value_if_false;

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

The new value of num is 9

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:

The syntax of the comma operator is as follows:

1. expression1, expression2, ..., expressionN;

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;

a++; // postfix increment


++b; // prefix increment
c--; // postfix decrement
--d; // prefix decrement

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


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

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.

Pre (Prefix) Increment Operator

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;

printf("x = %d, y = %d\n", x, y);

return 0;
}

When you run this code, it will produce the following output −

x = 11, y = 21

Post (Postfix) Increment Operator

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++;

printf("x = %d, y = %d\n", x, y);

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.

Pre (Prefix) decrement Operator


In an expression, the pre-decrement operator decreases 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-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;

printf("x = %d, y = %d\n", x, y);

return 0;
}

When you run this code, it will produce the following output −

x = 9, y = 19

Post (Postfix) Decrement Operator

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--;

printf("x = %d, y = %d\n", x, y);


return 0;
}

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.

Let's see an example:

1. a-b;

In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in C:

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.

Evaluation of Arithmetic Expressions

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.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.


1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

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

x%2 = = 0 This condition is used to check whether the x is an even number


or not. The relational expression results in value 1 if x is an even
number otherwise results in value 0.

a!=b It is used to check whether a is not equal to b. This relational


expression results in 1 if a is not equal to b otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the
expression "x+y".

a>=9 It is used to check whether the value of a is greater than or equal


to 9.

Let's see a simple example:

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.

Let's see some example of the logical expressions.

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.

Let's see a simple program of "&&" operator.

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

Let's see a simple example of "| |" operator

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.

The Syntax of Conditional operator

Suppose exp1, exp2 and exp3 are three expressions.

exp1 ? exp2 : exp3


The above expression is a conditional expression which is evaluated on the basis of the value of the exp1
expression. If the condition of the expression exp1 holds true, then the final conditional expression is
represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

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

Also known as ‘automatic type conversion’.


A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present. In such conditions type
conversion (type promotion) takes place to avoid loss of data.
C. All the data types of the variables are upgraded to the data type of the variable with the largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
D. It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long is implicitly converted to float).

Occurrences of Implicit Type Conversion in C

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

// An example of implicit conversion


#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}

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

// C program to demonstrate explicit type casting


#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;
printf("sum = %d", sum);

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

Advantages of Type Conversion

 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.

Disadvantages of type conversions in C programming:

 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

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

2 ++ / — Prefix increment, decrement Right-to-Left

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

(type) Cast Operator

* Dereference Operator

& Addressof Operator


Operator
Precedence Description Associativity

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
> , >= Relational greater than, greater than or equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

^= , |= Bitwise exclusive, inclusive OR assignment

<<=, >>= Bitwise shift left, right assignment


Operator
Precedence Description Associativity

15 , comma (expression separator) Left-to-Right

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)

After evaluating the higher precedence operator, the expression is


10 + 600

Now, the + operator will be evaluated.


610

We can verify this using the following C program C


// C Program to illustrate operator precedence
#include <stdio.h>

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

After evaluation, the expression will be


20 % 2

Now, the % operator will be evaluated.


0

We can verify the above using the following C program:


C
// C Program to illustrate operator Associativity
#include <stdio.h>

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

After that, * will be evaluated,


exp = 100 + 20 - (3 * 10)
= 100 + 20 - 30

Now, between + and –, + will be evaluated due to Left-to-Right associativity.


exp = (100 + 20) - 30
= 120 - 30

At last, – will be evaluated.


exp = 120 - 30
= 90

Again, we can verify this using the following C program.


C
// C Program to illustrate the precedence and associativity
// of the operators in an expression
#include <stdio.h>

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

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] ->. ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


MATHEMATICAL FUNCTIONS
C Math

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.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of 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

Reading and Writing a Character

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();

Note: getchar function has no any parameters.

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);

putchar is equivalent to printf("%c",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);

Formatted I/O Functions


Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the
user. These types of I/O functions can help to display the output to the user in different formats using the
format specifiers. These I/O supports all data types like int, float, char, and many more.
Why they are called formatted I/O?
These functions are called formatted I/O functions because we can use format specifiers in these functions
and hence, we can format these functions according to our needs.
List of some format specifiers-

S
Format Specifier Type Description
NO.

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value


7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-


1. printf()
2. scanf()
3. sprintf()
4. sscanf()
printf():
printf() function is used in a C program to display any value like float, integer, character, string, etc on the
console screen. It is a pre-defined function that is already declared in the stdio.h(header file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
Example:

 C

// C program to implement
// printf() function
#include <stdio.h>

// Driver code
int main()
{
// Declaring an int type variable
int a;

// Assigning a value in a variable


a = 20;

// Printing the value of a variable


printf("%d", 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: ");

// Taking an integer value


// from keyboard
scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);

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;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);

// Displays the string


printf("%s", str);
return 0;
}

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;

// The string "a = 2 and b = 8"


// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);

// The value of a and b is now in


// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);

// Displays the value of c and d


printf("c = %d and d = %d", c, d);
return 0;
}

Output
c = 2 and d = 8

You might also like