SlideShare a Scribd company logo
1 of 74
PROGRAMMING FOR
PROBLEM SOLVING IN C
UNIT – I
Algorithms, building blocks of algorithms
(Statements, State, Control flow, Functions),
notation (Pseudo code, Flow Chart, Programming
language), algorithmic problem solving, simple
strategies for developing algorithms (iteration,
recursion). Introduction to C Programming – Data
types - Operators and Expressions – Data Input
and Output – Decision making and Looping
Statements.
Prepared By,
S.SRIDEVI, CSE
Introduction to C
 Ken Thompson at Bell Labs, USA,
wrote his own variant over Martin
Richards’s Basic Combined
Programming Language and called it
B .
 Dennis Ritchie, at Bell Labs, is
credited for designing C in the early
1970s.
Why learn C?
a. C is quick.
b. C is a core language : In computing,
C is a general purpose, cross-
platform, block structured procedural,
imperative computer programming
language.
c. C is a small language: C has only
thirty-two keywords. This makes it
relatively easy to learn compared to
bulkier languages.
d. C is portable
Steps in executing a C
program
Structure of a C program
Standard Header Files
Variable
 A variable is an identifier for a memory
location in which data can be stored
and subsequently recalled.
 Variables are used for holding data
values so that they can utilized in
various computations in a program.
 data_type variable_name = value;
Datatypes
Basic Data types – Size and
Range
16 bit computer:
32 bit computer:
Specifiers or Modifiers
 In addition, C has four type specifiers or modifiers and
three type qualifiers.
Each of these type modifiers can be applied
to the base type int.
The modifiers signed and unsigned can also
be applied to the base type char.
In addition, long can be applied to double.
When the base type is omitted from a
declaration, int is assumed.
The type void does not have these
modifiers.
Specifiers: Data Types
 The specifiers and qualifiers for the data types can be broadly
classified into three types:
Size specifiers— short and long
Sign specifiers— signed and unsigned
 Type qualifiers— const, volatile and restrict
Program Statements
 A statement is a syntactic constructions that
performs an action when a program is
executed. All C program statements are
terminated with a semi-colon (;).
Program Statements
 Declaration :It is a program statement that serves
to communicate to the language translator
information about the name and type of the data
objects needed during program execution.
 Expression statement: It is the simplest kind of
statement which is no more than an expression
followed by a semicolon. An expression is a
sequence of operators and operands that specifies
computation of a value . Example :x = 4
 Compound statement is a sequence of
statements that may be treated as a single
statement in the construction of larger statements.
 Labelled statements can be used to mark any
statement so that control may be transferred to
the statement by switch statement.
Program Statements
 Control statement is a statement whose execution
results in a choice being made as to which of two or
more paths should be followed. In other words, the
control statements determine the ‘flow of control’ in a
program.
Selection statements allow a program to select a
particular execution path from a set of one or more
alternatives. Various forms of the if..else statement
belong to this category.
Iteration statements are used to execute a group
of one or more statements repeatedly. “while, for,
and do..while” statements falls under this group.
Jump statements cause an unconditional jump to
some other place in the program. Goto statement
Tokens
 The basic lexical building blocks of source
code.
 Five classes of tokens
 Identifier
 Keywords
 Operators
 Separators
 Constant
Identifiers
 An identifier or name is a sequence of
characters created by the programmer to
identify a name or specific object.
 In C, variables, arrays, functions and labels are
named.
 Rules:
First character – alphabet or underscore
_
All characters – alphabets, digits or _
First 31 characters are significant
An identifier cannot duplicate a
Keywords
 Keywords form the vocabulary of C.
 They have predefined uses and cannot be
used for any other purpose in a C program.
 They are always written in lowercase letters.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Constants
 A constant is an explicit data value written by the
programmer. Thus, it is a value known to the compiler
at compiling time.
Operators in C
Different Operators
Arithmetic Operators
 There are three types of arithmetic operators in C:
binary, unary, and ternary.
 Binary operators: C provides five basic arithmetic
binary operators.
 Arithmetic binary operators:
 Unary operators: The unary ‘–’ operator negates the
value of its operand (clearly, a signed number). A numeric
constant is assumed positive unless it is preceded by the
negative operator. That is, there is no unary ‘+’. It is
implicit. Remember that -x does not change the value of x
at the location where it permanently resides in memory.
 Unary increment and decrement operators ‘++’ and ‘--’
operators increment or decrement the value in a variable
by 1.
 Basic rules for using ++ and – – operators:
The operand must be a variable but not a constant or an
expression.
 The operator ++ and -- may precede or succeed the
operand.
Unary Operators
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.
Postfix
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.
Prefix
 C provides six relational operators for comparing
numeric quantities. Relational operators evaluate to 1,
representing the true outcome, or 0, representing the
false outcome.
Relational Operators
 C provides three logical operators for forming logical
expressions. Like the relational operators, logical
operators evaluate to 1 or 0.
Logical negation is a unary operator that negates the
logical value of its single operand. If its operand is non-
zero, it produces 0, and if it is 0, it produces 1.
Logical AND produces 0 if one or both its operands
evaluate to 0. Otherwise, it produces 1.
Logical OR produces 0 if both its operands evaluate to
0. Otherwise , it produces 1.
Logical Operators
 C provides six bitwise operators for manipulating the
