Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 219

18CSS101J

PROGRAMMING FOR
PROBLEM SOLVING

UNIT 1
Course Learning Outcome (CLO – 1)

• Identify methods to solve a problem through computer


programming.
• List the basic data types and variables in C.
Topics that will be covered in this Session

• Evolution of Programming Language


• Problem Solving through programming
EVOLUTION OF
PROGRAMMING &
LANGUAGE
Programming Language
• A computer needs to be given instructions in a programming language
that it understands.
• A programming language is an artificial language that can be used to
control the behavior of computer.
• Programming languages, like human languages, are defined through the
use of syntactic and semantic rules, to determine structure and meaning
respectively.
• Programming languages are used to facilitate communication about the
task of organizing and manipulating information, and to express
algorithms precisely”.
Types of Programming Language
• Programming language can be divided into three major categories:
1. Machine Language
2. Assembly Language
3. High Level Language
1. Machine Language
• It is the native language of computers.
• It uses only 0s and 1s to represent data
and the instruction.
• For example, the ASCII value for the
letter "A" is 01000001 in machine code,
but this data is displayed as "A" on the
screen.
• An image may have thousands or even
millions of binary values that
determine the color of each pixel.
2. Assembly Language
• It corresponds to symbolic instructions
and executable machine codes and was
created to use letter instead of 0s and 1s
to run a machine.
• It may be produced by compiling source
code from a high-level programming
language (such as C / C++) but can also
be written from scratch.
• Assembly code can be converted to
machine code using an assembler.
3. High Level Language
• These languages are written using
a set of words and symbols
following some rules similar to a
natural language such as English.
• The programs written in high level
languages are known as source
programs and these programs are
converted into machine readable
form by using compilers or
interpreters.
Evolution of programming Language
• In the computer world, we have
about 500+ programming
languages with having their
own syntax and features.
• Ada Lovelace who has written
the first-ever computer
programming language and the
year was 1883.
Evolution of programming Language (Cont…)
• In the early days, Charles Babbage had made the device, but he was
confused about how to give instructions to the machine, and then Ada
Lovelace wrote the instructions for the analytical engine.
• The device was made by Charles Babbage and the code was written by
Ada Lovelace for computing Bernoulli’s number.
• First time in history that the capability of computer devices was judged.
1949: Assembly Language
• It is a type of low-level language.
• It mainly consists of instructions (kind of symbols) that only machines
could understand.
• In today’s time also assembly language is used in real-time programs such
as simulation flight navigation systems and medical equipment eg – Fly-
by-wire (FBW) systems.
• It is also used to create computer viruses.
1952: Autocode
• Developed by Alick Glennie.
• The first compiled computer programming language.
• COBOL and FORTRAN are the languages referred to as Autocode.
1957: FORTRAN
• Developers are John Backus and IBM.
• It was designed for numeric computation and scientific computing.
• Software for NASA probes voyager-1 (space probe) and voyager-2 (space
probe) was originally written in FORTRAN 5.
1958: ALGOL
• ALGOL stands for ALGOrithmic Language.
• The initial phase of the most popular programming languages of C, C++,
and JAVA.
• It was also the first language implementing the nested function and has a
simple syntax than FORTRAN.
• The first programming language to have a code block like “begin” that
indicates that your program has started and “end” means you have ended
your code.
1959: COBOL
• It stands for COmmon Business-Oriented Language.
• In 1997, 80% of the world’s business ran on Cobol.
• The US internal revenue service scrambled its path to COBOL-based IMF
(individual master file) in order to pay the tens of millions of payments
mandated by the coronavirus aid, relief, and economic security.
1964: BASIC
• It stands for beginners All-purpose symbolic instruction code.
• In 1991 Microsoft released Visual Basic, an updated version of Basic
• The first microcomputer version of Basic was co-written by Bill Gates, Paul
Allen, and Monte Davidoff for their newly-formed company, Microsoft.
1972: C
• It is a general-purpose, procedural programming language and the most
popular programming language till now.
• All the code that was previously written in assembly language gets
replaced by the C language like operating system, kernel, and many other
applications.
• It can be used in implementing an operating system, embedded system,
and also on the website using the Common Gateway Interface (CGI).
• C is the mother of almost all higher-level programming languages like C#,
D, Go, Java, JavaScript, Limbo, LPC, Perl, PHP, Python, and Unix’s C shell.
Some other programming languages
Some other programming languages
PROBLEM SOLVING
THROUGH
PROGRAMMING
Problem Solving
• Problem solving is the purpose of basic and sequential steps to arrive at
the result of a given problem.
• Problem solving is the process of transforming the description of a
problem into a solution by using our knowledge of the problem domain
and by relying on our ability to select and use appropriate problem
solving strategies, techniques and tools.
Six steps in problem solving
• Programmer can solve problems effectively using Software Development
Method (SDM).
• The basic six steps in solving the problems are
1. Specifying the problem requirements
2. Analyse the problem
3. Design the algorithm to solve the problem
4. Implement the algorithm
5. Test and verify the completed program
6. Documentation
1. Specifying the problem requirements
• The problem to be solved or the task is defined.
• Inputs, outputs, processing requirements, system constraints such as
execution time, accuracy and error handling methods are specified.
2. Analyse the problem
• Programmer should thoroughly understand the problem and problem
requirements.
• Once the input and the output data of the problem are identified, the
programmer must find out whether all the input items necessary to
compute the required outputs are available.
• If necessary inputs are not available, before proceeding further, additional
information needed is determined and provided.
• If the problem is complex. It must be divided into sub problems.
3. Design the algorithm to solve the problem
• Algorithms are the foundation and framework of all computer programs.
• Algorithm is the step by step process of the computer program.
• They are the sequence of precise instructions given to a computer for
achieving a desired output.
• Many algorithmic patterns or paradigms exist such as greedy algorithm,
divide and conquer algorithm and backtracking algorithm.
• Each class of algorithm has its own unique design structure.
4. Implement the algorithm
• To implement the algorithm, print the pseudo code and try to implement
it.
• For an algorithm that takes a file as input.
• First, work on the code for reading the input file.
• Implementation is carried out by writing programs in a high level
language.
• In the past, The FORTRAN language was used to develop commercial
applications.
• Later, C language was developed. It is suitable to develop all types of
application and is also useful to develop system programs.
4. Implement the algorithm (Cont..)
• Testing the code extensively to make sure that the program reads the input
file correctly.
• Then, Programmer will add additional details to perform the first
operation of the algorithm.
• He will check if the intermediary results are correct by comparing with
the other data.
• If it is not correct, he has to debug it to make sure that there is no logical
error.
5. Test and verify the completed program
• Once the program code has been entered into the computer, edited and
saved, it should be executed, tested and verified.
• If there is no syntax error, compilation of program is done successfully and
can be executed.
• If there are any errors, the error messages are displayed on the terminal.
• Each error is corrected by typing a correct statement.
• The program is compiled and executed.
6. Documentation
• Documentation provides a written description of each step of the program.
• Once the program is free from errors, it is suitable for documentation.
• It enables the user to operate the program correctly and also to understand
the program correctly by the users.
Phases of programming
• A typical programming task can be divided into two phases:
1. Problem Solving Phase
2. Implementation Phase
Phases of programming (Cont..)
1. Problem Solving Phase
• Produce an ordered sequence of steps that describe solution of problem. This sequence of
steps is called an Algorithm.
• There are three steps in problem solving phase
a. Produce a general algorithm.
b. Refine the algorithm successively to get step by step detailed algorithm that is very
close to a computer language.
c. Pseudocode is an artificial and informal language that helps programmers develop
algorithms. Pseudocode is very similar to everyday English.

