Unit 1

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

Unit 1

Introduction
Introduction to algorithms
• Algorithm is a systematic logical approach which is a well-
defined, step-by-step procedure that allows a computer to
solve a problem..
• Pseudo code is a simpler version of a programming code in
plain English which uses short phrases to write code for a
program before it is implemented in a specific
programming language.
• A flowchart is a schematic representation of an algorithm
or the diagrammatic representation of way to solve the
given problem.
Algorithm
• This is the first step to solve a mathematical or computer problem.
• Breaking down the task.
• “A sequence of activities to be processed for getting desired output from a
given input.”
• A computer program can be viewed as an elaborate algorithm.
• While writing algorithms we will use following symbol for different
operations:

 ‘+’ for Addition

 ‘-’ for Subtraction

 ‘*’ for Multiplication

 ‘/’ for Division and

 ‘←’ for assignment


Pseudo code
• Pseudo code is an informal way of writing a program.
• It is not exactly a computer program.
• It represents the algorithm of the program in natural
language and mathematical notations.
• Usually, there is no particular code syntax to write a pseudo
code.
• Therefore, there is no strict syntax as a usual programming
language.
• It uses simple English language.
Flow chart
• A Flow chart is a Graphical representation of an Algorithm.
• Flowcharts are drawn using certain special purpose symbols
such as Rectangles, Diamonds, Ovals and small circles.
• These symbols are connected by arrows called flow lines.
• Flow chart simply a diagrammatic /pictorial representation of
way to solve the given problem.
• Flowcharts can be used to describe all sorts of processes:
business, educational, personal and of course algorithms.
• So, flowcharts are often used as a program planning tool to
visually organize step-by-step process of a program.
The following are the most common symbols used in
drawing flowcharts:
Example1: Algorithm to add two numbers

Step 1: Start

Step 2: Read values num1 and num2.

Step 3: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 4: Write/ Display sum

Step 5: Stop.
Example1: Pseudo code to add two numbers

Begin
Read: num1, num2;
Set sum = num1+num2;
Print sum;
End
Example1: Flowchart to add two numbers
Example2: Algorithm to find the sum of individual digits of a
given positive integer.

Step 1: start
Step 2: read a positive integer called num
Step 3: declare and initialize variables:
sum←0, dig←0
Step 4: repeat steps 4.1, 4.2, 4.3 until num greater than zero
4.1: dig ← num mod 10
4.2: sum ← sum + dig
4.3: num ← num/10
Step 5: write/ display sum
Step 6: stop
Example2: Pseudo code to find the sum of individual digits
of a given positive integer

Begin
Read num;
Set sum=0, dig=0;
While num>0 then
dig = num % 10
sum = sum + dig
num = num/10
End while
print sum
End
Example 2: Flow chart to find the sum of individual
digits of a given positive integer
Example 3 : Algorithm to find the largest among two
different numbers
Step 1: Start
Step 2: Declare variables a and b.
Step 3: Read values of a and b.
Step 4(a): If a greater than b then
Write/ Display a is the largest number.
Step 4(b): Else
Write/ Display b is the largest number.
Step 5: Stop
Example 3 : Pseudo Code to find the largest among two
different numbers
Begin
Read a and b
if a>b then
Print a is largest
else
Print b is largest
end if
End
Example 3: Flow chart to find the largest among two
different numbers
Example 4: Algorithm to convert temperature Fahrenheit to
Celsius
Algorithm:
Step 1: Start
Step 2:Read Temperature in Fahrenheit F
Step 3: convert temperature to celsius
C← 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step 5: Stop
Example 4: Pseudo code to convert temperature Fahrenheit
to Celsius