individual bits in an integer quantity . Bitwise operators
expect their operands to be integer quantities and treat
them as bit sequences.
Bitwise negation is a unary operator that complements
the bits in its operands.
Bitwise AND compares the corresponding bits of its
operands and produces a 1 when both bits are 1, and 0
otherwise.
 Bitwise OR compares the corresponding bits of its
operands and produces a 0 when both bits are 0, and 1
otherwise.
Bitwise exclusive or compares the corresponding bits of
its operands and produces a 0 when both bits are 1 or
both bits are 0, and 1 otherwise.
Bitwise Operators
Bitwise Operators
 The conditional operator has three expressions.
 It has the general form expression1 ?
expression2 : expression3
First, expression1 is evaluated; it is treated as a
logical condition.
If the result is non-zero, then expression2 is
evaluated and its value is the final result.
Otherwise, expression3 is evaluated and its value
is the final result.
 For example,int m = 1, n = 2, min;
min = (m < n ? m : n); /* min is assigned a value 1 */
 In the above example, because m is less than n,
m<n expression evaluates to be true, therefore, min
is assigned the value m, i.e., 1.
Conditional Operators
 This operator allows the evaluation of
multiple expressions, separated by the
comma, from left to right in order and the
evaluated value of the rightmost expression
is accepted as the final result. The general
form of an expression using a comma
operator is
 Expression M = (expression1, expression2,
…,expression N);
 where the expressions are evaluated strictly
from left to right and their values discarded,
except for the last one, whose type and value
determine the result of the overall
Comma Operator
 C provides a useful operator, sizeof, for calculating the size of an
data item or type. It takes a single operand that may be a type name
(e.g., int) or an expression (e.g.,100) and returns the size of the
specified entity in bytes .The outcome is totally machine-dependent
For example:
sizeof Operators
 Evaluation of an expression in
C is very important to
understand. Unfortunately
there is no ‘BODMAS’ rule in C
language as found in algebra.
 The precedence of operators
determines the order in which
different operators are
evaluated when they occur in
the same expression.
Operators of higher
precedence are applied before
operators of lower
precedence.
Expression Evaluation:
Precedence and Associativity
Example: Precedence
Operator
 An l- value is an expression to which a value can be
assigned.
 An r- value can be defined as an expression that can be
assigned to an l- value.
 The l- value expression is located on the left side of an
assignment statement, whereas an r- value is located on
the right side of an assignment statement.
 The address associated with a program variable in C is
called its l- value; the contents of that location are its r-
value, the quantity that is supposed to be the value of
the variable.
 The r- value of a variable may change as program
execution proceeds; but never its l- value. The distinction
between l- values and r- values becomes sharper if one
l-value & r-value
 For example :
a = b;
b, on the right-hand side of
the assignment operator, is
the quantity to be found at
the address associated
with b, i.e., an r- value. a is
assigned the value stored
in the address associated
with b. a, on the left-hand
side, is the ad dress at
which the contents are
altered as a result of the
assignment. a is an l-
value. The assignment
operation deposits b’s r-
value at a’s l- value.
© Oxford University Press 2013. All rights reserved.
l-value & r-value
 Generally ,standard input and output devices
are the keyboard and the screen.
 To carry out the input and output, a number of
standard functions such as getchar(),putchar(),
scanf(), and printf() are in-built in C.
 getchar() and putchar() functions are single-
character input and output functions
respectively. So, these do not need any
formatted inputs or outputs.
 The functions scanf() and printf() handle
multiple variables of all the allowed data types in
Input and Output
 Non-formatted input and output can be carried out by
standard input-output library functions in C. These can
handle one character at a time. For the input functions it
does not require <Enter> to be pressed after the entry
of the character.
 A number of functions provide for character-oriented
input and output. The declarations format of two of these
are given as follows:
int getchar(void);(function for character input)
int putchar(int c);(function of character output)
Non-formatted I/O
 getchar() is an input function that reads a single
character from the standard input device,
normally a keyboard.
 putchar() is an output function that writes a
single character on the standard output device,
the display screen.
 There are two other functions, gets() and puts(),
that are used to read and write strings from and
to the keyboard and the display screen
respectively. A string may be defined as an
arranged collection of characters.
Non-formatted I/O function
 When input and output is required in a specified format
the standard library functions scanf() and printf() are
used.
 The scanf() function allows the user to input data in a
specified format. It can accept data of different data
types .
The printf() function allows the user to output data of
different data types on the console in a specified
format.
 The format string in printf(), enclosed in quotation
marks, has three types of objects:
 Ordinary characters: these are copied to output,
 Conversion specifier field: denoted by % containing
Formatted I/O function
Format specifiers for
printf()
Example
Example
 The scanf() function works in much the same way as the
printf(). It has the general form :
scanf(“control_string”,variable1_address,variable2_
address,..);
 In scanf(), the control string or format string, that
consists of a list of format specifiers, indicates the
format and type of data to be read in from the standard
input device, which is the keyboard, for storing in the
corresponding address of variables specified.
 There must be the same number of format specifiers
and addresses as there are input fields.
 scanf() returns the number of input fields successfully
