Unit 1
Unit 1
Unit 1
PROGRAMMING FOR
PROBLEM SOLVING
UNIT 1
Course Learning Outcome (CLO – 1)
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)
• 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.
UNIT 1
Course Learning Outcome (CLO – 1)
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..)
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..)
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;
UNIT 1
Course Learning Outcome (CLO – 1)
• Expressions
• Single Line and Multiline comments
• Constants
• Keywords
• Binding
• Storage classes
STUCTURE OF ‘C’
PROGRAMMING
Introduction
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
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
Example:
“green”, “Washington, D.C.2005”, “270-32-3450”, “ ”
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.
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)
• 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
• 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
Syntax Example
• 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.