Begin
Read Fahrenheit
set Celsius = 5/9*(Fahrenheit -32)
Print Celsius
End
Example4: Flow chart to convert temperature Fahrenheit to
Celsius
Introduction to C Language
History of C
• Developed by Dennis Ritchie in the early 1970’s at Bell
telephone laboratory.
• C is a general purpose, structured programming language.
• The first standard for C was published by ANSI (American
National Standards Institute).
C Programming Language
• Set of instructions is called as program.
• These instructions are formed using certain symbols
and words according to some rules known as syntax
rules.
• Purpose: C is used for systems programming (for
writing OS) as well as for application programming
(writing general purpose programs).
Features of C programming
• C has many built-in functions that can be used to write any
complex code or program.
• C has its own built-in library. User defined functions can be
added to extend library.
• C has many data types and operators that helps in fast
execution of program.
• A program can be separated in different modules. Modularity
makes a program easy to debug, test and maintain.
• C language is case sensitive.
Program development steps
(Creating, Compiling and running program)
• Source code is a file with instructions in high level language.
• A compiler translates the high level language into the machine
language.
• The Object code is the output of a compiler after it processes
source code.
• The Linker combines both the object code and specified header
file code and generates an Executable file.
• Loader is the program of the operating system which loads the
executable file from the disk into the primary memory(RAM) for
execution. It allocates the memory space to the executable
module in main memory and then transfers control to the
beginning instruction of the program
• CPU places the result on User window.
Structure Of A C-program
This section is used to provide small description of the program.
The comment lines are simply ignored by the compiler
/*comments or documentation*/
Preprocessing commands Preprocessing commands are used to include header files
or linking Section and to define constants, it instructs the compiler to do
required pre-processing before the actual compilation
Global declarations;
int main() Used to declare variables that are common
{ to multiple functions
local declarations;
Every C program must write this statement. This
executable statements; statement (main) specifies the starting point of the
. C program execution
.
return 0;
} The return value of the main function is considered
the "Exit Status" of the application.
On most operating systems returning 0 is a success
status like saying "The program worked fine".
A simple C program to Print Hello world

#include<stdio.h>
void main()
{
printf("Hello, World! \n");
}

Output:
Hello, World!
C Tokens
• In a C program the smallest individual units known as C tokens.
• C has 6 types of tokens namely:
1) Keywords
2) Identifiers
3)Constants
4)String literals
5)Operators.
6) White spaces.
C Tokens
• Keywords
– These are reserved words of the C language.
– There are 32 keywords in C, all the keywords are in small
case.
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
• Identifiers
– An Identifier is a sequence of letters and digits, but must
start with a letter. Identifiers are case sensitive. Identifiers
specifies the names to the particular entity such as name
of variables, functions etc.
– Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
– Invalid: 324, short, price$, My Name
• Variable
– Indicates the name of the data value.
• Constants: It refers to fixed values that do not change during
the execution of program.
– Numeric constants: integer and real(float)
– Character constants: single character and strings
• String Literals
– A sequence of characters enclosed in double quotes as
“…”. For example “13” is a string literal and not number 13.
‘a’ and “a” are different.
– Ex: “GfG”, “hello world” etc.,
• Operators
– Arithmetic operators like +, -, *, / ,% etc.
– Logical operators like ||, &&, ! etc.
• White Spaces
– Spaces, new lines, tabs. These are used to separate the
adjacent identifiers, keywords and constants.
Data types
• Data type determines the type of data a variable will hold.
• C language has some predefined set of data types to handle
various kinds of data that we can use in our program.
• Primary data types:
– void: Has no values and no operations.
– character(char): Used to store character value.
– integer(int): Used to store whole numbers.
– Floating point(float, double): Used to store real numbers.
Data type
Type Storage Value range Format
size specifier
unsigned 1 byte 0 to 255 %c
char
signed char 1 byte -128 to 127 %c
short int 2 bytes -32,768 to 32,767 %d
unsigned 2 bytes 0 to 65,535 %u
short int
long int 4 bytes -2,147,483,648 to 2,147,483,647 %ld
unsigned 4 bytes 0 to 4,294,967,295 %lu
long int
float 4 bytes 3.4*E-38 to 3.4*E+38 %f
double 8 bytes 1.7*E-308 to 1.7*E+308 %lf
long double 10 bytes 3.4*E-4932 to 1.1*E+4932 %Lf
Derived and User defined data types

• Derived data types are


 array
 pointer
• User Defined Data types
 structure
 union
 enum
 typedef