scanned, converted, and stored.
 If scanf() attempts to read end-of-file, the return value is
EOF. If no fields were stored, the return value is 0.
Input function: scanf()
 1.The scanf() function returns the number
of variables successfully read in.
 2. The printf() function returns a number
that is equal to the number of characters
printed.
scanf() vs. printf()
CONTROL STATEMENTS
Selection
Statements
• if
• if-else
• switch
Iteration
Statements
• for
• while
• do-while
Jump
Statements
• goto
• break
• continue
• return
CONTROL STATEMENTS
Program Control
Statements/Construct
s
Selection/Branching
Conditional
Type
if
if-
else
if-
else-
if
switc
h
Unconditional
Type
break continu
e
goto
Iteration/Loopin
g
for while
do-
while
Operators for Control
Statements
Operators
<
>
<=
>=
!=
==
||
&&
!
Points to Note
 If an expression, involving the relational operator, is
true, it is given a value of 1. If an expression is false, it
is given a value of 0. Similarly, if a numeric expression
is used as a test expression, any non-zero value
(including negative) will be considered as true, while a
zero value will be considered as false.
 Space can be given between operand and operator
(relational or logical) but space is not allowed between
any compound operator like <=, >=, ==, !=. It is also
compiler error to reverse them.
 a == b and a = b are not similar, as == is a test for
equality, a = b is an assignment operator. Therefore, the
equality operator has to be used carefully.
 The relational operators have lower precedence than all
arithmetic operators.
Selection Statements
 One-way decisions using if statement
 Two-way decisions using if-else statement
 Multi-way decisions
 Dangling else Problem
One-way decisions using if statement
Flowchart for if construct
if(TestExpr)
stmtT; T F
TestExpr
stmtT
Example : if
Algorithm C Program
1. START #include <stdio.h>
int main()
{
int a, b, c, max;
printf(“nEnter 3 numbers”);
scanf(“%d %d %d”, &a, &b, &c);
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
printf(“Largest No is %d”, max);
return 0;
}
2. PRINT “ENTER THREE
NUMBERS”
3. INPUT A, B, C
4. MAX=A
5. IF B>MAX THEN MAX=B
6. IF C>MAX THEN MAX=C
7. PRINT “LARGEST
NUMBER IS”, MAX
8. STOP
Flowchart of if-else construct
The form of a two-way decision
is as follows:
if(TestExpr)
stmtT;
else
stmtF;
TestExpr
stmtT stmtF
two-way decisions using if-else
statement
if-else-if ladder General format of switch
statements
if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
.. .
else if(TestExprN)
stmtTN;
else
stmtF;
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
Multi way Decisions
Flowchart of an if-else-if Construct
TestExpr
TestExpr2
TestExprN
TestExpr3
stmtT2
stmtTN
stmtT3
stmtTF
stmtT1
Nested if
 When any if statement is
written under another if
statement, this cluster is
called a nested if.
 The syntax for the nested
is given here:
Construct 1 Construct 2
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
stmtAF;
if(TestExprA)
if(TestExprB)
stmtBT;
else
stmtBF;
else
if(TestExprC)
stmtCT;
else
stmtCF;
Nested if
A program to find the largest among three
numbers using the nested loop
#include <stdio.h>
int main()
{
int a, b, c;
printf(“nEnter the three
numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
 This classic problem occurs
when there is no matching else
for each if. To avoid this problem,
the simple C rule is that always
pair an else to the most recent
unpaired if in the current block.
Consider the illustration shown
here.
 The else is automatically paired
with the closest if. But, it may be
needed to associate an else with
the outer if also.
Dangling else Problem
 Use of null else
 Use of braces to
enclose the true
action of the
second if
With null
else
With braces
if(TestExprA)
if(TestExprB)
stmtBT;
else
;
else
stmtAF;
if(TestExprA)
{
if(TestExprB)
stmtBT;
}
else
stmtAF;
Solution to Dangling Else Problem
The C switch construct
The general format of a switch
statement is
switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
………………………….
………………………….
default: stmtListn;
}
The Switch Statement
Switch Vs. Nested if
 The switch differs from the else-if in that
switch can test only for equality, whereas the
if conditional expression can be of a test
expression involving any type of relational
operators and/or logical operators.
 A switch statement is usually more efficient
than nested ifs.
 The switch statement can always be replaced
with a series of else-if statements.
 A loop allows one to
execute a statement or
block of statements
repeatedly. There are
mainly two types of
iterations or loops –
unbounded iteration or
unbounded loop and
bounded iteration or
bounded loop.
 A loop can either be a pre-
test loop or be a post-test
loop as illustrated in the
diagram.
Iteration & Repetitive Execution
Expanded Syntax of “while” and its Flowchart
Representation
while statement is a
pretest loop. The basic
syntax of the while
statement is shown
below:
“While” Construct
An Example
#include <stdio.h>
int main()
{
int c;
c=5; // Initialization
while(c>0)
{ // Test Expression
printf(“ n %d”,c);
c=c-1; // Updating
}
return 0;
}
This loop contains all the
parts of a while loop. When
executed in a program, this
loop will output
5
4
3
2
1
An Example
“for” Construct
 The general form of the for statement is
as follows:
for(initialization; TestExpr; updating)
stmT;
An Example
#include <stdio.h>
int main()
{
int i,n;
printf(“Enter the number”);
scanf(“%d”,&n);
for(i = 0; i < n; i++)
printf(“ %dn”,i);
return 0;
}
This loop contains all the
parts of a for loop. When
executed in a program, this
loop will output
0
1
2
3
4
An Example
The C do-while loop
The form of this loop
construct is as
follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr);
“do-while” Construct
Point to Note
With a do-while statement, the body of the
loop is executed first and the test
expression is checked after the loop body
is executed. Thus, the do-while statement
always executes the loop body at least
once.
An Example
#include <stdio.h>
int main()
{
int n = 5;
do
{
printf(“HELLO”);
n++;
}while(n <= 5);
return 0;
}
This loop contains all the
parts of a do-while loop.
When executed in a
program, this loop will
output
HELLO
An Example
The control is
unconditionally
transferred to the
statement associated
with the label specified in
the goto statement. The
form of a goto statement
is
goto label_name;
The following program is used
to find the factorial of a
number.
#include <stdio.h>
int main()
{
int n, c, f=1;
printf(“n Enter the number:”);
scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“n FACTORIAL IS %d”, f);
end:
return 0;
}
goto Statement
SPECIAL CONTROL STATEMENTS
 “return” statements
 “break” statements
 “continue” statements
