[go: up one dir, main page]

0% found this document useful (0 votes)
4 views179 pages

Module 1.Pptx

The document provides an overview of C programming, including its history, components of a computer system, and the structure of a C program. It discusses the evolution of C, its standardization, and compares it with other programming languages, while detailing the roles of the CPU, input/output units, and language processors like compilers and interpreters. Additionally, it covers basic input/output operations in C, format specifiers, and the execution steps of a C program.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views179 pages

Module 1.Pptx

The document provides an overview of C programming, including its history, components of a computer system, and the structure of a C program. It discusses the evolution of C, its standardization, and compares it with other programming languages, while detailing the roles of the CPU, input/output units, and language processors like compilers and interpreters. Additionally, it covers basic input/output operations in C, format specifiers, and the execution steps of a C program.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

‘C’ Programming

By Asst. Prof. Sudeshna Baliarsingh


Information & Technology Dept.
KJSIT, Mumbai
Module 1
1.Introduction, Fundamentals of C Programming

2.Introduction to components of a Computer


System.

3.Introduction to structure programming approach

4.Introduction to Algorithm and Flowchart


C Orientation
• Created in 1972 to write operating systems (Unix
in particular)
– By Dennis Ritchie
– Bell Labs
• Evolved from B
• Can be portable to other hardware (with careful
design – use Plauger’s The Standard C Library
book)
• Built for performance and memory management –
operating systems, embedded systems, real-time
systems, communication systems
But nowadays used for a wide variety of applications

- industry-standard language

Note: High-level language => “resembles” everyday


English. Instructions are written in a condensed
(pseudo) form of English

5
C Standardization
• 1989 ANSI and ISO -> Standard C
• 1999 C99
• 2011 C11
Later Languages
• 1979 C++ by Bjarn Stroustrup also at Bell
– Object orientation
• 1991 Java by Sun
– Partial compile to java bytecode: virtual
machine code
– Write once, run anywhere
– Memory manager – garbage collection
– Many JVMs written in C / C++
Introduction to Components of a computer System.
A computer is an electronic device that accepts data,
performs operations, displays results, and stores the
data or results as needed.

It is a combination of hardware and software resources


that integrate together and provides various
functionalities to the user.

Hardware is the physical components of a computer


like a processor, memory devices, monitor, keyboard,
etc.,

while software is a set of programs or instructions that


are required by the hardware resources to function
properly.
Components of a Computer
There are basically three important components of a computer:
Input Unit
Central Processing Unit(CPU)
Output Unit
1. Input Unit:
The input unit consists of input devices that are attached to the
computer. These devices take input and convert it into binary
language that the computer understands. Some of the common
input devices are keyboard, mouse, joystick, scanner etc.
The Input Unit is formed by attaching one or more input devices
to a computer.
A user input data and instructions through input devices such as
a keyboard, mouse, etc.
The input unit is used to provide data to the processor for
further processing.
2. Central Processing Unit:
Once the information is entered into the computer by the input
device, the processor processes it.

The CPU is called the brain of the computer because it is the


control centre of the computer. It first fetches instructions from
memory and then interprets them so as to know what is to be
done.

If required, data is fetched from memory or input device.


Thereafter CPU executes or performs the required computation,
and then either stores the output or displays it on the output
device.
The CPU has three main components, which are responsible for
different functions: Arithmetic Logic Unit (ALU), Control Unit
(CU) and Memory registers
A. Arithmetic and Logic Unit (ALU): The ALU, as its
name suggests performs mathematical calculations
and takes logical decisions. Arithmetic calculations
include addition, subtraction, multiplication and
division. Logical decisions involve the comparison of
two data items to see which one is larger or smaller or
equal.
Arithmetic Logical Unit is the main component of the
CPU

It is the fundamental building block of the CPU.

Arithmetic and Logical Unit is a digital circuit that is


used to perform arithmetic and logical operations.
B. Control Unit: The Control unit coordinates and controls the
data flow in and out of the CPU, and also controls all the
operations of ALU, memory registers and also input/output
units. It is also responsible for carrying out all the instructions
stored in the program. It decodes the fetched instruction,
interprets it and sends control signals to input/output devices
until the required operation is done properly by ALU and
memory.
The Control Unit is a component of the central processing unit of
a computer that directs the operation of the processor.
It instructs the computer’s memory, arithmetic and logic unit,
and input and output devices on how to respond to the
processor’s instructions.
In order to execute the instructions, the components of a
computer receive signals from the control unit.
It is also called the central nervous system or brain of the
computer.
C. Memory Registers: A register is a temporary unit of memory
in the CPU. These are used to store the data, which is directly
used by the processor.