Variables
• We can store data in a memory space and name it, so that it
becomes easier to access memory space.
• The naming of an address is known as variable.
• Unlike constant, variables are changeable, we can change value of a
variable during execution of a program.
Rules to name a variable:
• The name of a variable can be composed of letters, digits, and the
underscore character.
• Variable name must not start with a digit.
• Blank spaces are not allowed in variable name.
• Keywords are not allowed as variable name.
• C is case-sensitive, so it is suggested to keep the variable names in
lower case.
• Example : average, height, age, total etc
• Declaration of variables must be done before they are used in
the program.
• Syntax of variable declaration:
datatype variable;
• Single variable declaration:
int a;
• multiple variables declaration of same data type
float b, c;
• Initializing a variable means to provide it with a value.
int a;
a = 10;
Or
int a=10;
Constants
• A constant is a value or variable that can't be changed in the
program, for example: 10, 20, 'a', 3.4, "c programming" etc.
• Two ways to define constant in C:
– const keyword: The const keyword is used to define
constant in C programming.
• Ex: const float PI=3.14;
– #define preprocessor: The #define preprocessor is also
used to define constant.
Example
#include<stdio.h>
int main(){
const float PI=3.14;
//PI=4.5; //it will render compile time error
printf("The value of PI is: %f",PI);
return 0;
}
Output:
The value of PI is: 3.14
Input & Output
• The printf() and scanf() functions are used for input and output in C
language.
• Both functions are inbuilt library functions, defined in stdio.h
(header file).
• The printf() function is used for output. It prints the given
statement to the console.
• Syntax:
printf("format string",argument_list);
• The format string can be %d (integer), %c (character), %s (string),
%f (float) etc.
• The scanf() function is used for input. It reads the input data from
the console.
• Syntax:
scanf("format string",argument_list);
Example
• C program to take input from user and print
#include <stdio.h> //preprocessor directive command
int main()
{
int number;
// printf() dislpays the formatted output
printf("Enter an integer: ");
// scanf() reads the formatted input and stores them
scanf("%d", &number);
// printf() displays the formatted output
printf("You entered: %d", number);
return 0; // exit status
}
• Output:
Enter a integer: 25
You entered: 25
• C program to multiply two numbers
#include <stdio.h>
int main()
{
double firstNumber, secondNumber, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &firstNumber,&secondNumber);
product = firstNumber * secondNumber;
printf("Product = %.2lf", product);
return 0;
}
• Output:
Enter two numbers: 2.4
1.12
Product = 2.69
What is an Error?
• It is an unexpected output
• Illegal operation which results in abnormal working of
the program.
• It is also known as bug.
• For the successful execution of the programs, it is
necessary to remove all types of errors.
• Debugging:
 It is the process of finding and removing errors
from the program.
Types of Error
• Syntax errors
• Runtime errors
• Logical errors
Syntax errors
• Reason:
 It occurs due to the violation of writing C syntax rules.
• Detector:
 Compiler detects during compilation.
 Easy to locate and remove them
 Compiler can easily specifies the location and type of
error.
• Outcome:
 The program having syntax error cannot be
compiled/translated.
When do syntax errors occurs?
• Missing statement terminator(;).
• Missing parenthesis({,}).
• Misspelled Keyword.
Example
// C program to illustrate syntax error
• #include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
• Output:
error: expected ';' before '}' token
Runtime Error
• Reason:
 Occurs due to performing an illegal operation.
• Detector:
 Computer detects errors at the time of running
the program.
• Outcome:
 Running program is stopped or crashed and a
diagnostic message is displayed on screen causing
that error
Why runtime error occurs?
• Number when divided by zero
• Accessing memory that is not available

These types of error are hard to find as the


compiler doesn’t point to the line at which the
error occurs.
Example
• // C program to illustrate run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
• Output:
warning: division by zero [-Wdiv-by-zero] div = n/0;
Logical error
• Reason:
 Occurs due to following a faulty algorithm.
 provide incorrect output but appears to be error free
• Detector:
 Programmer find their errors by checking the whole