return statement
 The return type is used in the definition of
a function to set its returned value and the
return statement is used to terminate
execution of the function.
 Syntax
 return;
 return expression;
“break” & “continue” statements
break continue
1. It helps to make an early
exit from the block where it
appears.
1. It helps in avoiding the
remaining statements in a
current iteration of the loop
and continuing with the next
Iteration
2. It can be used in all control
statements including switch
construct.
2. It can be used only in loop
constructs.
#include<stdio.h>
int main()
{
int c = 1;
while(c <= 5)
{
if(c == 3)
break;
printf(“t%d”, c);
c++;
}
return 0;
}
Output: 1 2
#include<stdio.h>
int main()
{
int c = 1;
while(c <= 5)
{
if(c == 3)
continue;
printf(“t%d”, c);
c++;
}
return 0;
}
Output: 1 2 4 5
 A nested loop refers to a
loop that is contained
within another loop.
 If the following output has
to be obtained on the
screen
1
2 2
3 3 3
4 4 4 4
then the corresponding
program will be
#include <stdio.h>
int main()
{
int row, col;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
printf(“%d t”, row);
printf(“n”);
}
return 0;
}
Nested Loops

More Related Content

What's hot

Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computerKamal Acharya
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler DesignKuppusamy P
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignKuppusamy P
 
Code generator
Code generatorCode generator
Code generatorTech_MX
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
Basic Structure of a Computer System
Basic Structure of a Computer SystemBasic Structure of a Computer System
Basic Structure of a Computer SystemAmirthavalli Senthil
 
Data flow model -Lecture-4
Data flow model -Lecture-4Data flow model -Lecture-4
Data flow model -Lecture-4Dr.YNM
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Keyappasami
 
Verilog data types -For beginners
Verilog data types -For beginnersVerilog data types -For beginners
Verilog data types -For beginnersDr.YNM
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)bolovv
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question keyArthyR3
 
Compiler worksheet
Compiler worksheetCompiler worksheet
Compiler worksheetArthyR3
 
system software 16 marks
system software 16 markssystem software 16 marks
system software 16 marksvvcetit
 
Verilog operators
Verilog operatorsVerilog operators
Verilog operatorsDr.YNM
 
Assemblers: Ch03
Assemblers: Ch03Assemblers: Ch03
Assemblers: Ch03desta_gebre
 

What's hot (20)

Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computer
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
Code generator
Code generatorCode generator
Code generator
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Basic Structure of a Computer System
Basic Structure of a Computer SystemBasic Structure of a Computer System
Basic Structure of a Computer System
 
Data flow model -Lecture-4
Data flow model -Lecture-4Data flow model -Lecture-4
Data flow model -Lecture-4
 
Cs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer KeyCs6660 compiler design may june 2016 Answer Key
Cs6660 compiler design may june 2016 Answer Key
 
Verilog data types -For beginners
Verilog data types -For beginnersVerilog data types -For beginners
Verilog data types -For beginners
 
Handout#08
Handout#08Handout#08
Handout#08
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Compiler worksheet
Compiler worksheetCompiler worksheet
Compiler worksheet
 
system software 16 marks
system software 16 markssystem software 16 marks
system software 16 marks
 
Verilog operators
Verilog operatorsVerilog operators
Verilog operators
 
Assemblers: Ch03
Assemblers: Ch03Assemblers: Ch03
Assemblers: Ch03
 

Similar to C basics

Fundamentals of c language
Fundamentals of c languageFundamentals of c language
Fundamentals of c languageAkshhayPatel
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III TermAndrew Raj
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdfShivamYadav886008
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdfHome
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptxAnisZahirahAzman
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++Aahwini Esware gowda
 
Programming presentation
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
 

Similar to C basics (20)

C program
C programC program
C program
 
C programming
C programming C programming
C programming
 