Registers can be of different sizes(16 bit, 32 bit, 64 bit and so


on) and each register inside the CPU has a specific function, like
storing data, storing an instruction, storing address of a location
in memory etc.

The user registers can be used by an assembly language


programmer for storing operands, intermediate results etc.
Accumulator (ACC) is the main register in the ALU and contains
one of the operands of an operation to be performed in the ALU.
3. Output Unit :
The output unit consists of output devices that are attached to
the computer. It converts the binary data coming from the CPU
to human understandable form. The common output devices
are monitor, printer, plotter, etc.

The output unit displays or prints the processed data in a


user-friendly format.

The output unit is formed by attaching the output devices of a


computer.

The output unit accepts the information from the CPU and
displays it in a user-readable form.
Low Level vs High level Languages
Language Processors: Assembler, Compiler and
Interpreter
1. Compiler

The language processor that reads the complete sourc


program written in high-level language as a whole in one g
and translates it into an equivalent program in machin
language is called a Compiler. Example: C, C++, C#.

In a compiler, the source code is translated to object cod


successfully if it is free of errors. The compiler specifies th
errors at the end of the compilation with line numbers whe
there are any errors in the source code. The errors must b
removed before the compiler can successfully recompile th
source code again the object program can be execute
number of times without translating it again.
2. Assembler
The Assembler is used to translate the program written in Assemb
language into machine code. The source program is an input of a
assembler that contains assembly language instructions. The outp
generated by the assembler is the object code or machine cod
understandable by the computer. Assembler is basically the 1
interface that is able to communicate humans with the machine. W
need an assembler to fill the gap between human and machine
that they can communicate with each other. code written
assembly language is some sort of mnemonics(instructions) li
ADD, MUL, MUX, SUB, DIV, MOV and so on. and the assembler
basically able to convert these mnemonics in binary code. Her
these mnemonics also depend upon the architecture of th
machine.
For example, the architecture of intel 8085 and intel 8086 a
different.
3. Interpreter
The interpreter moves on to the next line for execution
only after the removal of the error. An Interpreter
directly executes instructions written in a programming
or scripting language without previously converting
them to an object code or machine code. An
interpreter translates one line at a time and then
executes it.

Example: Perl, Python and Matlab.


3. Interpreter
The interpreter moves on to the next line for execution
only after the removal of the error. An Interpreter
directly executes instructions written in a programming
or scripting language without previously converting
them to an object code or machine code. An
interpreter translates one line at a time and then
executes it.
Example: Perl, Python and Matlab.
General Aspect of ‘C’
C was originally developed in the 1970s, by Dennis Ritchie at
Bell Telephone Laboratories, Inc.
C is a High level , general –purpose structured programming
language.
Instructions of C consists of terms that are very closely same to
algebraic expressions, consisting of certain English keywords
such as if, else, for ,do and while
C contains certain additional features that allows it to be used at
a lower level , acting as bridge between machine language and
the high level languages.
This allows C to be used for system programming as well as for
applications programming
Features of C Language
Structure of program
1. Documentation section:
Comment Section: Author Date time ,brief description of that prog.
Single line comment : //—----------
Double line Comment: /*------------*/
2. Link Section:Inclusion of Header files
The first and foremost component is the inclusion of the Header files in a C
program. A header file is a file with extension .h which contains C function
declarations and macro definitions to be shared between several source
files. All lines that start with # are processed by a preprocessor which is a
program invoked by the compiler. The preprocessor copies the
preprocessed code of stdio.h to our file. The .h files are called header files
in C.
Some of the C Header files:
stddef.h – Defines several useful types and macros.
stdint.h – Defines exact width integer types.
stdio.h – Defines core input and output functions
stdlib.h – Defines numeric conversion functions, pseudo-random number
generator, and memory allocation
string.h – Defines string handling functions
3. Definition section : Defines all symbolic constants i.e.
#define a 20
#define max 100

4. Global Declaration Section: Global and Local Variables.


#include <stdio.h>
void main ( ) #include <conio.h>
{ int a;
int a void main ();
}

5. Main Function: It is the entry point of a C program and the execution


typically begins with the first line of the main(). The empty brackets indicate
that the main doesn’t take any parameter. It's the compulsory one.
A pair of curly brackets define the body of a function. All functions must
start and end with curly brackets.Everything inside this function in a C
program will be executed, hence the actual logic or the code is always
written inside the main() function.
#include <stdio.h>
#include <conio.h>
int a;
void sum ( );
void subs ( );
void main ( )
{
Declaration Section- Where variables are declared
(optional)
Executable Section- Logic
}

6. Subprogram Section : Here all the user defined functions


will be used generally written after main (). this is optional .
A First Program
//Sudeshna Baliarsingh Documentation
/* my first
program */
//11.01.2024
Header Files

#include <stdio.h> Main Func.


#include <conio.h>

statements
void main()
{
printf("This is my first C program.");
getch();
}

open and close braces mark


the beginning and end
A First Program – What Does It Do?
printf("This is my first C program.");

Prints the message


This is my first C program.
2nd Program Documentation
//Sudeshna Baliarsingh Header files
/* program for
example*/ Definition sec.
//11.01.2024

#include <stdio.h> Global dec. Func.


#include <conio.h>
#define mnx 100 datatype
int a=50;
Declaration of variable
void display(); user defined is “a”
void main() section.

{
Main fun.
printf("Hello"); Calling of user
display (); defined section

} Sub program
void display() Definition of sec
user defined
{ section
printf(“Hi am Sudeshna ”);
Steps in the Execution of the C Program
Source code
First c
Preprocessor
First .i
Compile

Syntax
Error
Yes

First .asm NO
Assembler
First .obj
Link with system Libraries
First .exe
Input data Execute
Logic
and
data
Error No O/p
steps of execution
of the C program
into the C compiler
Syntax of the steps of execution of C program.
Loader
Compiler
Basics of a Typical C Program Development Environment
Program is created in
the editor and stored
Editor Disk on disk.
Phases of C Programs: Preprocessor
Preprocessor Disk program
1. Edit processes the code.
Compiler creates
2. Preprocess Disk object code and
stores it on disk.
3. Compile
Linker Disk Linker links the object
4. Link code with the libraries
Primary
5. Load Memory

Loader puts program


6. Execute in memory.
Disk ..
..
..

Primary Memory CPU takes each


CPU instruction and
executes it, possibly
storing new data
values as the program
..
.. executes.
..
33
Basic Input and Output in C
C language has standard libraries that allow input and output in a
program. The stdio.h or standard input output library in C that has
methods for input and output.

printf()
The printf() method, in C, prints the value passed as the parameter
to it, on the console screen.

Syntax: printf(“%X”, variableOfXType);

where %X is the format specifier in C.


It is a way to tell the compiler what type of data is in a variable
and & is the address operator in C, which tells the compiler to
change the real value of this variable, stored at this address in the
memory.
Basic Input and Output in C
scanf()
The scanf() method, in C, reads the value from the console
as per the type specified.

Syntax: scanf(“%X”, &variableOfXType);

where %X is the format specifier in C.

It is a way to tell the compiler what type of data is in a


variable and & is the address operator in C, which tells the
compiler to change the real value of this variable, stored at
this address in the memory.
Example
Output:
Enter the integer: 10
Entered integer is: 10

Enter the float: 2.5


Entered float is: 2.500000

Enter the Character: A


Entered Character is: A
Format Specifiers in C
The format specifier in C is used to tell the compiler about
the type of data to be printed or scanned in input and
output operations. They always start with a % symbol and
are used in the formatted string in functions like printf(),
scanf().
The %u is the format specifier for the Syntax:
unsigned integer data type. If we specify printf("%u...", ...);
a negative integer value to the %u, it
scanf("%u...", ...);
converts the integer to its first complement.

Input:

Enter an integer: 25

Output:

Entered unsigned integer: 25


Printing -10 using %u:
4294967286
The %f is the floating point format specifier in C language
that can be used inside the formatted string for input and output
of float data type. Apart from %f, we can use %e or %E format
specifiers to print the floating point value in the
exponential form.

Syntax:
printf("%f...", ...);
scanf("%e...", ...);
printf("%E...", ...);
Output
Using %f: 12.670000
Using %e: 1.267000e+01
Using %E, 1.267000E+01
Changing the width (continued)
Number Formatting Print as:
23 %1d 23
23 %2d 23
23 %6d ….23
23 %8d ……23
11023 %4d 11023
11023 %6d .11023
-11023 %6d -11023
-11023 %10d ….-11023
Changing The Precision
Number Formatting Prints as:
2.718281828 %8.5f `2.71828
2.718281828 %8.3f ```2.718
2.718281828 %8.2f ````2.72
2.718281828 %8.0f ````````3
2.718281828 %13.11f 2.71828182800
2.718281828 %13.12f 2.718281828000
FLOW CHARTS : SYMBOLIC
REPRESENTATION
FLOW-CHART
ADVANTAGES
• Communication
• Effective analysis
• Proper documentation
• Efficient coding
• Proper debugging
• Efficient program maintenance
Example 1:
ALGORITHM :
Definition of Algorithm
The word Algorithm means ” A set of finite
rules or instructions to be followed in
calculations or other problem-solving
operations ”

Or

” A procedure for solving a mathematical


problem in a finite number of steps that
frequently involves recursive operations”.
USE of ALGORITHM :
Use of the Algorithms:
Algorithms play a crucial role in various fields and have many applications.
Some of the key areas where algorithms are used include:Computer
Science: Algorithms form the basis of computer programming and are
used to solve problems ranging from simple sorting and searching to
complex tasks such as artificial intelligence and machine learning.
Mathematics: Algorithms are used to solve mathematical problems, such as
finding the optimal solution to a system of linear equations or finding the
shortest path in a graph.
Operations Research: Algorithms are used to optimize and make decisions
in fields such as transportation, logistics, and resource allocation.
Artificial Intelligence: Algorithms are the foundation of artificial intelligence
and machine learning, and are used to develop intelligent systems that
can perform tasks such as image recognition, natural language
processing, and decision-making.
Data Science: Algorithms are used to analyze, process, and extract insights
from large amounts of data in fields such as marketing, finance, and
healthcare.
USE of ALGORITHM :
What is the need for algorithms?
1. Algorithms are necessary for solving complex problems efficiently and
effectively.
2. They help to automate processes and make them more reliable, faster,
and easier to perform.
3. Algorithms also enable computers to perform tasks that would be
difficult or impossible for humans to do manually.
4. They are used in various fields such as mathematics, computer science,
engineering, finance, and many others to optimize processes, analyze
data, make predictions, and provide solutions to problems.
What are the Characteristics of an Algorithm?
● Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be
clear in all aspects and must lead to only one meaning.
● Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may
or may not take input.
● Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it
should be well-defined as well. It should produce at least 1 output.
● Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
● Feasible: The algorithm must be simple, generic, and practical, such that it can be executed
with the available resources. It must not contain some future technology or anything.
● Language Independent: The Algorithm designed must be language-independent, i.e. it must
be just plain instructions that can be implemented in any language, and yet the output will be
the same, as expected.
● Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must
accept zero or more inputs.
● Output: fundamental operator must accept zero or more inputs.
● Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to
interpret. By referring to any of the instructions in an algorithm one can clearly understand
what is to be done. Every fundamental operator in instruction must be defined without any
ambiguity.
● Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every
instruction which contains a fundamental operator must be terminated within a finite amount of
time. Infinite loops or recursive functions without base conditions do not possess finiteness.
● Effectiveness: An algorithm must be developed by using very basic, simple, and feasible
operations so that one can trace it out by using just paper and pencil.
● Properties of Algorithm:
Properties of Algorithm:
● It should terminate after a finite time.

● It should produce at least one output.

● It should take zero or more input.

● It should be deterministic means giving the same


output for the same input case.

● Every step in the algorithm must be effective i.e.


every step should do some work.
ALGORITHM : DESIGNING STATEGY
1. Identify the outputs needed.
2. Identify the input variables available.
3. Identify the major decisions and
conditions.
4. Identify the processes required to
transform inputs into required outputs.
5. Identify the environment available.
The Character set of ‘C’
C language consist of some characters set, numbers and
some special symbols. The character set of C consist of all
the alphabets of English language.

C consist of
Alphabets a to z, A to Z
Numeric 0,1 to 9
Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more

The words formed from the character set are building


blocks of C and are sometimes known as tokens. These
tokens represent the individual entity of language.
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:
The following different types of token are used in C

1. Keywords
2. Identifiers
3. Variables
4. Constants
5. Strings
6. Special Symbols
7. Operators
Constants
•As the name suggests, a constant in C is a variable that
cannot be modified once it is declared in the program.
We can not make any change in the value of the
constant variables after they are defined.

Syntax to Define Constant


const data_type var_name = value;
Constants
Integer constants
•A integer constant is a numeric constant (associated with
number) without any fractional or exponential part.
There are three types of integer constants in C
programming:

•decimal constant(base 10): 0-9


•octal constant(base 8): 0-7
•hexadecimal constant(base 16):0-15(0-9,A-F)
Constants
Floating-point constants
•A floating point constant is a numeric constant
that has either a fractional form or an exponent
form. For example: 2.0,0.0000234,-0.22E-5

Character constants
•A character constant is a constant which uses
single quotation around characters. For example:
'a', 'l', 'm', 'F'

String constants
•String constants are the constants which are
enclosed in a pair of double-quote marks. For
example: "good" ,"x","Earth is round\n"
Example of Constants in C
Output

Printing value of Integer Constant: 25


Printing value of Character Constant: A
Printing value of Float Constant: 15.660000

One thing to note here is that we have to initialize the


constant variables at declaration. Otherwise, the
variable will store some garbage value and we won’t
be able to change it.
Question 1
Output

In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
Defining Constant using #define Preprocessor
We can also define a constant in C using #define preprocessor. The
constants defined using #define are macros that behave like a
constant.

These constants are not handled by the compiler, they are handled
by the preprocessor and are replaced by their value before
compilation.

SYNTAX:

#define const_name value


Example of Constant Macro

Output
The value of pi: 3.14

Note: This method for defining constant is not preferred as it may introduce bugs and make the
code difficult to maintain.
Variables
• A variable is nothing but 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.

• The name of a variable can be composed of letters, digits, and the


underscore character. It must begin with either a letter or an
underscore. Upper and lowercase letters are distinct because C is
case-sensitive. There are following basic variable types −
Variables
In C, there are different types of variables (defined with
different keywords), for example:

1. int - stores integers (whole numbers), without decimals,


such as 123 or -123
2. float - stores floating point numbers, with decimals, such
as 19.99 or -19.99
3. char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
C Variable Syntax
data_type variable_name = value; // defining
single variable
or
data_type variable_name1, variable_name2; //
defining multiple variable
Here
data_type: Type of data that a variable can store.
variable_name: Name of the variable given by the user.
value: value assigned to the variable by the user.
int a; // variable definition
a = 10; // initialization
or
int a = 10; // variable declaration
and definition
Rules for Naming Variables in C
You can assign any name to the variable as long as it
follows the following rules:

1. A variable name must only contain alphabets, digits,


and underscore.
2. A variable name must start with an alphabet or an
underscore only. It cannot start with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or
keyword.
HW Examples:
Simpleintrest
age
int_type
num12
_b
SUM
Rohit’s
1case
rosy garden
Example:
Output

Defined_var: 0
Value of defined_var after initialization: 12
Value of ini_var: 25
Keywords
• Keywords are predefined or reserved words that have special meanings
to the compiler.

• These are part of the syntax and cannot be used as identifiers in the
program.

• Keywords are nothing but system defined identifiers.

• Keywords are reserved words of the language.

• They have specific meaning in the language and cannot be used by the
programmer as variable or constant names

• C is case sensitive, it means these must be used as it is.

• 32 Keywords in C Programming
Keywords
Example:
char
char keyword in C is used to declare a character variable in the C
programming language.

char x = 'D';

Output
a
Example:
double and float
The doubles and floats are data types used to declare decimal type
variables. They are similar, but doubles have 15 decimal digits,
and floats only have 7.

Output
Float value:
0.300000
Double
value:
10.670000000
000000
Identifiers
• Identifiers are unique names that are assigned to
variables, structs, functions, and other entities.
They are used to uniquely identify the entity within
the program.
• Identifiers is nothing but a name given to these
elements

•An identifier is a word used by a programmer to


name a variable , function, or label.

•Identifiers consist of letters and digits if any


order,except that the first character must be letter.

•Both Upper and lowercase letters can be used


Rules to Name an Identifier in C
A programmer has to follow certain rules while naming
variables. For the valid identifier, we must follow the given
below set of rules.

An identifier can include letters (a-z or A-Z), and digits (0-9).


• An identifier cannot include special characters except the
‘_’ underscore.
• Spaces are not allowed while naming an identifier.
• An identifier can only begin with an underscore or
letters.
• We cannot name identifiers the same as keywords
because they are reserved words to perform a specific
task. For example, printf, scanf, int, char, struct, etc. If we
use a keyword’s name as an identifier the compiler will
throw an error.
• The identifier must be unique in its namespace.
• C language is case-sensitive so, ‘name’ and ‘NAME’ are
different identifiers.
Valid and Invalid Identifiers in C
Example

Let’s understand it with an example.

float area;

Here ‘float’ is a ‘keyword’, and ‘area’ is an ‘identifier’. The


identifier ‘area’ is a name given to a ‘variable’ which will
store a float value. Now if ‘area’ weren’t a variable, but a
function, then

float area()

Here, ‘area’ is still an identifier, but this time, the identifier


‘area’ is a name given to a ‘function’.
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:

1. Brackets[]: Opening and closing brackets are used as array element


references. These indicate single and multidimensional subscripts.

2. Parentheses(): These special symbols are used to indicate function calls


and function parameters.

3. Braces{}: These opening and ending curly braces mark the start and end
of a block of code containing more than one executable statement.

4. Comma (, ): It is used to separate more than one statement like for


separating parameters in function calls.

5. Colon(:): It is an operator that essentially invokes something called an


initialization list.
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:

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

2. Asterisk (*): It is used to create a pointer variable and for the


multiplication of variables.

3. Assignment operator(=): It is used to assign values and for logical


operation validation

4. Pre-processor (#): The preprocessor is a macro processor that is used


automatically by the compiler to transform your program before actual
compilation.
5. Period (.): Used to access members of a structure or union.
6. Tilde(~): Used as a destructor to free some space from memory.
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.
Data Types in C
Different data types also have different ranges up to which
they can store numbers. These ranges may vary from
compiler to compiler. There is a list along with the memory
requirement and format specifiers on the 32-bit GCC
compiler.
Integer Data Type
The integer datatype in C is used to store the integer
numbers (any number including positive, negative and
zero without decimal part).

Octal values, hexadecimal values, and decimal values


can be stored in int data type in C.

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


Size: 4 bytes
Format Specifier: %d

Syntax of Integer:
We use int keyword to declare the integer variable:

int var_name;
NOTE:

The integer data type can also be used as

1. unsigned int: Unsigned int data type in C is used to store the


data values from zero to positive numbers but it can’t store
negative values like signed int.

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

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

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


unsigned int with int.
Output
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Character Data Type
Character data type allows its variable to store only a single
character.
The size of the character is 1 byte.
It is the most basic data type in C. It stores a single character
and requires a single byte of memory in almost all
compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of
character type:
char var_name;
Output
Value of a: a
Value of a after increment is: b
Value of c: c
Float Data Type
In C programming float data type is used to store floating-point
values.
Float in C is used to store decimal and exponential values. It is
used to store decimal numbers (numbers with floating point
values) with single precision.

Range: 1.2E-38 to 3.4E+38


Size: 4 bytes
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating
point:
float var_name;
Output
9.000000
2.500000
0.000200
Double Data Type
A Double data type in C is used to store decimal numbers (numbers
with floating point values) with double precision.
The double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points.
Since double has more precision as compared to that float then it is
much more obvious hat it occupies twice the memory occupied by
the floating-point type. It can easily accommodate about 16 to 17
digits after or before a decimal point.

Range: 1.7E-308 to 1.7E+308


Size: 8 bytes
Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using
the double keyword:
double var_name;
Output
123123123.00
0000
12.293123
2312312312.1
23123
Escape Sequences
• Sometimes, it is necessary to use characters which cannot
be typed or has special meaning in C programming.

• The escape sequence in C is the characters or the sequence


of characters that can be used inside the string literal.

• The purpose of the escape sequence is to represent the


characters that cannot be used normally using the
keyboard.

• For example: newline(enter), tab, question mark etc. In


order to use these characters, escape sequence is used.

• For example: \n is used for newline. The backslash ( \ ) causes


"escape" from the normal way the characters are interpreted
by the compiler.
Operators in C
An operator is a symbol which operates on a value or a
variable.

For example: + is an operator to perform addition.

An operator in C can be defined as the symbol that helps


us to perform some specific mathematical, relational,
bitwise, conditional, or logical computations on values
and variables.

The values and variables used with operators are called


operands.

So we can say that the operators are the symbols that


perform operations on operands.
C programming has wide range of operators to perform
various operations. For better understanding of operators,
these operators can be classified as:

A unary operator in C is an operator that operates on a single


operand to produce a new value.

Binary operators operate on two operands. Some of the binary


operators in C

The ternary operator takes three arguments: a conditional


expression, a result if the condition is True, and a result if the
condition is False.
Arithmetic Operator
Arithmetic Operator
Example 1 Arithmetic Operator
Output
a + b = 30
a - b = 20
a * b = 125
a / b = 5
a % b = 0
+a = 25
-a = -25
a++ = 25
a-- = 26
Example 2 Arithmetic Operator
Example 3 Arithmetic Operator
Increment and Decrement Operators
1. C programming has two operators increment ++ and
decrement -- to change the value of an operand (constant
or variable) by 1.

2. Increment ++ increases the value by 1 whereas


decrement -- decreases the value by 1.

3. These two operators are unary operators, meaning they


only operate on a single operand.
Syntax of Increment Operator

Increment Operator can be used in two ways which are as follows:

// AS PREFIX
++m
// AS POSTFIX
m++

1. Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also known
as prefix increment, the value is incremented first according to the
precedence and then the less priority operations are done.
2. Post-Increment
In post-increment, the increment operator is used as the suffix of the
operand. The increment operation is performed after all the other
operations are done. It is also known as postfix increment.
POSTFIX
Postfix:
• (a) x = a++;
First action: store value of a in memory location for
variable x.
Second action: increment value of a by 1 and store
result in memory location for variable a.
• (b) y = b––;
First action: put value of b in memory location for
variable y.
Second action: decrement value of b by 1 and put
result in memory location for variable b.
PREFIX
Prefix :
• (a) x = ++a;
First action: increment value of a by 1 and store
result in memory location for variable a.
Second action: store value of a in memory location
for variable x.
• (b) y = ––b;
First action: decrement value of b by 1 and put
result in memory location for variable b.
Second action: put value of b in memory location
for variable y.
Output:
Prefix Increment: 6
Postfix Increment: 5
Output
Prefix = 4
Postfix = 5
Increment and Decrement Operators Example:

Note: ++ and -- are used as


prefixes. These two operators
can also be used as postfixes like
a++ and a--
C Assignment Operators
•An assignment operator is used for assigning a value
to a variable. The most common assignment operator
is =
Left Shift(<<)
It is a binary operator that takes two numbers, left shifts the bits of the
first operand, and the second operand decides the number of places to
shift. In other words, left-shifting an integer “a” with an integer “b”
denoted as ‘(a<<b)’ is equivalent to multiplying a with 2^b (2 raised to
power b).

Syntax:

a << b;

Right Shift(>>)
It is a binary operator that takes two numbers, right shifts the bits of the
first operand, and the second operand decides the number of places to
shift. In other words, right-shifting an integer “a” with an integer “b”
denoted as ‘(a>>b)‘ is equivalent to dividing a with 2^b.

Syntax:

a >> b;
C Relational Operators
•Relational operators in C are vital for making
comparisons and decisions in programming.
•A relational operator checks the relationship between
two operands.
•If the relation is true, it returns 1; if the relation is
false, it returns value 0.

•Relational operators are used in decision making and


loops.
Working of Relational Operators in C

• Equal-to operator (==) compares two values. It returns


true (1) if the values are equal and false (0) if they are
not.

• Not Equal to Operator (!=) The not equal to operator (!=)


compares two values. It returns true (1) if the values are
not equal and false (0) if they are equal.

• Less than Operator (<) The less than operator (<)


compares two values. It returns true (1) if the left value is
less than the right value and false (0) otherwise.
Working of Relational Operators in C

• Greater than Operator (>) The greater than operator (>)


compares two values. It returns true (1) if the left value is
greater than the right value and false (0) otherwise.

• Less than or Equal to Operator (<=) The less than or equal


to operator (<=) compares two values. It returns true (1) if
the left value is less than or equal to the right value and
false (0) otherwise.

• Greater than or Equal to Operator (>=) The greater than


or equal to operator (>=) compares two values. It returns
true (1) if the left value is greater than or equal to the
right value and false (0) otherwise.
"a is greater than b"
because the condition
a > b is true.
Condition is true.
Bitwise Operator
Truth table of the bitwise operators
Example 1:
1. We have two variables a and b.
2. a =6;
3. b=4;
4. The binary representation of the above two variables are
given below:
5. a = 0110
6. b = 0100
7. When we apply the bitwise AND operation in the above
two variables, i.e., a&b, the output would be:
8. Result = 0100
Example 2:

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
C Logical Operators
Logical operators in C are used to combine multiple
conditions/constraints.

Logical Operators returns either 0 or 1, it depends on


whether the expression result is true or false.

We have 3 logical operators in the C language:

1. Logical AND ( && )


2. Logical OR ( || )
3. Logical NOT ( ! )
1. Logical AND Operator ( && )
If both operands are non zero then the condition
becomes true. Otherwise, the result has a value of 0.
The return type of the result is int.

2. Logical OR Operator ( || )
The condition becomes true if any one of them is
non-zero. Otherwise, it returns false i.e., 0 as the value.

3. Logical NOT Operator ( ! )


If the condition is true then the logical NOT operator will
make it false and vice-versa. Below is the truth table for
the logical NOT operator.
logical AND logical OR

logical NOT
Syntax logical AND
(operand_1 && operand_2)

Output
Both values are
greater than 0
Syntax logical OR
(operand_1 || operand_2)

Output
Any one of the given value is
greater than 0
Syntax logical NOT
!(operand_1 && operand_2)

OUTPUT:
Both values are less than
0
HW Example
Output
False True
The && (logical AND) operator indicates
whether both operands are true.

If both operands have nonzero values, the


result has the value 1. Otherwise, the
result has the value 0.

bitwise operators return an integer


value.
Conditional or Ternary Operator (?:) in C

The conditional operator in C is kind of similar to the if-else


statement as it follows the same algorithm as of if-else
statement.

but the conditional operator takes less space and helps to


write the if-else statements in the shortest way possible.

It is also known as the ternary operator in C as it operates on


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

variable = (condition) ? Expression2 : Expression3;


Or syntax can also be in this form

(condition) ? (variable = Expression2) : (variable


= Expression3);
Conditional/Ternary Operator in C

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

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Working of Conditional/Ternary Operator in C
The working of the conditional operator in C is as follows:
● Step 1: Expression 1 is the condition to be evaluated.
● Step 2A: If the condition(Expression 1) is True then
Expression 2 will be executed.
● Step 2B: If the condition(Expression 1) is false then
Expression 3 will be executed.
● Step 3: Results will be returned.
Flowchart of Conditional/Ternary Operator in C
Example 1: C Program to Store the greatest of the two
Numbers using the ternary operator

Output
m is greater than n that is 5 > 4
Example 2: C Program to check whether a year is a leap year
using ternary operator

Output
The year 1900 is not a leap year
LOgic ::
Given a year, check if it is a leap year or not.

A leap year is a year that has 366 days, instead


of 365 days. It has one day extra in the month of
February. Leap years occur once in 4 years, so
any year that is completely divisible by four
should be a leap year. But this is not always
true.
If there is some year and it is divisible by
hundred, it will be a leap year only if it is also
divisible by four hundred.
In the Gregorian calendar, a normal year consists of 365 days. Because the
actual length of a sidereal year (the time required for the Earth to revolve
once about the Sun) is actually 365.2425 days, a "leap year" of 366 days is
used once every four years to eliminate the error caused by three normal
(but short) years. Any year that is evenly divisible by 4 is a leap year:
for example, 1988, 1992, and 1996 are leap years.

However, there is still a small error that must be accounted for. To


eliminate this error, the Gregorian calendar stipulates that a year that
is evenly divisible by 100 (for example, 1900) is a leap year only if it is
also evenly divisible by 400.

For this reason, the following years are not leap years:

1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600

This is because they are evenly divisible by 100 but not by 400.

The following years are leap years: 1600, 2000, 2400

This is because they are evenly divisible by both 100 and 400.
Generally used when we need a short
conditional code such as assigning value to
a variable based on the condition.

It can be used in bigger conditions but it


will make the program very complex and
unreadable.
Sizeof Operator in C
● Sizeof is a much-used operator in the C. It is a
compile-time unary operator which can be used to
compute the size of its operand.

● The result of sizeof is of the unsigned integral type


which is usually denoted by size_t.

● sizeof can be applied to any data type, including


primitive types such as integer and floating-point
types, pointer types, or compound data types
such as Structure, union, etc.
Syntax:
sizeof(Expression);

where ‘Expression‘ can be a data type or a


variable of any type.

Return: It returns the size of the given expression.


Usage of sizeof() operator
1. When the operand is a Data Type: When sizeof() is used
with the data types such as int, float, char… etc it simply
returns the amount of memory allocated to that data types.
Output Note: sizeof()
1 may give
4 different
4 output
8 according to
machine, we
have run our
program on a
32-bit gcc
compiler.
2. When the operand is an expression: When
sizeof() is used with the expression, it returns the
size of the expression.

Output
8
3. To find out the number of elements in an array:
Sizeof can be used to calculate the number of
elements of the array automatically.
Output
Number of elements:11
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
operator with higher precedence.

• It helps to maintain the ambiguity of the expression


and helps us in avoiding unnecessary use of
parentheses.
Output
10 + 20 * 30 = 610
Output
100 / 5 % 2 = 0
Output:

100 + 200 / 10 – 3 * 10 = 90
HW
Output:
10

What would the output of the above program – ‘5’ or ’10’?

The output is undefined as the order of evaluation of f1() + f2() is


not mandated by standard.

The compiler is free to first call either f1() or f2().

Only when equal level precedence operators appear in an


expression, the associativity comes into picture.

For example, f1() + f2() + f3() will be considered as (f1() + f2()) +


f3().

But among first pair, which function (the operand) evaluated first is
not defined by the standard.
Library Functions
In C language, a built-in function is a pre-defined operation that you
can use in your code without having to write the code for that
operation from scratch.

These functions are provided by the C standard library and cover a


wide range of tasks like math operations, input/output, memory
management, updation and more.

They save time and effort by allowing you to reuse common operations.
These functions are the built-in functions i.e., they are predefined in
the library of the C.

Some of the library functions are printf, scanf, sqrt, etc. To use these
functions in the program the user has to use a header file associated
with the corresponding function in the program.
math.h: This header file contains mathematical functions. It contains functions
such as sqrt, pow, exp, log, sin, etc.
sqrt(): This function takes a double argument and returns the square root. It can
be mathematically expressed as ✔a Prototype
Prototype: double sqrt (double a)

Example:
#include <stdio.h>
#include<math.h>
int main()
{
double a = 25.5637;
printf("%lf",sqrt(a));
return 0;
}
Output: 5.056056
pow(): This function takes two arguments, the base and the exponent. It returns
the value of the base raised to the exponent.
double pow(double a, double b)

Example:
#include <stdio.h>
#include<math.h>
int main() {
double a = 4.0;
double b = 3.0;
double c = pow(a,b);
printf("%.1lf",c);
return 0;
}

You might also like