program statement by statement.
 Comparatively difficult to detect this error
• Outcome:
 Running program does not stop or crash but the
wrong output is generated.
Example
• Program to find modulus
#include<stdio.h>
int main()
{
int a=10,b=2;
int mod;
mod = a/b; // Logical Error. Correct statement “mod=a%b;”
return 0;
}
• Output:
output which you were expecting will not be shown.
Operators in C
• An operator is a symbol used to perform operations in a
program.
• Set of operators that are classified as follows...
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Increment & Decrement Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operator
 Special Operators
Arithmetic Operators

• The addition operator can be used with numerical data types and
character data type.
‘c’ + ‘r’ = ‘cr’
• The remainder of division operator is used with integer data type
only.
Priority of operators:

Ex:-
3–5*7/8+6/2
3 – 35 / 8 + 6 / 2
3–4+6/2
3–4+3
-1 + 3
2
Convert arithmetic statements to C
• AxB–CxD
 A*B–C*D
• (M+N)(P-Q)
 (M+N)*(P-Q)
• 3x2 + 5x + 2
 3*x*x* + 5*x + 2
• A+B+C
E+D
 (A+B+C) / (D+E)
Assignment Operators
• Assign right hand side value (Rvalue) to the left hand side variable (Lvalue).
• The assignment operator is used in different variants along with arithmetic
operators.
simple assignment operators short hand assignment operators
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
a=a*b a*=b
a=a/b a/=b
Increment & Decrement Operators
• The increment and decrement operators are called as unary
operators.

• (++a): pre-increment
• (--a): pre-decrement
• (a--): post-decrement
• (a++): post-increment
Pre-Increment and Pre-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf(“++i = %d, --j = %d",++i,--j);
}
Output:
++i = 6, --j = 4
Post-Increment or Post-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf("i++ = %d, j-- = %d\n",i++,j--);
printf(“i = %d, j = %d\n” ,i,j);
}
Output:
i++ = 5, j-- = 5
i = 6, j = 4
Relational Operators
• They are used to compare or check the relationship between two values.
• Every relational operator has two results TRUE or FALSE.
• Relational operators are used to define conditions and take decisions in a
program.
Logical Operators
• The logical operators are used to combine multiple conditions into one
condition.
exp-1 exp-2 exp-1 && exp-2 exp-1 || exp-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
exp-1 !exp-1
non-zero zero
zero non-zero

• Logical operator examples:


– if ( marks >= 40 && attendance >= 75 )
grade = ‘P’;
– if ( marks < 40 || attendance < 75 )
grade = ‘N’;
Conditional operator
• It is also called as ternary operator .
• This operator is used for decision making.
• In this operator,
– first we verify a condition
– If the condition is TRUE the first option is performed,
– if the condition is FALSE the second option is performed.
• Syntax
Condition ? TRUE Part : FALSE Part ;
• Example
A = (10<15) ? 100 : 200 ;
⇒ A value is 100
Program to find largest of 2 different numbers
using ternary operator
#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d %d",&i,&j);
large=(i>j)?i:j;
printf("Largest = %d",large);
}
Bitwise Operators
• Perform bit level operations.
• The operations are performed based on the binary values.
• For example: A = 25 (11001) and B = 20 (10100)
Special operators
sizeof operator
• This operator is used to find the size of the memory (in bytes)
allocated for a variable. This operator is used with the following
syntax...
• Syntax
sizeof(variableName);
• Example
int A;
X=sizeof(A);
result is 2 if A is an integer
Comma operator (,)
• This operator is used to separate variables while they are declaring,
separate the expressions in function calls etc.
float a=2.5,b;
Pointer operator (*)
• This operator is used to define pointer variables in c programming
language.
int *p;
Dot operator (.)
• This operator is used to access members of structure or union.
printf(“%d”, emp.num);
Expressions in C
What is an expression?
• An expression is a collection of operators and operands that
represents a specific value.
• operator is a symbol which performs tasks like arithmetic
operations, logical operations and conditional operations etc.,
• Operands are the values on which the operators perform the
task.
• Here operand can be a direct value or variable or address of
memory location.
The precedence and associativity of
operators
Expression evaluation
• In C programming language, expression is evaluated based on
the operator precedence and associativity.