C material
C materialC material
C material
 
Fundamentals of c language
Fundamentals of c languageFundamentals of c language
Fundamentals of c language
 
Basic Of C language
Basic Of C languageBasic Of C language
Basic Of C language
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdf
 
C intro
C introC intro
C intro
 
Basics of c
Basics of cBasics of c
Basics of c
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
c programming2.pptx
c programming2.pptxc programming2.pptx
c programming2.pptx
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptx
 
2nd PUC Computer science chapter 5 review of c++
2nd PUC Computer science chapter 5   review of c++2nd PUC Computer science chapter 5   review of c++
2nd PUC Computer science chapter 5 review of c++
 
Pc module1
Pc module1Pc module1
Pc module1
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
Unit 1
Unit 1Unit 1
Unit 1
 

More from sridevi5983

Geographic Information System unit 5
Geographic Information System   unit 5Geographic Information System   unit 5
Geographic Information System unit 5sridevi5983
 
Geographic Information System unit 2
Geographic Information System unit 2Geographic Information System unit 2
Geographic Information System unit 2sridevi5983
 
Geographic Information System unit 1
Geographic Information System   unit 1Geographic Information System   unit 1
Geographic Information System unit 1sridevi5983
 
Principles of Management unit 5
Principles of Management  unit 5Principles of Management  unit 5
Principles of Management unit 5sridevi5983
 
Principles of Management unit 4
Principles of Management   unit 4Principles of Management   unit 4
Principles of Management unit 4sridevi5983
 
Principles of Management unit 3
Principles of Management   unit 3Principles of Management   unit 3
Principles of Management unit 3sridevi5983
 
Principles of Management unit 2
Principles of Management  unit 2Principles of Management  unit 2
Principles of Management unit 2sridevi5983
 
Principles of Management unit 1
Principles of Management   unit 1Principles of Management   unit 1
Principles of Management unit 1sridevi5983
 

More from sridevi5983 (9)

Geographic Information System unit 5
Geographic Information System   unit 5Geographic Information System   unit 5
Geographic Information System unit 5
 
Gis unit 3
Gis   unit 3Gis   unit 3
Gis unit 3
 
Geographic Information System unit 2
Geographic Information System unit 2Geographic Information System unit 2
Geographic Information System unit 2
 
Geographic Information System unit 1
Geographic Information System   unit 1Geographic Information System   unit 1
Geographic Information System unit 1
 
Principles of Management unit 5
Principles of Management  unit 5Principles of Management  unit 5
Principles of Management unit 5
 
Principles of Management unit 4
Principles of Management   unit 4Principles of Management   unit 4
Principles of Management unit 4
 
Principles of Management unit 3
Principles of Management   unit 3Principles of Management   unit 3
Principles of Management unit 3
 
Principles of Management unit 2
Principles of Management  unit 2Principles of Management  unit 2
Principles of Management unit 2
 
Principles of Management unit 1
Principles of Management   unit 1Principles of Management   unit 1
Principles of Management unit 1
 

Recently uploaded

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 

Recently uploaded (20)

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

C basics

  • 1. PROGRAMMING FOR PROBLEM SOLVING IN C UNIT – I Algorithms, building blocks of algorithms (Statements, State, Control flow, Functions), notation (Pseudo code, Flow Chart, Programming language), algorithmic problem solving, simple strategies for developing algorithms (iteration, recursion). Introduction to C Programming – Data types - Operators and Expressions – Data Input and Output – Decision making and Looping Statements. Prepared By, S.SRIDEVI, CSE
  • 2. Introduction to C  Ken Thompson at Bell Labs, USA, wrote his own variant over Martin Richards’s Basic Combined Programming Language and called it B .  Dennis Ritchie, at Bell Labs, is credited for designing C in the early 1970s.
  • 3. Why learn C? a. C is quick. b. C is a core language : In computing, C is a general purpose, cross- platform, block structured procedural, imperative computer programming language. c. C is a small language: C has only thirty-two keywords. This makes it relatively easy to learn compared to bulkier languages. d. C is portable
  • 4. Steps in executing a C program
  • 5. Structure of a C program
  • 7. Variable  A variable is an identifier for a memory location in which data can be stored and subsequently recalled.  Variables are used for holding data values so that they can utilized in various computations in a program.  data_type variable_name = value;
  • 9. Basic Data types – Size and Range 16 bit computer: 32 bit computer:
  • 10. Specifiers or Modifiers  In addition, C has four type specifiers or modifiers and three type qualifiers. Each of these type modifiers can be applied to the base type int. The modifiers signed and unsigned can also be applied to the base type char. In addition, long can be applied to double. When the base type is omitted from a declaration, int is assumed. The type void does not have these modifiers.
  • 11. Specifiers: Data Types  The specifiers and qualifiers for the data types can be broadly classified into three types: Size specifiers— short and long Sign specifiers— signed and unsigned  Type qualifiers— const, volatile and restrict
  • 12. Program Statements  A statement is a syntactic constructions that performs an action when a program is executed. All C program statements are terminated with a semi-colon (;).
  • 13. Program Statements  Declaration :It is a program statement that serves to communicate to the language translator information about the name and type of the data objects needed during program execution.  Expression statement: It is the simplest kind of statement which is no more than an expression followed by a semicolon. An expression is a sequence of operators and operands that specifies computation of a value . Example :x = 4  Compound statement is a sequence of statements that may be treated as a single statement in the construction of larger statements.  Labelled statements can be used to mark any statement so that control may be transferred to the statement by switch statement.
  • 14. Program Statements  Control statement is a statement whose execution results in a choice being made as to which of two or more paths should be followed. In other words, the control statements determine the ‘flow of control’ in a program. Selection statements allow a program to select a particular execution path from a set of one or more alternatives. Various forms of the if..else statement belong to this category. Iteration statements are used to execute a group of one or more statements repeatedly. “while, for, and do..while” statements falls under this group. Jump statements cause an unconditional jump to some other place in the program. Goto statement
  • 15. Tokens  The basic lexical building blocks of source code.  Five classes of tokens  Identifier  Keywords  Operators  Separators  Constant
  • 16. Identifiers  An identifier or name is a sequence of characters created by the programmer to identify a name or specific object.  In C, variables, arrays, functions and labels are named.  Rules: First character – alphabet or underscore _ All characters – alphabets, digits or _ First 31 characters are significant An identifier cannot duplicate a
  • 17. Keywords  Keywords form the vocabulary of C.  They have predefined uses and cannot be used for any other purpose in a C program.  They are always written in lowercase letters. auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
  • 18. Constants  A constant is an explicit data value written by the programmer. Thus, it is a value known to the compiler at compiling time.
  • 21. Arithmetic Operators  There are three types of arithmetic operators in C: binary, unary, and ternary.  Binary operators: C provides five basic arithmetic binary operators.  Arithmetic binary operators:
  • 22.  Unary operators: The unary ‘–’ operator negates the value of its operand (clearly, a signed number). A numeric constant is assumed positive unless it is preceded by the negative operator. That is, there is no unary ‘+’. It is implicit. Remember that -x does not change the value of x at the location where it permanently resides in memory.  Unary increment and decrement operators ‘++’ and ‘--’ operators increment or decrement the value in a variable by 1.  Basic rules for using ++ and – – operators: The operand must be a variable but not a constant or an expression.  The operator ++ and -- may precede or succeed the operand. Unary Operators
  • 23. 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. Postfix
  • 24. 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. Prefix
  • 25.  C provides six relational operators for comparing numeric quantities. Relational operators evaluate to 1, representing the true outcome, or 0, representing the false outcome. Relational Operators
  • 26.  C provides three logical operators for forming logical expressions. Like the relational operators, logical operators evaluate to 1 or 0. Logical negation is a unary operator that negates the logical value of its single operand. If its operand is non- zero, it produces 0, and if it is 0, it produces 1. Logical AND produces 0 if one or both its operands evaluate to 0. Otherwise, it produces 1. Logical OR produces 0 if both its operands evaluate to 0. Otherwise , it produces 1. Logical Operators
  • 27.  C provides six bitwise operators for manipulating the individual bits in an integer quantity . Bitwise operators expect their operands to be integer quantities and treat them as bit sequences. Bitwise negation is a unary operator that complements the bits in its operands. Bitwise AND compares the corresponding bits of its operands and produces a 1 when both bits are 1, and 0 otherwise.  Bitwise OR compares the corresponding bits of its operands and produces a 0 when both bits are 0, and 1 otherwise. Bitwise exclusive or compares the corresponding bits of its operands and produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise. Bitwise Operators
  • 29.  The conditional operator has three expressions.  It has the general form expression1 ? expression2 : expression3 First, expression1 is evaluated; it is treated as a logical condition. If the result is non-zero, then expression2 is evaluated and its value is the final result. Otherwise, expression3 is evaluated and its value is the final result.  For example,int m = 1, n = 2, min; min = (m < n ? m : n); /* min is assigned a value 1 */  In the above example, because m is less than n, m<n expression evaluates to be true, therefore, min is assigned the value m, i.e., 1. Conditional Operators
  • 30.  This operator allows the evaluation of multiple expressions, separated by the comma, from left to right in order and the evaluated value of the rightmost expression is accepted as the final result. The general form of an expression using a comma operator is  Expression M = (expression1, expression2, …,expression N);  where the expressions are evaluated strictly from left to right and their values discarded, except for the last one, whose type and value determine the result of the overall Comma Operator
  • 31.  C provides a useful operator, sizeof, for calculating the size of an data item or type. It takes a single operand that may be a type name (e.g., int) or an expression (e.g.,100) and returns the size of the specified entity in bytes .The outcome is totally machine-dependent For example: sizeof Operators
  • 32.  Evaluation of an expression in C is very important to understand. Unfortunately there is no ‘BODMAS’ rule in C language as found in algebra.  The precedence of operators determines the order in which different operators are evaluated when they occur in the same expression. Operators of higher precedence are applied before operators of lower precedence. Expression Evaluation: Precedence and Associativity
  • 34.  An l- value is an expression to which a value can be assigned.  An r- value can be defined as an expression that can be assigned to an l- value.  The l- value expression is located on the left side of an assignment statement, whereas an r- value is located on the right side of an assignment statement.  The address associated with a program variable in C is called its l- value; the contents of that location are its r- value, the quantity that is supposed to be the value of the variable.  The r- value of a variable may change as program execution proceeds; but never its l- value. The distinction between l- values and r- values becomes sharper if one l-value & r-value
  • 35.  For example : a = b; b, on the right-hand side of the assignment operator, is the quantity to be found at the address associated with b, i.e., an r- value. a is assigned the value stored in the address associated with b. a, on the left-hand side, is the ad dress at which the contents are altered as a result of the assignment. a is an l- value. The assignment operation deposits b’s r- value at a’s l- value. © Oxford University Press 2013. All rights reserved. l-value & r-value
  • 36.  Generally ,standard input and output devices are the keyboard and the screen.  To carry out the input and output, a number of standard functions such as getchar(),putchar(), scanf(), and printf() are in-built in C.  getchar() and putchar() functions are single- character input and output functions respectively. So, these do not need any formatted inputs or outputs.  The functions scanf() and printf() handle multiple variables of all the allowed data types in Input and Output
  • 37.  Non-formatted input and output can be carried out by standard input-output library functions in C. These can handle one character at a time. For the input functions it does not require <Enter> to be pressed after the entry of the character.  A number of functions provide for character-oriented input and output. The declarations format of two of these are given as follows: int getchar(void);(function for character input) int putchar(int c);(function of character output) Non-formatted I/O
  • 38.  getchar() is an input function that reads a single character from the standard input device, normally a keyboard.  putchar() is an output function that writes a single character on the standard output device, the display screen.  There are two other functions, gets() and puts(), that are used to read and write strings from and to the keyboard and the display screen respectively. A string may be defined as an arranged collection of characters. Non-formatted I/O function
  • 39.  When input and output is required in a specified format the standard library functions scanf() and printf() are used.  The scanf() function allows the user to input data in a specified format. It can accept data of different data types . The printf() function allows the user to output data of different data types on the console in a specified format.  The format string in printf(), enclosed in quotation marks, has three types of objects:  Ordinary characters: these are copied to output,  Conversion specifier field: denoted by % containing Formatted I/O function
  • 43.  The scanf() function works in much the same way as the printf(). It has the general form : scanf(“control_string”,variable1_address,variable2_ address,..);  In scanf(), the control string or format string, that consists of a list of format specifiers, indicates the format and type of data to be read in from the standard input device, which is the keyboard, for storing in the corresponding address of variables specified.  There must be the same number of format specifiers and addresses as there are input fields.  scanf() returns the number of input fields successfully scanned, converted, and stored.  If scanf() attempts to read end-of-file, the return value is EOF. If no fields were stored, the return value is 0. Input function: scanf()
  • 44.  1.The scanf() function returns the number of variables successfully read in.  2. The printf() function returns a number that is equal to the number of characters printed. scanf() vs. printf()
  • 45. CONTROL STATEMENTS Selection Statements • if • if-else • switch Iteration Statements • for • while • do-while Jump Statements • goto • break • continue • return
  • 48. Points to Note  If an expression, involving the relational operator, is true, it is given a value of 1. If an expression is false, it is given a value of 0. Similarly, if a numeric expression is used as a test expression, any non-zero value (including negative) will be considered as true, while a zero value will be considered as false.  Space can be given between operand and operator (relational or logical) but space is not allowed between any compound operator like <=, >=, ==, !=. It is also compiler error to reverse them.  a == b and a = b are not similar, as == is a test for equality, a = b is an assignment operator. Therefore, the equality operator has to be used carefully.  The relational operators have lower precedence than all arithmetic operators.
  • 49. Selection Statements  One-way decisions using if statement  Two-way decisions using if-else statement  Multi-way decisions  Dangling else Problem
  • 50. One-way decisions using if statement Flowchart for if construct if(TestExpr) stmtT; T F TestExpr stmtT
  • 51. Example : if Algorithm C Program 1. START #include <stdio.h> int main() { int a, b, c, max; printf(“nEnter 3 numbers”); scanf(“%d %d %d”, &a, &b, &c); max=a; if(b>max) max=b; if(c>max) max=c; printf(“Largest No is %d”, max); return 0; } 2. PRINT “ENTER THREE NUMBERS” 3. INPUT A, B, C 4. MAX=A 5. IF B>MAX THEN MAX=B 6. IF C>MAX THEN MAX=C 7. PRINT “LARGEST NUMBER IS”, MAX 8. STOP
  • 52. Flowchart of if-else construct The form of a two-way decision is as follows: if(TestExpr) stmtT; else stmtF; TestExpr stmtT stmtF two-way decisions using if-else statement
  • 53. if-else-if ladder General format of switch statements if(TestExpr1) stmtT1; else if(TestExpr2) stmtT2; else if(TestExpr3) stmtT3; .. . else if(TestExprN) stmtTN; else stmtF; switch(expr) { case constant1: stmtList1; break; case constant2: stmtList2; break; case constant3: stmtList3; break; …………………………. …………………………. default: stmtListn; } Multi way Decisions
  • 54. Flowchart of an if-else-if Construct TestExpr TestExpr2 TestExprN TestExpr3 stmtT2 stmtTN stmtT3 stmtTF stmtT1
  • 55. Nested if  When any if statement is written under another if statement, this cluster is called a nested if.  The syntax for the nested is given here: Construct 1 Construct 2 if(TestExprA) if(TestExprB) stmtBT; else stmtBF; else stmtAF; if(TestExprA) if(TestExprB) stmtBT; else stmtBF; else if(TestExprC) stmtCT; else stmtCF; Nested if
  • 56. A program to find the largest among three numbers using the nested loop #include <stdio.h> int main() { int a, b, c; printf(“nEnter the three numbers”); scanf(“%d %d %d”, &a, &b, &c); if(a > b) if(a > c) printf(“%d”, a); else printf(“%d”, c); else if(b > c) printf(“%d”, b); else printf(“%d”, c); return 0; }
  • 57.  This classic problem occurs when there is no matching else for each if. To avoid this problem, the simple C rule is that always pair an else to the most recent unpaired if in the current block. Consider the illustration shown here.  The else is automatically paired with the closest if. But, it may be needed to associate an else with the outer if also. Dangling else Problem
  • 58.  Use of null else  Use of braces to enclose the true action of the second if With null else With braces if(TestExprA) if(TestExprB) stmtBT; else ; else stmtAF; if(TestExprA) { if(TestExprB) stmtBT; } else stmtAF; Solution to Dangling Else Problem
  • 59. The C switch construct The general format of a switch statement is switch(expr) { case constant1: stmtList1; break; case constant2: stmtList2; break; case constant3: stmtList3; break; …………………………. …………………………. default: stmtListn; } The Switch Statement
  • 60. Switch Vs. Nested if  The switch differs from the else-if in that switch can test only for equality, whereas the if conditional expression can be of a test expression involving any type of relational operators and/or logical operators.  A switch statement is usually more efficient than nested ifs.  The switch statement can always be replaced with a series of else-if statements.
  • 61.  A loop allows one to execute a statement or block of statements repeatedly. There are mainly two types of iterations or loops – unbounded iteration or unbounded loop and bounded iteration or bounded loop.  A loop can either be a pre- test loop or be a post-test loop as illustrated in the diagram. Iteration & Repetitive Execution
  • 62. Expanded Syntax of “while” and its Flowchart Representation while statement is a pretest loop. The basic syntax of the while statement is shown below: “While” Construct
  • 63. An Example #include <stdio.h> int main() { int c; c=5; // Initialization while(c>0) { // Test Expression printf(“ n %d”,c); c=c-1; // Updating } return 0; } This loop contains all the parts of a while loop. When executed in a program, this loop will output 5 4 3 2 1 An Example
  • 64. “for” Construct  The general form of the for statement is as follows: for(initialization; TestExpr; updating) stmT;
  • 65. An Example #include <stdio.h> int main() { int i,n; printf(“Enter the number”); scanf(“%d”,&n); for(i = 0; i < n; i++) printf(“ %dn”,i); return 0; } This loop contains all the parts of a for loop. When executed in a program, this loop will output 0 1 2 3 4 An Example
  • 66. The C do-while loop The form of this loop construct is as follows: do { stmT; /* body of statements would be placed here*/ }while(TestExpr); “do-while” Construct
  • 67. Point to Note With a do-while statement, the body of the loop is executed first and the test expression is checked after the loop body is executed. Thus, the do-while statement always executes the loop body at least once.
  • 68. An Example #include <stdio.h> int main() { int n = 5; do { printf(“HELLO”); n++; }while(n <= 5); return 0; } This loop contains all the parts of a do-while loop. When executed in a program, this loop will output HELLO An Example
  • 69. The control is unconditionally transferred to the statement associated with the label specified in the goto statement. The form of a goto statement is goto label_name; The following program is used to find the factorial of a number. #include <stdio.h> int main() { int n, c, f=1; printf(“n Enter the number:”); scanf(“%d”,&n); if(n<0) goto end; for(c=1; c<=n; c++) f*=c; printf(“n FACTORIAL IS %d”, f); end: return 0; } goto Statement
  • 70. SPECIAL CONTROL STATEMENTS  “return” statements  “break” statements  “continue” statements
  • 71. return statement  The return type is used in the definition of a function to set its returned value and the return statement is used to terminate execution of the function.  Syntax  return;  return expression;
  • 72. “break” & “continue” statements break continue 1. It helps to make an early exit from the block where it appears. 1. It helps in avoiding the remaining statements in a current iteration of the loop and continuing with the next Iteration 2. It can be used in all control statements including switch construct. 2. It can be used only in loop constructs.
  • 73. #include<stdio.h> int main() { int c = 1; while(c <= 5) { if(c == 3) break; printf(“t%d”, c); c++; } return 0; } Output: 1 2 #include<stdio.h> int main() { int c = 1; while(c <= 5) { if(c == 3) continue; printf(“t%d”, c); c++; } return 0; } Output: 1 2 4 5
  • 74.  A nested loop refers to a loop that is contained within another loop.  If the following output has to be obtained on the screen 1 2 2 3 3 3 4 4 4 4 then the corresponding program will be #include <stdio.h> int main() { int row, col; for(row=1;row<=4;++row) { for(col=1;col<=row;++col) printf(“%d t”, row); printf(“n”); } return 0; } Nested Loops