2. Implementation Phase
• Implement the program in some programming language.
Combination of Problem Solving
• Problem solving is a combination of creative thinking and critical thinking.
Creative Thinking
• Proven method for approaching a challenge or opportunity in an
imaginative way.
• Process for innovation that helps explore and reframe the problems faced,
come up with new, innovative responses and solutions and then take
action.
• It is generative, non-judgmental and expansive.
• Thinking creatively, a lists of new ideas are generated.
Critical Thinking
• Engages a diverse range of intellectual skills and activities that are
concerned with evaluating information, our assumptions and our thinking
processes in a disciplined way so that we can think and assess information
more comprehensively.
• It is analytical, judgemental and selective.
• Thinking critically allows a programmer in making choices.
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 1
Course Learning Outcome (CLO – 1)

• Identify methods to solve a problem through computer


programming.
• List the basic data types and variables in C.
Topics that will be covered in this Session

• Creating Algorithms
• Drawing Flowcharts
• Writing Pseudocode
• Evolution of C language; its usage history
CREATING ALGORITHMS
Algorithm
• An algorithm is defined as the step by step instructions that perform a
specific task or operation.
• In the context of computer programming, an algorithm is defined “as a
well ordered collection of unambiguous and effectively computable
operations that are executed, produces a result and halts in a finite amount
of time”.
• It is an informal description of a program.
• A program is the step by step description of the solution to a certain
problem.
• Thus an algorithm is a sequence of simple steps that can be followed to
solve a problem.
• These steps must be organized in a logical and clear manner.
Explicit or Implicit of an algorithm
• Incoming Information – The values or data that are needed to find the
solution (called input).
• Line numbers – Positions in algorithm. This we can mention explicitly or
can be understood implicitly.
• Control Flow – which step comes after which one, in what sequence.
• Statements – tell which data variable to update, and in what manner.
• Outgoing information – the values or data that are solution (called
output).
Characteristics of an algorithm
• The instructions must be in an ordered form.
• The instructions must be simple and concise. They must not be
ambiguous.
• There must be an instruction for program termination.
• The repetitive programming constructs must possess an exit condition.
Otherwise the program might run infinitely.
• The algorithm must completely and definitely solve the given problem
statement.
Qualities of a good algorithm
• It uses the most efficient logic to solve the given problem (Time
complexity).
• It uses minimal system memory for this execution (Space complexity).
• It is able to generate the most accurate results for a wide range of input set.
• It is easy to implement in the form of a program.
• It is designed with standard conventions so that others are able to easily
modify it while adding additional functionality.
Method for developing an algorithm
• Define the problem – State the problem you are trying to solve in clear
and concise terms.
• Problem Requirements – List the inputs (information needed to solve the
problem) and the outputs (what the algorithm will produce as a result).
• Manipulating Requirements – Describe the steps needed to convert or
manipulate the inputs to produce the outputs. Start at a high level first,
and keep refining the steps until they are effectively computable
operations.
• Test the algorithm – Choose data sets and verify that how the algorithm
works.
Example for an Algorithm
Add two numbers Find the largest among 3 numbers
Step 1 : Start • Step 1: Start
Step 2 : Declare variables n1, n2 and • Step 2: Read three numbers, say a, b, c
sum • Step 3: If a is greater than b goto step 4;
Step 3 : Read values n1 and n2 otherwise goto step 7
Step 4 : Add n1 and n2 and assign the • Step 4: If a is greater than c goto step 5;
result to sum otherwise goto step 6
sum  n1 + n2 • Step 5: Display a. Goto step 10
Step 5 : Display sum • Step 6: Display c. Goto step 10
Step 6 : Stop • Step 7: If b is greater than c, goto step 8;
otherwise goto step 9
• Step 8: Display b. Goto step 10
• Step 9: Display c. Goto step 10
• Step 10: Stop
DRAWING FLOWCHARTS
Flowchart
• A flowchart is a pictorial representation of an algorithm in which the steps
are drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting arrows.
• The boxes represent operations and the arrows represent the sequence in
which the operations are implemented.
• The primary purpose of the flow chart is to help the programmer in
understanding the logic of the program.
• The flowchart is drawn according to defined rules and using standard
flowchart symbols prescribed by American National Standard Institute
(ANSI).
Standard Symbols used in flowchart
Standard Symbols used in flowchart (Cont..)
Standard Symbols used in flowchart (Cont..)
Guidelines for preparing flowcharts
• The flowchart should be clear, neat and easy to follow.
• The flowchart must have a logical start and finish.
• The direction of the flow of a procedure should always be from left to right
or top to bottom.
• Only one flow line should come out of a process symbol.
Guidelines for preparing flowcharts (Cont..)
• Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.

• Only one flow line is used with a terminal symbol.


Guidelines for preparing flowcharts (Cont..)
• Within standard symbols, write briefly. If necessary, use the annotation
symbol to describe data or process more clearly.

• In case of complex flowcharts, connector symbols are used to reduce the


number of flow lines.
• Intersection of flow lines should be avoided to make it a more effective
and better way of representing communication.
• It is useful to test the validity of the flowchart by passing through it with
normal / unusual test data.
Benefits of Flowchart
• Makes logic clear: The pictorial representation makes the logic easier to follow.
• Communication: Flow charts are a better way of communicating the logic of a
system to all concerned.
• Effective analysis: With the help of a flow chart, the problem can be analyzed in
an effective way.
• Useful in coding: The flowcharts act as a guide or blueprint during the program
development phase.
• Proper testing and debugging: A flowchart helps in detecting the errors in a
program.
• Appropriate Documentation: Flowcharts serve as a good program
documentation tool.
Limitations of flowchart
• Complex: When a program is very large, the flow charts may continue for
many pages and it is complex.
• Costly: If flowcharts are to be drawn for a huge application, it takes much
time and it is costly.
• Difficult to modify: Any changes or modification to a flowchart requires
redrawing the entire logic again. Redrawing a complex flowchart is
tedious.
• No update: Usually, programs are updated regularly. However, the
corresponding update of flowcharts may not take place.
Example for an Flowchart
Add two numbers Find the biggest among 3 numbers
WRITING PSEUDOCODE
Pseudocode
• Pseudocode is made up of two words: pseudo and code.
• Pseudo means imitation and code refers to instructions written in
programming language.
• Pseudocode is not a real programming code, but it looks like
programming code.
• Pseudocode is an outline of a program, written in a form that can be easily
converted into real programming statements.
• Pseudocode instructions are written in normal English, but in a structured
way.
Guidelines of Pseudocode
• Statements should be written in English and should be programming
language independent.
• Pseudocode should describe the login plan to develop a program.
• Steps must be understandable and it should not be difficult.
• Each instruction should be written in a separate line.
• Keywords should be capitalized.
• Each set of instruction must be written from top to bottom.
• It should be easy for translating the design into coding in any
programming language
Keywords to denote programming process
• Pseudocode uses some keywords to denote programming process.

1. Input: READ, OBTAIN, GET and PROMPT

2. Output: PRINT, DISPLAY and SHOW

3. Compute: COMPUTE, CALCULATE and DETERMINE

4. Initialize: SET and INITIALIZE

5. Add one: INCREMENT


Benefits of Pseudocode
• It allows the designer to express the design in plain natural language.
• It is easier to develop a program from pseudocode.
• Pseudocode is compact and does not tend to run over may pages.
• It is easier to modify.
• It allows programmers who work in different computer languages to talk
to each other.
• It works well for large program design.
Limitations of Pseudocode
• It does not provide visual representation.
• There are no accepted standards for writing pseudocodes. Programmers
use their own style of writing pseudocode.
• Pseudocode cannot be compiled nor executed.
Example for Pseudocode
Add two numbers Find the largest among 3 numbers
READ a, b, c
READ a, b IF (a > b) THEN
COMPUTE sum = a + b IF (a > c) THEN
DISPLAY sum DISPLAY a is largest
Stop ELSE
DISPLAY c is largest
ELSE
IF (b > c)
DISPLAY b is largest
ELSE
DISPLAY c is largest
Stop
SOME EXAMPLE OF
ALGORITHM,
PSEUDOCODE &
FLOWCHART
Find the area & circumference of circle
Calculate the total marks of the student
Find the sum of the digit
Print the reverse of the number
Find the given number is prime or not
Find the given year is leap year or not
Convert Celsius into Fahrenheit
EVOLUTION OFC
LANGUAGE; ITS USAGE
HISTORY
Overview of C
• C is a general-purpose, structured programming language.
• C resembles other high-level structured programming languages such as
Pascal and Fortran.
• C can also be used at a lower level thus bridging the gap between machine
language and high-level languages.
• Thus C can be used for systems programming (e.g. for writing operating
systems) as well as for application programming.
• C is characterized by the ability to write very concise source programs.
• It has a relatively small instruction set, though actual implementations
include extensive library functions which enhance the basic instructions.
Overview of C (Cont..)
• Furthermore, the language encourages users to write additional library
functions of their own.
• Thus, the features and capabilities of the language can easily be extended
by the user.
• C compilers are commonly available for computers of all sizes and C
interpreters are becoming increasingly common.
• The compilers are usually compact and they generate object programs that
are small and highly efficient when compared to programs compiled from
other high-level languages.
• The interpreters are less efficient, though they are easier to use when
developing a new program.
Overview of C (Cont..)
• Another important characteristic of C is that its programs are highly
portable.
• Every version of C is accompanied by its own set of library functions,
which are written for the particular characteristics of the host computer.
• Each library function is generally accessed in the same manner from one
version of C to another.
• Therefore, most C programs can be processed on many different
computers with little or no alteration.
History of C
• C was originally developed in 1970s by Dennis
Ritchie at Bell Telephone Laboratories.
• It is an outgrowth of 2 earlier languages BCPL and
B, which were also developed at Bell Laboratories.
• C was largely confined to use within Bell
Laboratories until 1978, when Brian Kernighan
and Ritchie published a definitive description of
the language.
• The Kernighan and Ritchie description is
commonly referred to as “K&R C”. Dennis Ritchie
History of C (Cont..)
• Following the publication of the K&R description, computer professionals,
impressed with C’s many desirable features, began to promote the use of
the language.
• By the mid of 1980s, the popularity of C had become widespread.
• Numerous C compilers and interpreters had been written and many
commercial application programs had been developed.
• Moreover many commercial software products that were originally
written in other languages were rewritten in C in order to take advantage
of its efficiency and its portability.
History of C (Cont..)
• Most commercial implementations of C differ somewhat from Ritchie’s
original definition.
• This has created some minor incompatibilities among different
implementations of the language, thus diminishing the portability that the
language attempts to provide.
• Consequently, the American National Standards Institute (ANSI) has
developed a standardized definition of the language.
• Most commercial C compilers and interpreters adopt the ANSI standard.
Evolution of C
Features of C
• C is a general-purpose programming language.
• C is a structured programming language.
• The features and capabilities of C can be extended by the user. The
instruction set in C is relatively very small. But, the actual implementation
of the program in C includes an extensive set of library functions.
• C is a typed language. A typed language is one, which requires the
declaration of all variables in the program and their types before they are
put to use.
• C allows us to extend its set of data types by declaring structures,
enumerated data types and typedef statements.
Features of C (Cont..)
• Functions in C are inherently recursive in nature.
• Recursion is the process of a function calling itself and many of the
programming languages written prior to C do not support this feature.
• C provides a large set of data structures.
• The concept of pointer variables has blossomed to its fullest extent in C to
the great joy of tricky programmers.
• C has a robust collection of operators.
• The concept of dynamic memory allocation was newly introduced by C.
• Programs in C are highly portable.
Desirable Program Characteristics
• Integrity: This refers to the accuracy of the calculations.
• Clarity: This refers to the overall readability of the program. If a program
is clearly written, it should be possible for another programmer to follow
the program logic without undue effort.
• Simplicity: The clarity and accuracy of a program are usually enhanced by
keeping things as simple as possible, consistent with the overall program
objectives.
Desirable Program Characteristics (Cont..)
• Efficiency: This is concerned with the execution speed and efficient
memory utilization.
• Modularity: Many programs can be broken down into a series of
identifiable subtasks. It is good programming practice to implement each
of these subtasks as a separate program module. In C, such modules are
written as functions.
• Generality: Usually we will want a program to be as general as possible,
within reasonable limits
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 1
Course Learning Outcome (CLO – 1)

• Identify methods to solve a problem through computer


programming.
• List the basic data types and variables in C.
Topics that will be covered in this Session

• Input and Output functions: printf and scanf


• Variables and identifiers
INPUT AND OUPUT
FUNCTIONS: PRINTF AND
SCANF
Introduction
• The process of running input and output functions of C program is called
managing the input and output functions.
• Reading and accepting the data are called input functions.
• The display of processed data by output devices is called output function.
• Reading data from input devices and displaying the results on the screen
are the main tasks of any programs.
• To perform these tasks, C supports number of input and output functions.
• These standard library for input and output functions used in C is stdlib.
Introduction (Cont..)
• There are two streams in C program to work with the input and output
devices. They are standard input (stdin) and standard output (stdout)
streams.
• Standard input is the data stream for taking input from devices such as
keyboard.
• Standard output is the data stream for sending output to the devices such
as monitor.
• Input and output functions are necessary for reading, processing and
writing of any data.
• To use input and output functions in the program stdio header should be
included to the program: #include<stdio.h>
Input
• In any programming language input means to feed some data into
program.
• This can be given in the form of file or from command line.
• C programming language provides a set of built-in functions to read given
input and feed it to the program as per requirement.
Output
• In any programming language output means to display some data on
screen, printer or in any file.
• C programming language provides a set of built-in functions to output
required data.
Input / Output functions
• The input / output function in C is classified into two types
I. Formatted functions
II. Unformatted functions
Formatted functions
• The formatted I/O functions can be used to read and write all types of data
values and also it is used to arrange the data in the particular format.
• Formatted function is divided into formatted input functions and
formatted output functions.
• Formatted function require a format specifier to identify the datatypes.
Format specifiers
• Format specifiers are,
Conversion
Meaning
Character
c Data item is displayed as a single character
d Data item is displayed as a signed decimal integer
e Data item is displayed as a floating-point value with an exponent
f Data item is displayed as a floating-point value without an exponent
Data item is displayed as a floating-point value using either e-type or f-type conversion,
g
depending on value; trailing zeros, trailing decimal point will not be displayed
i Data item is displayed as a signed decimal integer
o Data item is displayed as an octal integer, without leading zero
s Data item is displayed as a string
u Data item is displayed as an unsigned decimal integer

x Data item is displayed as a hexadecimal integer, without the leading 0x


Formatted Input function
• The formatted input refers to the input data that have been arranged in a
particular format.
scanf()
• The scanf() statements read all types of data values, assignment of value
for the variable is done during runtime.
Syntax
scanf(“format specifier / control string”,&arg1,&arg2….&arg n);
• The control string specifies the format specifier in which the data are to be entered and
the arguments arg 1, arg 2, ……arg n specify the address of locations where the data
separated by commas.
Example
int n;
scanf(“%d”,&n);
Formatted Output function
• The formatted output function is used to display the standard output data
items on the output devices, it can display any combination of numerical
values, strings and single character.
printf()
• The printf() function prints all types of data value to the console, the printf statement
requires the format specifiers and variable names to print the data.
• The printf() statement provides certain features that can be effectively exploited to
control the alignment and spacing of outputs on the terminals.
• The control string comprise the character to be printed, specification of format and etc..
Syntax printf(“format specifier / control string”,arg 1,arg 2….arg n);

Example printf(“Welcome all”);


printf(“n is %d”,n);
Unformatted functions
• The unformatted I/O functions can be used to read and write single or
group of characters.
• Here the user cannot specify the type of data that is going to be input /
output.
• Unformatted function is divided into unformatted input functions and
unformatted output functions.
Unformatted input functions
• The unformatted I/O functions can be used to read a single or group of
characters.

getch()
• The functions read the alphanumeric characters from the standard input.
• The character entered is not displayed by getch() function.

Syntax
getch();
Unformatted input functions (Cont..)

getchar() – Single character input


• This function reads character type data from the standard input.
• It reads one character at a time till the user clicks the enter key.

Syntax

getchar();
Unformatted input functions (Cont..)
gets()
• The function gets() collects a string of characters terminated by a new line
from the standard input stream and puts into s.
• It replaces the newline by a null character (\0) in s.
• It also allows input strings to contain certain whitespace characters
(spaces, tabs).
• It returns when it encounters a newline; Everything upto the newline is
copied into s.
Example
gets();
Unformatted output functions
• The unformatted I/O functions can be used to write single or group of
characters.

putch()
• It is a string output function to write any alphanumeric.
• Character to a standard output device.

Syntax

putch();
Unformatted output functions (Cont..)

puts()
• The function puts() copies the null terminated string s to the standard
output stream and appends a newline character.
• On success, puts() returns a non-negative value. On error, puts() returns a
value of EOF.

Syntax

puts();
Unformatted output functions (Cont..)

putchar() – Single character output


• Single characters can be displayed using the C library function putchar().
• It is an output function to write any alphanumeric character on the
standard output.
• It prints one character at a time or as an argument.

Syntax
putchar();
IDENTIFIERS
Identifiers
• Identifiers refer to the names of variables, functions and arrays. These are
user-defined names and consist of a sequence of letters and digits, with a
letter as a first character.
• Both uppercase and lowercase letters are permitted, although lowercase
letters are commonly used.
• The underscore character is also permitted in identifiers.
• It is usually used as a link between two words in long identifiers.
Rules for identifiers
• First character must be an alphabet (or underscore).
• Must consist of only letters, digits or underscore.
• Only first 31 characters are significant.
• Cannot use a keyword.
• Must not contain white space.
VARIABLES
Variables
• A variable is an identifier that is used to represent some specified type of
information within a designated portion of the program.
• Simply, a variable represents a single data item, that is, a numerical
quantity or a character constant.
• The data item must be assigned to the variable at some point in the
program.
• The data item can then be accessed later in the program simply referring
to the variable name.
• A given variable can be assigned different data items at various places
within the program.
• Thus, the information represented by the variable can change during the
execution of the program.
• However, the data type associated with the variable cannot change.
Rules for declaring the variables
• All variables must be declared before they can appear in executable statement.
• A declaration consists of a datatype followed by one or more variable names
separated by commas. Example: int a,b,c;
• Variables can be distributed among declarations in any fashion. The declaration
can be written as,
int a;
int b,c;
• Integer type variables can be declared to be short integer for smaller integer
quantities or long integer for larger integer quantities.
Example: short int a,b,c;
long int a,b,c;
• An integer variable can also be declared to be unsigned by writing unsigned int,
Example: unsigned int
Rules for naming the variables
• A variable name must be made from the characters, underscore (_), upper
case letter (A – Z), lower case letter (a – z) and digits (0 – 9).
• Blank space and commas or not allowed.
• No special symbols other than underscore (_) are allowed.
• Variable name should not be reserved word (keyword) of C language.
• Variable name can only start with character or underscore (_).
• Uppercase and lowercase are significant. That is, the variable Total is not
the same as total or TOTAL.
Syntax: datatype variable name;

Example: int average_number;


Examples of variable name
Scope of variables
• The scope of variables is the part of the program where the variable name
can be used. It is also called lexical scope.
• It defines whether the declared variable is accessible to other sections of
the program code.
• It is classified into two types.
• Local variable
• Global variable
Local variables
• Internal variables are the variables Example
declared inside a particular
function or block of the program.
• A local variables scope is restricted
within the block or function; it
must always be defined at the top
of the block.
• Local variables are define inside
the function block or inside a
compound statement.
• The internal variable only during
the execution of the declared block
or function of the program.
Global variables
Example
• Global variables are the variables
declared outside of all functions or
blocks of the program.
• It is defined at the top of the
program file and it can be visible
and modified by any function that
may reference it.
• A global variable can be accessed
by any function.
• It will be available during the
execution of the entire program.
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 1
Course Learning Outcome (CLO – 1)

• Identify methods to solve a problem through computer


programming.
• List the basic data types and variables in C.
Topics that will be covered in this Session

• Expressions
• Single Line and Multiline comments
• Constants
• Keywords
• Binding
• Storage classes
STUCTURE OF ‘C’
PROGRAMMING
Introduction

• C programming language was developed by combining the features of


ALGOL, BCPL and B languages called Combined Programming Language
(CPL) or C language.
• C language is the most popular language among all the modern
languages.
• The structure of a C program is based on a set of rules defined by the
computer.
Basic structure of C programs
Documentation Section
• The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer
would like to use later.
• Comment is a sequence of characters beginning with a forward slash ‘/’
asterisk ‘*’ combination.
• It is treated as single white space by the compiler.
• It can include any combination of characters by the compiler.
• The comment statement is not executable because they are ignored at the
time of execution.
Example:
/* This is the program to find the sum of two numbers. */
Link Section
• The link section provides instructions to the compiler to link functions
from the system library.
• it is also called as Preprocessor directives or header files.
• The preprocessor statement begins with # symbol.
• These statements instruct the compiler to include C preprocessor such as
header files and symbolic constants before compiling the c program.
• Some preprocessor statements are,
o # include<stdio.h>
o # include<math.h> Header
Files
o #include<stdlib.h>
o #include<string.h>
Link Section (Cont..)
• The important preprocessor directives are,
Directives Description
#define It defines a sequence of characters, called symbol.
#undef It allows you to undefine a symbol.
#if It allows testing a symbol or symbols to see if they evaluate to true.
#else It allows to create a compound conditional directive, along with #if.
#elif It allows creating a compound conditional directive.
#endif Specifies the end of a conditional directive.
#include Inserts a particular header from another file.
It lets you modify the compiler's line number and (optionally) the file name output for errors and
#line warnings.
#error It allows generating an error from a specific location in your code.
#warning It allows generating a level one warning from a specific location in your code.
It lets you specify a block of code that you can expand or collapse when using the outlining feature
#region of the Visual Studio Code Editor.
#endregion It marks the end of a #region block.
Definition Section
• The definition section defines all symbolic constants.
• A symbolic constant is a name given to some numeric constant or a
character constant or strig constant or any other constant.
• Symbolic constant names are also known as constant identifiers.
• Pre-processor directive #define is used for defining symbolic constants.
• When a program is compiled, each occurrence of a symbolic constant is
replaced by its corresponding character sequence.
• Symbolic constants are usually defined at the beginning of a program.
o #define PI 3.14
Symbolic
o #define TRUE 1 Constants
o #define FALSE 0
Global Declaration Section
• There are some variables that are Example
used in more than one function.
Such variables are called global
variables.
• They are declared in the global
declaration section that is outside
of all the functions. This section
also declares all the user-defined
functions.
main() function Section
• Every C program must have one main() function section. This section
contains two parts, declaration part and executable part.
• The declaration part declares all the variables used in the executable part.
• There is at least one statement in the executable part.
• These two parts must appear between the opening and the closing braces.
• The program execution begins at the opening brace and ends at the closing
brace.
• The closing brace of the main function section is the logical end of the
program.
• All statements in the declaration and executable parts end with a
semicolon(;).
Subprogram Section
• The subprogram section contains all the user-defined functions that are
called in the main function.
• User-defined functions are generally placed immediately after the main
function, although they may appear in any order.
• All sections, except the main function section may be absent when they are
not required.
C TOKENS
C Tokens
• In a passage of text, individual words and punctuation marks are called
tokens.
• Similarly, in a C program the smallest individual units are known as C
tokens. C has six types of tokens.
• C programs are written using these tokens and the syntax of the language.
EXPRESSIONS
Expressions
• An expression represents a single data item, such as a number or a
character.
• The expression may consist of a single entity, such as constant, a variable,
an array element or a reference to a function.
• It may also consist of some combination of such entities interconnected by
one or more operators.
• Expressions can also represent logical conditions that are either true or
false.
• In C, the conditions true and false are represented by the integer values 1
and 0 respectively. Hence, logical-type expressions really represent
numerical quantities.
• Example:
a+b x=y c=a+b x <= y x == y ++i
SINGLE LINE &
MULTILINE COMMENTS
Comments
• Used to provide information about lines of code
• Provide clarity to the C source code
• Allows others to better understand what the code was intended to
• Helps in debugging the code
• Important in large projects containing hundreds or thousands of lines of
source code
• Types – Single line and multiline comment
Single Line Comments
• Represented by double slash //
Multi-Line Comments
• Represented by slash asterisk /* … */
Single-line and Multi-line Comments
• Difference between Single-line and Multi-line Comments

Single-Line Comments Multi-Line Comment

Starts with // Starts with /* and ends with */

Statements after the symbol // upto the end All Words and Statements written between
of line are ignored /* and */ are ignored
Comment Ends whenever ENTER is Pressed
Comment ends when */ Occures
and New Line Starts

e.g // Program for Fibonacci e.g /* Program for Factorial */


CONSTANTS
Constants
• Constants in C refer to fixed values that do not change during the
execution of a program. C supports several types of constants.
Integer Constant
• An integer constant is an integer-valued number. It consists of a sequence
of digits.
• Integer constants can be written in 3 different number systems.

1. decimal (base 10)


2. octal (base 8)
3. hexadecimal (base 16)
Integer Constant (Cont..)
Decimal Integer Constant:
• A decimal integer constant can consist of any combination of digits from
the set 0 through 9. If the constant contains 2 or more digits, the first digit
should not be 0.
Examples for valid decimal integer constants
0 1 743 5280
Examples for invalid decimal integer constants

12,245 illegal character (,)


36.0 illegal character (.)
10 20 30 illegal character (blank space)
123-45-6789 illegal character (-)
09 the first digit cannot be 0
Integer Constant (Cont..)
Octal Integer Constant:
• An octal integer constant can consist of any combination of digits taken
from the set 0 through 7. The first digit must be 0 in order to identify the
constant as an octal number.
Examples for valid octal integer constants
0 01 0743 07777

Examples for invalid octal integer constants


05280 illegal digit (8)
0777.777 illegal character (.)
Integer Constant (Cont..)
Hexadecimal Integer Constant:
• A hexadecimal integer constant must begin with either 0x or 0X. It can
then be followed by any combination of digits taken from the sets 0
through 9 and a through f (either uppercase or lowercase). The letters a
through f represent the quantities 10 through 15 respectively.
Examples for valid hexadecimal integer constants
0x 0x1 0x7FFF 0xabcd
Examples for invalid hexadecimal integer constants
0x12.34 illegal character (.)
0BE38 does not begin with 0x
0x.46fb illegal character (.)
0xDEFG illegal character G
Integer Constant (Cont..)
Unsigned and Long Integer Constants
• An unsigned integer constant can be identified by appending the letter U
to the end of the constant.
Example:
50000U decimal
07777U octal
0x5000U hexadecimal
• A long integer constant can be identified by appending the letter L to the
end of the constant.
Example:
123456789L decimal
0123456L octal
0xFFFFL hexadecimal
Integer Constant (Cont..)
Unsigned Long Integer Constants
• An unsigned long integer may be specified by appending the letters UL to
the end of the constant. U must precede L.

Example:
123456789UL decimal
0123477UL octal
0xDEFFUL hexadecimal
Real Constant
• A real constant is a base-10 number that contains either a decimal point or
an exponent or both.
• If an exponent is present its effect is to shift the location of the decimal
point to the right if the exponent is positive or to the left if the exponent is
negative.
• Real constants have a much greater range than integer constants.
Minimum Value : 3.4E-38
Maximum Value : 3.4E+38
• The precision of floating point constants will vary from one version of C to
another.
• Almost all versions of language permit at least six significant figures and
some versions permit as many as 18 significant figures.
Real Constant - Example
Examples for valid real constants
0. 1. 0.2 827.602 5000. 0.00074 12.3
2E-8 0.oo6e-3 .1212e12

Examples for invalid real constants


1 Either a decimal point or an exponent must be present
1,000.0 Illegal character (,)
2E+10.2 Exponent must be an integer quantity
3E 10 Illegal character (blank space) in the exponent
Character Constant
• A character constant is a single character enclosed in apostrophes (single
quotation marks).
Examples:
‘A’ ‘r’ ‘S’ ‘$’
• Character constants have integer values that are determined by the
computer’s particular character set.
• Most computers make use of the American Standard Code for Information
Interchange (ASCII) character in which each individual character is
numerically encoded with its own unique 7-bit combination.
• IBM mainframe computers utilize the Extended Binary Coded Decimal
Information Code (EBCDIC) character set, in which each individual
character is numerically encoded with its own unique 8-bit combination.
Character Constant – ASCII Values
Character Constant – Escape Sequence
• Certain non printing characters, as • Some Escape sequence are,
well as the double quote(“), the Character Escape Sequence ASCII Value
apostrophe(‘), the question mark(?) Bell (alert) \a 007
Backspace \b 008
and the backslash(\) can be Horizontal Tab \t 009
Vertical Tab \v 011
expressed in terms of escape New line \n 010
sequences. Form Feed \f 012
Carriage Return \r 013

• An escape sequence always begins Quotation Mark \” 034

with a backward slash and is Apostrophe \’ 039


Question Mark \? 063
followed by one or more special Back slash \\ 092
characters. Null \0 000
String Constant
A string constant consists of any number of consecutive characters enclosed
in double quotation marks.

Example:
“green”, “Washington, D.C.2005”, “270-32-3450”, “ ”

• The string constant “” is a null (empty) string.


• The string “\t To continue, press the \” RETURN \” key\n” will be
displayed as
• To continue, press the “RETURN” key
• The compiler automatically places a null character (\0) at the end of each
string constant.
KEYWORDS
Keywords
• Keywords are reserved words that have predefined meanings in C. They
cannot be used as identifiers.
• All keywords have fixed meanings and these meanings cannot be
changed. Keywords serve as basic building blocks for program statements.
The standard keywords are
BINDING
Binding
• A Binding is an association between an entity and an attribute
• Between a variable and its type or value
• Between a function and its code
• Binding time is the point at which a binding takes place
• Types of Binding
• Design Time
• Compile Time
• Link Time
• Run Time
Binding (Cont..)

a) Design Time
• Binding decisions are made when a language is designed
Example
• Binding of + to addition in C

b) Compile Time
• Bindings done while the program is compiled
• Binding variables to datatypes
Example
• int a; float b; char c;
Binding (Cont..)

c) Link Time
• Compiled code is combined into a full program for C
Example
• Global and Static variables are bound to addresses

d) Run Time
• Any binding that happens at run time is called Dynamic
• Any binding that happens before run time is called Static
• Values that are dynamically bound can change
STORAGE CLASSES
Storage class
• A storage class represents the • There are total four types of
visibility and a location of a variable. standard storage classes. The table
• It tells from what part of code we can below represents the storage
access a variable. classes in C.

• A storage class in C is used to describe


the following things:
o The variable scope.
o The location where the variable will be
stored.
o The initialized value of a variable.
o A lifetime of a variable.
o Who can access a variable?
Automatic Storage class
• Automatic variables are allocated memory automatically at runtime.
• The visibility of the automatic variables is limited to the block in which
they are defined.
• The scope of the automatic variables is limited to the block in which they
are defined. The automatic variables are initialized to garbage by default.
• The memory assigned to automatic variables gets freed upon exiting from
the block.
• The keyword used for defining automatic variables is auto.
• Every local variable is automatic in C by default.
Automatic Storage class - Example
Example:
auto int age;
Program:

Output: 3 2 1
Static Storage class
• The variables defined as static specifier can hold their value between the
multiple function calls.
• Static local variables are visible only to the function or the block in which
they are defined.
• A same static variable can be declared many times but can be assigned at
only one time.
• Default initial value of the static integral variable is 0 otherwise null.
• The visibility of the static global variable is limited to the file in which it
has declared.
• The keyword used to define static variable is static.
Static Storage class - Example
Register Storage class
• The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
• The access time of the register variables is faster than the automatic
variables.
• The initial default value of the register local variables is 0.
• The register keyword is used for the variable which should be stored in
the CPU register.
• We can store pointers into the register, i.e., a register can store the address
of a variable.
• Static variables can not be stored into the register since we can not use
more than one storage specifier for the same variable.
Register Storage class - Example
Program

Output:
0
External Storage class
• The external storage class is used to tell the compiler that the variable defined
as extern is declared with an external linkage elsewhere in the program.
• The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere in
the program.
• The default initial value of external integral type is 0 otherwise null.
• We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
• An external variable can be declared many times but can be initialized at only
once.
• If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern or
static. If it is not, then the compiler will show an error.
External Storage class - Example
Program

Output:
20
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING

UNIT 1
Course Learning Outcome (CLO – 1)

• Identify methods to solve a problem through computer


programming.
• List the basic data types and variables in C.
Topics that will be covered in this Session

• Numeric Data Types: Integer


• Numeric Data Types: Floating Point
• Non – Numeric Data Types: Char and String
• Increment and Decrement Operator
• Comma, Arrow and Assignment Operator
• Bitwise and Sizeof Operator
DATA TYPES
Data Types

• C language is rich in its data types. Storage representations and machine


instructions to handle constants differ from machine to machine.
• The variety of data types available allow the programmer to select the type
appropriate to the needs of the application as well as the machine.
• ANSI C supports three classes of data types:
1. Primary (or fundamental) data types (void, int, char, double, float)
2. Derived data types (array, references, pointers)
3. User-defined data types (structure, union, Enumeration)
Data Types (Cont..)

• All C compilers support five fundamental data types, namely integer (int),
character (char), floating point (float), double-precision floating point
(double) and void.
• Many of them also offer extended data types such as long int and long
double.
PRIMARY DATA TYPES
Primary Data Type
• Every C compiler supports following primary data types.
Various Data types
• The range of the basic four types.
NUMERIC DATA TYPES
INTERGER
Integer Data Type
• Integers are used to store whole numbers.
• The integer occupy one word of storage typically 16 bits.
• The size of the integer is 2 bytes.
• ‘int’ is used to define integer number. Format specifier is %d.

Syntax Example

int variable_name; int number;


int sum;
Integer Data Type (Cont..)
• C has three classes of integer storage, namely short int, int, and long int, in
both signed and unsigned forms.

• Short int represents small integer values and requires half the amount of
storage as a regular int number uses.
• Unsigned integers use all the bits for the magnitude of the number and are
always positive.
• Long and unsigned integers to increase the range of values.
Integer Data Type (Cont..)
• Size and range of Integer type on 16-bit machine
NUMERIC DATA TYPES
FLOATING POINT
Floating Point Data Type
• Floating point data types are used to store real numbers.
• The floating point numbers are generally stored in 32 bits with the 6 digits
of precision.
• These numbers are defined by using the keyword float.
• The format specifier is %f.

Syntax Example
float variable_name; float number;
double price;
Floating Point Data Type (Cont…)
• The type double can be used to define the number. A double data type
number uses 64 bits giving a precision of 14 digits. These are known as
double precision numbers.
• The double type represents the same data type that float represents, but
with a greater precision.
• To extend the precision further, we may use long double which uses 80
bits.
Floating Point Data Type (Cont..)
• Size and range of Integer type on 16-bit machine
NON – NUMERIC DATA
TYPES: CHAR
Character Data Type
• Character data type is used to store character value.
• ASCII character set is considered as the character data type.
• The size of the character data type is one byte.
• It is represented by the key word ‘char’. Char defines character.
• At compile time, all the character literals are converted into their
corresponding integer values.
• Character is stored in 8 bits of the internal storage of computer.
Syntax Example

char variable_name; char letter;


letter = ‘x’;
Character Data Type (Cont..)
• Characters are usually stored in 8 bits (one byte) of internal storage.
• The qualifier signed or unsigned may be explicitly applied to char.
• While unsigned chars have values between 0 and 255, signed chars have values from –128 to 127.
NON – NUMERIC DATA
TYPES: STRING
String
• Strings are defined as an array of characters.
• The difference between a character array and a string is the string is
terminated with a special character ‘\0’.
• Declaring a string is as simple as declaring a one dimensional array.

Syntax Example

char variable_name[size]; char str_name[20];


str_name[20] = “string”;
String Cont..)
• A strings can be initialized in different ways.
String Cont..)
• Memory representation of the String
VOID
Void
• The void type has no values. This is usually used to specify the type of
functions.
• The type of a function is said to be void when it does not return any value
to the calling function.
• It can also play the role of a generic type, meaning that it can represent any
of the other standard types.
Void - Types
DERIVED DATA TYPES
Derived Data Types
• Data types that are derived from fundamental data types are derived
types.
• C supports three derived data types.
USER DEFINED DATA
TYPES
User Defined Data Types
• C allows the feature called type definition which allows programmers to
define their identifier that would represent an existing data type.
• There are three such types.
INCREMENT &
DECREMENT OPERATOR
Increment & Decrement Operators
• C allows two very useful operators not generally found in other
languages.
• These are the increment and decrement operators: ++ and –
• The operator ++ adds 1 to the operand, while – – subtracts 1. Both are
unary operators and takes the following form:

• We use the increment and decrement statements in for and while loops
extensively.
Increment Operators
• The increment operator is used to Example
increment the value of a variable in
an expression.
• In the Pre-Increment, value is first
incremented and then used inside
the expression.
• In the Post-Increment, value is first
used inside the expression and
then incremented.
++m; // Prefix Output
m++; // Postfix 5
6
Decrement Operators
• The decrement operator is used to Example
decrement the value of a variable
in an expression.
• In the Pre-Decrement, value is first
decremented and then used inside
the expression.
• In the Post-Decrement, value is
first used inside the expression and
then decremented.
--m; // Prefix Output
m--; // Postfix 5
4
Difference between Increment & Decrement Operators
Increment Operator Decrement Operator
• Increment Operator adds 1 to the • Decrement Operator subtracts 1 from the
operand. operand.
• Postfix increment operator means the • Postfix decrement operator means the
expression is evaluated first using the expression is evaluated first using the
original value of the variable and then the original value of the variable and then the
variable is incremented(increased). variable is decremented(decreased).
• Prefix increment operator means the • Prefix decrement operator means the
variable is incremented first and then the variable is decremented first and then the
expression is evaluated using the new expression is evaluated using the new
value of the variable. value of the variable.
• Generally, we use this in decision making • This is also used in decision making and
and looping. looping.
Rules for ++ and -- operators

• Increment and decrement operators are unary operators and they require
variable as their operands.
• When postfix ++ (or – –) is used with a variable in an expression, the
expression is evaluated first using the original value of the variable and
then the variable is incremented (or decremented) by one.
• When prefix ++(or – –) is used in an expression, the variable is incremented
(or decremented) first and then the expression is evaluated using the new
value of the variable.
• The precedence and associatively of ++ and – – operators are the same as
those of unary + and unary –.
COMMA OPERATOR
Comma Operator
• The comma operator is used to separate the statement elements such as
variables, constants and expressions etc.
• This operator is used to link the related expressions together.
• This expression can be evaluated from left to right and the value of right
most expression is the value of combined expression.
Example
val = (a=3, b=9, c=77, a+c);
where, First assigns the value 3 to a
Then assigns the value 9 to b
Then assigns the value 77 to c
Finally assigns value 80 to val
ARROW OPERATOR
Arrow Operator
• An arrow operator allows to access elements in structure and union.
• It is used with a pointer variable pointing to a structure and union.
• The arrow operator is formed by using a minus sign, followed by the
greater than symbols.

Syntax
pointer_name -> variable_name

Example
emp -> age = 18;
ASSIGNMENT OPERATOR
Assignment Operator
• Assignment operators are used to assigning value to a variable.
• The left side operand of the assignment operator is a variable and right
side operand of the assignment operator is a value.
• The value on the right side must be of the same data-type of the variable
on the left side otherwise the compiler will raise an error.
Assignment Operator - Example
Program

Output
BITWISE OPERATOR
Bitwise Operator
• Bitwise Operators are used for manipulating data at the bit level, also
called bit level programming.
• Bitwise operates on one or more bit patterns or binary numerals at the
level of their individual bits.
• They are used in numerical computations to make the calculation process
faster.
Bitwise Operator (Cont..)
AND (&) operator OR (|) Operator
• The output of bitwise AND is 1 if the • The output of bitwise OR is 1 if at least
corresponding bits of two operands is 1. one corresponding bit of two operands is
• If either bit of an operand is 0, the result 1.
of corresponding bit is evaluated to 0. • In C Programming, bitwise OR operator is
• Let us suppose the bitwise AND denoted by |.
operation of two integers 12 and 25.
Bitwise Operator (Cont..)
XOR (^) operator Complement (~) Operator
• The result of bitwise XOR operator • Bitwise compliment operator is an
is 1 if the corresponding bits of unary operator (works on only one
two operands are opposite. operand).
• It is denoted by ^. • It changes 1 to 0 and 0 to 1. It is
denoted by ~.
Bitwise Operator (Cont..)
Right Shift (>>) Operator Left Shift (<<) Operator
• Right shift operator shifts all bits • Left shift operator shifts all bits towards
towards right by certain number of left by a certain number of specified bits.
specified bits. • The bit positions that have been vacated
by the left shift operator are filled with 0.
• It is denoted by >>.
• The symbol of the left shift operator is <<.
Bitwise Operator (Cont..)
SIZEOF OPERATOR
Sizeof() Operator
• The sizeof() operator is commonly used in C.
• It determines the size of the expression or the data type specified in the
number of char-sized storage units.
• The sizeof() operator contains a single operand which can be either an
expression or a data typecast where the cast is data type enclosed within
parenthesis.
• The data type cannot only be primitive data types such as integer or
floating data types, but it can also be pointer data types and compound
data types such as unions and structs.
Need of Sizeof() Operator
• Programs know the storage size of the primitive data types.
• Though the storage size of the data type is constant, it varies when
implemented in different platforms.
• For example, we dynamically allocate the array space by
using sizeof() operator:

• In the above example, we use the sizeof() operator, which is applied to the
cast of type int.
• We use malloc() function to allocate the memory and returns the pointer
which is pointing to this allocated memory.
• The memory space is equal to the number of bytes occupied by the int
data type and multiplied by 10.

You might also like