• Expression Types in C
– Infix Expression
– Postfix Expression
– Prefix Expression
Infix Expression
• The expression in which operator is used between operands is
called as infix expression.
• Structure of infix expression:

Example:
10 + 4 * 3 / 2
4 * 3 => 12
12 / 2 => 6
10 + 6 => 16
Postfix Expression
• The expression in which operator is used after operands
is called as postfix expression.
• Structure of postfix expression:

• Example:
4 5*8+
4*5 =>20
20+8 =>28
Prefix Expression
• The expression in which operator is used before
operands is called as prefix expression.
• The structure of prefix notation:

• Example:
+ * 2 3/ 10 2
2*3 => 6
10/2 =>5
6+5 =>11
Type conversion
• Type Conversion: Conversion from one data
type to another.

• Two ways of type conversion are:


Implicit Type Conversion
Explicit Type Conversion
Implicit Type conversion
• Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external
trigger from the user.
• All the variables are upgraded to the data type of the
variable with largest data type. This is also known as type
promotion.
• bool -> char-> short int-> int -> unsigned int-> long->
unsigned long-> float -> double-> long double
Example program
#include<stdio.h>
void main()
{
char c='a';
int x=5;
x = x+c; //char is converted to int
float y=6.45;
y = y+x; //int is converted to float
printf("x=%d\n",x);
printf("y=%.2f\n",y);
}
Explicit Type Conversion
• This process is also called type casting and is user
defined.
• Here the user can type cast the result to make it of a
particular data type.
• The syntax in C:
(type) expression
• Type indicated the data type to which the final result
is converted.
Example program
#include<stdio.h>
void main()
{
int a=8;
float b=a/3;
printf("8/3 = %f\n",b);

b=(float)a/3;
printf("8/3 = %.2f",b);
}
Decision making and branching
Introduction
• In c program, statements are executed sequentially, when no
options or repetitions are necessary.
• But the order of execution changes based on
– certain conditions
– repeats group of statements until certain condition is met
• This involves decision making to check whether a conditions has
occurred or not.
• Then direct the computer to execute some statements accordingly.
• Such decision making statements in C:
– if statement
– switch statement
– Conditional operator statement
– goto statement
if statement in c
• In c, if statement is used to make decisions based on a condition.
• The if statement verifies the given condition and decides whether a
block of statements are executed or not based on the condition
result.
• The if statement may be implemented in different forms depending
on the complexity of conditions to be tested. The different forms
are:
– Simple if statement
– if - else statement
– Nested if - else statement
– else if ladder(if-else-if statement )
Simple if statement
Syntax:
if (condition)
{
block of statement;
}
statement-x;

• The simple if statement evaluates specified condition.


• If condition is TRUE (non-zero), the block of statements are executed
and then statement-x is executed
• otherwise the block of statements are skipped and the execution will
jump to statement-x.
• Simple if statement is used when we have only one option that is
executed or skipped based on a condition.
Example: C program to find whether given
number is divisible by 5
#include <stdio.h>
Case 1:
void main() Enter any integer: 100
{ 100 is divisible by 5
int n ; statement does not belong to if!!!
printf("Enter any integer: ") ; Case 2:
Enter any integer: 99
scanf("%d", &n) ;
statement does not belong to if!!!
if ( n%5 == 0 )
printf("%d is divisible by 5\n“, n) ;
printf("statement does not belong to if!!!") ;
}
if - else statement
• The if-else statement is an extension of the simple if statement.
• Syntax:
if(condition)
{
true block statements;
}
else
{
false block statements;
}

• In either case, either true block or false block will be executed, not both.
Example: c program to check whether given
number is even or odd
#include <stdio.h>
#include<conio.h>
void main()
{ Case 1:
int n ; Enter any integer: 100
100 is EVEN
printf("Enter any integer: ") ;
Case 2:
scanf("%d", &n) ; Enter any integer: 99
if ( n%2 == 0 ) 99 is ODD
printf("%d is EVEN\n", n) ;
else
printf("%d is ODD\n", n) ;
}
Nested if-else statement
• When a series of decisions are involved, we use more than one if-else
statement in nested form.
• The nested if-else statement can be defined using any combination of
simple if and if-else statements.

Syntax: else
if (condition-1) {
{ statements 3;
if (condition-2) }
{ statement x;
statements 1;
}
else
{
statements 2;
}
}
Example: c program to check whether given
number is even or odd if it is below 100.
#include <stdio.h>
void main(){
int n ;
printf("Enter any integer: ") ;
scanf("%d", &n) ;
if ( n < 100 ) {
printf(“%d is below 100\n", n) ; Case 1:
if( n%2 == 0) Enter any integer: 55
printf("And it is EVEN") ; 55 is below 100
And it is ODD
else
Case 2:
printf("And it is ODD") ; Enter any integer: 999
} 999 is not below 100
else
printf(“%d is not below 100" , n);
}
else if ladder(if-else-if statement )
• When multi path decisions are involved, we use a chain of ifs in
which the statement associated with each else is an if.
• Syntax:
if (condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else
statement 4;
statement x;
Example: C program to find the largest of three
numbers.
#include <stdio.h>
void main(){
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output:
Enter any three integer numbers: 55 60 20
60 is the largest number
• When we use conditional control statement like if statement, condition
might be an expression evaluated to a numerical value, a variable or a
direct numerical value.
• If the expression value or direct value is zero the condition becomes
FALSE otherwise becomes TRUE.
• Examples:
– if(10) - is TRUE
– if(x) - is FALSE if x value is zero otherwise TRUE
– if(a+b) - is FALSE if a+b value is zero otherwise TRUE
– if(a = 99) - is TRUE because a value is non-zero
– if(10, 5, 0) - is FALSE because it considers last value
– if(0) - is FALSE
– if (a=0, x=10) – is TRUE because it considers last value
– if(a=10, b=15, c=0) - is FALSE because last value is zero
switch statement in C
• When one of the many options is to be selected, we can use if
statement to control the selection.
• The complexity increase with increase in number of options.
• Program becomes difficult to read and flow.
• C has a built-in multi-way decision statement known as
switch.
• The switch statement tests the value of a given (or
expression) against a list of case values
• And when match is found, a block of statements associated
with that case is executed.
• expression can integer or character.
Syntax: • value1, value2 ... are constants (unique)
or constant expressions and are known as
switch (expression) case labels.
{ • block1, block2 ... are statement lists and
case value1: may contain zero or more statements.
block1
break; • No need of braces for blocks and case
case value2: labels end with colon (:).
block2 • If a case is found whose value matches
break; with the value of the expression, then the
......... block of statements that follows the case
......... are executed.
default: • The break statement signals the end of a
default block particular case and causes an exit from
break; switch.
} • The default is an optional case.
Statement-x;
Flow of execution
Example: c program to assign grades.
#include <stdio.h> case 4: printf("Third division") ;
void main(){ break ;
int n ; default: printf("Fail") ;
printf("Enter CGPA: ") ; }
scanf("%d", &n) ; }
index = n/10
switch( n ) { Case 1:
case 10: Enter marks: 85
case 9: Distinction
case 8: printf("Distinction") ; Case 2:
break ; Enter marks: 15
case 7: Fail
case 6: printf("First division") ;
break ;
case 5: printf("Second division") ;
break ;
The conditional operator
• Conditional operator is useful for making two-way decisions.
• This operator is a combination of ? and :, and takes 3 operands.
• Syntax:
conditional expression ? expression1 : expression2
• The conditional expression is evaluated first.
• If the result is non-zero, expression 1 is evaluated and its value is returned.
• Otherwise expression 2 is evaluated and its value is returned.
• For example:
if (x%2==0)
flag=1
else
flag=0
Can be written as
flag = (x%2==0) ? 1 : 0
• Using conditional operator is concise and efficient
• The conditional operator can be nested for evaluating more complex
assignment decisions.
• Example: consider the weekly salary of a sales girl who is selling some
domestic products. If x is the number of products sold in a week, her
weekly salary is given as:
4x +100 for x < 40
salary= 300 for x=40
4.5x+150 for x>40
• Using else-if ladder
if(x<40)
salary = 4*x + 100
else if (x>40)
salary = 4.5*x + 150
else
salary = 300
• This equation can be written as
salary = (x != 40) ? ((x<40) ? (4*x + 100) : (4.5*x + 150)) : 300
The goto statement
• In c, there are control statements which does not need any condition
to control the program execution flow.
• When we use goto statement in the program, the execution control
directly jumps to the line with specified label unconditionally..
• Using goto statement we can jump from top to bottom or bottom to
top.
• Syntax
goto label;
label:
Statement x; statetements;
------ -----------
label: -----------
goto label;
Statements 1;
Statements 2;
• The goto statement can be used with any statement like if, switch,
while, do-while and for etc,.
Example: forward jump
#include <stdio.h>
void main()
{
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last:
printf("We are at last printf statement!!!\n") ;
}
Output
We are at first printf statement!!!
We are at last printf statement!!!
Example: backward jump

#include<stdio.h> #include<stdio.h>
Void main()
Void main()
{
{ double x,y;
double x,y; read:
read: if ( x > 0)
scanf(“%f”, &x); {
scanf(“%f”, &x);
y = sqrt(x);
y = sqrt(x);
print(“%f %f\n”, x , y); print(“%f %f\n”, x , y);
goto read; goto read;
} }
}
Decision making and looping
The for statement
• The for loop is entry-controlled loop.
• It is concise control structure.
• General form of for:
Control variable is
Initialization of control variables incremented

for( initialization; test-condition; increment)


{
body of the loop
}
The value of control
variables is tested
Flow chart
Example
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
for ( i=1; i<=10; i++) for ( i=10; i>0; i--)
{ printf(“%d”,i);
printf(“%d”,i); printf(“\nEnd of for loop.\n”);
} }
printf(“\nEnd of for loop.\n”);
} Output:
Output: 10987654321
12345678910 End of for loop.
End of for loop.
The three loops

for while do…while

for(n=1;n<=10;n++) n=1; n=1;


{ while(n<=10) do
-------- { {
-------- ----- -----
} ----- -----
} } while(n<=10);
Program to print Fibonacci series
#include<stdio.h> }
void main() }
{ Output:
int num1=0, num2=1, fib ,n ,I; Enter the value of n: 8
printf(“\nEnter the value of n: ”); Fibonacci series: 0 1 1 2 3 5 8 13
scanf(“%d”,&n);
if(n==1)
printf(“Fibonacci series: %d ”, num1)
if(n>=2)
printf(“Fibonacci series: %d %d ”,
num1,num2);
for(i=3; i<=n; i++)
{
fib=num1+num2;
printf(“%d ”,fib);
num1=num2;
num2=fib;
• More than one variable can be initialized and the increment section may
have more than 1 part.
#include<stdio.h>
void main()
{
int n,m,p;
for(n=1, m=5; n<=m; n++, m--)
{
p = m/n;
printf(“%d / %d =%d\n”, m,n,p);
}
}
Output:
5/1=5
4/2=2
3/3=1
• Test condition may have any compound relation.
sum=0;
for (i=1; i<5 && sum<50; i++)
{
sum=sum+i;
printf(“%d %d\n”, i, sum);
}
• Use of expressions in initialization and increment.
for(x = (m+n)/2 ; x>0 ; x = x/2)
• Initialization, loop-continuation, and increment can contain arithmetic
expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
• Both the initialization and increment sections are omitted in the for
statement.
m=10;
for( ; m!=100 ; )
{
printf(“%d\n”,n);
m=m+10;
}
• If the loop continuation condition is initially false
• The body of the for structure is not performed
• Control proceeds with the next statement after the for structure
Nested for loop
for(n=1;n<=10;n++)
{
--------
--------
for(j=1;j!=5;j++)
{
Inner loop outer loop
--------
--------
}
------
------
}
Program to find the prime numbers from 2 to 10

#include <stdio.h> return 0;


int main () { }
int i, j; Output:
for(i = 2; i<10; i++) 2 is prime
{ 3 is prime
for(j = 2; j <= (i/j); j++) 5 is prime
if(!(i%j)) 7 is prime
break;
if(j > (i/j))
printf("%d is
prime\n", i);
}
• break
– Causes immediate exit from a while, for, do/while or switch
structure
– Program execution continues with the first statement after the
structure
– Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch structure
• continue
– Skips the remaining statements in the body of a while, for or
do/while structure
• Proceeds with the next iteration of the loop
– while and do/while
• Loop-continuation test is evaluated immediately after the
continue statement is executed
– for
• Increment expression is executed, then the loop-
continuation test is evaluated
Outline
/*Using the continue statement in a for structure */

#include <stdio.h>

int main()

for ( x = 1; x <= 10; x++ ) {

if ( x == 5 )
continue; /* skip remaining code in loop only

if x == 5 */

printf( "%d ", x );

}
printf("\nUsed continue to skip printing the value 5\n");

return 0;
}
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5  2000 Prentice H
Loops
• Loops are used to repeat a set of statements.
• In looping, a sequence of statements are repeatedly
executed until some end condition is met.
• A program loop has
 Body of the loop.
 Control statement.
• Depending on the position of the control statement in
the loop, control structure has
– Entry controlled loop.
– Exit controlled loop.
• Entry controlled and exit controlled loop
structure is shown below:

• There are three loops in C programming:


 while loop
 do...while loop
 for loop
while loop
• while loop is a control flow • while is an entry controlled loop.
statement that allows code to be
executed repeatedly based on a
given Boolean condition.
• The Boolean condition is either true
or false.
• The syntax of a while loop is:
Initialization;
while (test expression)
{
body of the loop;
increment/decrement;
}
where, the test expression is the
condition that checks it is true or
false before each iteration.
Example #1: while loop
• // Program to print a statement 5 times using while loop
#include <stdio.h>
int main ()
{
int a = 1;
while( a < =5 )
{
printf(“hello world \n");
a++;
}
return 0;
}
Output: hello world
hello world
hello world
hello world
hello world
do….while loop
• The body of do...while loop is executed first and then the test expression is
evaluated.
• If condition is true then loop is iterated till the condition is satisfied.
• The body of the do...while loop is executed at least once even if the
condition is false.
• do...while loop Syntax
• Initialization;
do
{
body of the loop;
increment/decrement;
}
while (test expression);
Example #2: do.....while loop

• // Program to print numbers output:


from 10 to 1 using do…while 10
loop 9
#include <stdio.h> 8
void main() 7
{ 6
int i = 10; 5
do 4
{ 3
printf(" %d\n", i ); 2
i --; 1
}
while ( i > 0 );
}
break
• When a break statement is encountered, it terminates the
block and gets the control out of the switch or loop.
• The break statement can be used in both switch and loop
statements.
• A break causes the innermost enclosing loop or switch to
be exited immediately.
Example that illustrates break
• //Program to print 20 natural }
numbers and exit the loop at 10. • Output:
#include<stdio.h> 1
int main() 2
{ 3
int i=1; 4
while ( i <20 ) 5
{ 6
if ( i == 10) 7
break; 8
printf(“%d\n”,i); 9
i++;
}
return 0;
continue
• A continue can appear only in loop (for, while, do) statements.
• A continue doesn't terminate the loop, it causes the loop to
go to the next iteration. All iterations of the loop are executed
even if continue is encountered. The continue statement is
used to skip statements in the loop that appear after
the continue.
• When a continue statement is encountered, it gets the control
to the next iteration of the loop.
Example to illustrate continue
#include<stdio.h> 4
int main() 5
{ 6
int i=0; 7
while ( i <20 ) 8
{ 9
i++; 11
if ( i == 10) 12
continue; 13
printf(“%d\n”,i); 14
} 15
return 0; 16
} 17
• Output: 18
1 19
2 20
3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy