[go: up one dir, main page]

0% found this document useful (0 votes)
14 views62 pages

PPS Mod-2

Module 2 covers control statements in programming, including decision-making and iterative statements, along with their syntax and examples. It introduces problem-solving concepts such as algorithms, flowcharts, and top-down design. The module also explains various control structures like if, switch, while, do-while, and for loops, along with unconditional statements like break, continue, and goto.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views62 pages

PPS Mod-2

Module 2 covers control statements in programming, including decision-making and iterative statements, along with their syntax and examples. It introduces problem-solving concepts such as algorithms, flowcharts, and top-down design. The module also explains various control structures like if, switch, while, do-while, and for loops, along with unconditional statements like break, continue, and goto.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Module 2

CONTROL STATEMENTS AND


INTRODUCTION TO PROBLEM
SOLVING
Control Statements: Specifying test condition for selection and iteration, Writing
test expression, Conditional execution and selection, Iteration and repetitive
execution, goto statement, Special control statements, Nested loops.
Introduction to Problem Solving: Algorithms, Flowcharts, Problem solving
aspect, Topdown design, Implementation of algorithms, program verification
and efficiency of algorithms
Control statements
A control statement is a statement that decides whether some statements will
execute or not. There are two types of control statements available.
1. Decision making or Selective statements.
2. Looping or Iterative statements.
Decision making statements:
These statements will allow us to make to decision, whether to execute some
statements of not.
These are Two Types.
3. Conditional statements,
4. Unconditional statements.
Conditional statements
Different types of conditional statements are
1. if statement
2. if else statement
3. else if ladder
4. Nested if statement
5. switch statement
if condition :
We have to give an if condition, if the condition is TRUE, then the
statements inside if loop will execute. If it is FALSE, the statements will
not execute.
Syntax:

if(condition) {
statements;
}

#include <stdio.h>

int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

if (number % 2 == 0) {
printf("%d is even.\n", number);
}
}
if else condition:
We have to give an if condition.
if the condition is TRUE, then the statements inside if block will execute.
If it is FALSE, the statements inside else block will execute.
Syntax:

if(condition) {
statements;
}
else {
statements;
}

Eg: Even or odd
Largest of two numbers
#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
} else
{
printf("You are not eligible to vote.\n");
}

return 0;
}
else if ladder :
• The else if ladder statement executes one condition from multiple statements.
• The execution starts from top and checked for each if condition.
• The statement of if block is executed first. If the condition is TRUE, the statements in if block is executed first.
• If it is FALSE, next else if condition is executed.
Syntax :
if (condition) {
statements;
}
else if (condition) {
statements;
}
else if (condition) {
statements;
}
.
.
else {
statements;
}
#include<stdio.h>
void main()
{
int marks;
printf("Enter your marks ");
scanf("%d",&marks);
if(marks<0 || marks>100)
{
printf("Invalid Entry,the marks must be between 0-100");
}
else if(marks<50)
{
printf("Grade F");
}
else if(marks>=50 && marks<60)
{
printf("Grade D");
}
else if(marks>=60 && marks<70)
{
printf("Grade C");
}
else if(marks>=70 && marks<80)
{
printf("Grade B");
}
else if(marks>=80 && marks<90)
{
printf("Grade A");
}
else
{
printf("Grade A+");
}
}
Nested if statement:
• An if statement within another if statement is known as Nested if statement.
• Syntax:
if (condition) {
if (condition) {
statements;
}
else {
statements;
}
}
else {
statements;
}
Eg:Largest of three numbers
//nested if-else
#include <stdio.h>
int main()
{
int A, B, C;

printf("Enter three numbers: ");


scanf("%d %d %d", &A, &B, &C);

if (A >= B) {
if (A >= C)
printf("%d is the largest number.", A);
else
printf("%d is the largest number.", C);
}
else {
if (B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
}

return 0;
}
switch statement :
• A switch statement is a type of selection, used to allow the value of a variable to change the control flow of program
execution.
• It allows to choose only one choice among many choices.
• It consists of optional default statement.
• break keyword is used inside cases to terminate from switch.
Syntax :
switch (expression) {
case label 1: statements;
break;
case label 2: statements;
break;
.
.
case label n: statements;
break;
default : statements;
break;
}
#include <stdio.h>
int main()
{
char ch;

/* Input an alphabet from user */


printf("Enter any alphabet: ");
scanf("%c", &ch);

/* Switch value of ch */
switch(ch)
{
case 'a':
printf("Vowel");
break;
case 'e':
printf("Vowel");
break;
case 'i':
printf("Vowel");
break;
case 'o':
printf("Vowel");
break;
case 'u':
printf("Vowel");
break;
default:
printf("Consonant");
}

return 0;
}
#include <stdio.h>
int main() {
int choice;
printf("Welcome to Our Restaurant!\n");
printf("Menu:\n");
printf("1. Pizza - $100.00\n");
printf("2. Burger - $50.00\n");
printf("3. Pasta - $40.00\n");
printf("4. Salad - $99.00\n");
printf("5. Exit\n");
printf("Please enter your choice (1-5): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You have selected Pizza. Price: $100.00\n");
break;
case 2:
printf("You have selected Burger. Price: $50.00\n");
break;
case 3:
printf("You have selected Pasta. Price: $40.00\n");
break;
case 4:
printf("You have selected Salad. Price: $99.00\n");
break;
case 5:
printf("Thank you for dining with us. Goodbye!\n");
break;
default:
printf("Invalid choice. Please select a valid option.\n");
}

return 0;
}
Iterative statements or looping
statements
An iterative statement repeatedly executes some statements which are
inside the loop until the control statement fails.
These are of 3 types
1. while loop
2. do – while loop
3. for loop
There are mainly two types of loops in C Programming:
• Entry Controlled loops: In Entry controlled loops the test condition is checked
before entering the main body of the loop. For Loop and While Loop is Entry-
controlled loops.
• Exit Controlled loops: In Exit controlled loops the test condition is evaluated at
the end of the loop body. The loop body will execute at least once, irrespective
of whether the condition is true or false. do-while Loop is Exit Controlled loop.
while loop :
It is also known as entry controlled loop.
• Syntax :
while (condition) {
statements / body of loop; Repeat
}
• First the while condition is evaluated.
• If it is TRUE, then the body of while loop will execute. After that the control again
transfer to while condition and once again the while condition is evaluated.
• This process repeats until while condition is FALSE.
• If it is FALSE, the statements after while block will execute.
• To repeat the loop we have to give an updating statement, otherwise it will be an
infinite loop.
• Infinite while loop: if the while condition is always true, then the loop will execute
forever.
//Natural numbers
n=100,i=0
while(i<=n)
{
printf("%d It is a natural number,i");
i++;
}
//Reversing the numbers:
#include <stdio.h>
int main(){
int i=100;
while(i>=0)
{
printf("%d\n",i);
i--;
}
}
Sum of N numbers:
#include <stdio.h>
int main() {
int n, i=1, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

while (i <= n) {
sum =sum + i;
++i;
}

printf("Sum = %d", sum);


return 0;
}
//sum of squares of N natural numbers
int main()
{
int i=1,n=5,sum=0;
While(i<=n)
{
sum=sum+(i * i);
i++;
}
printf(“%d”,sum);
}
//C program to product the number
#include <stdio.h>
int main() {
int i = 1, n, product = 1;

printf("Enter the number: ");


scanf("%d", &n);

while (i <= n) {
product = product * i;
i++;
}

printf("Product of first %d natural numbers: %d", n, product);

return 0;
}
Example:Amstrong number.
The sum of the digits of the cubes of the given number is equal to the given number is known as
amstrong number.
#include<stdio.h>
int main() {
int num, ams, rem, sum = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
ams = num;

while (num!= 0) {
// remainder contains the last digit
rem = num % 10;
sum =sum + rem * rem * rem;
// removing last digit from the orignal number
num=num/10;
}
if (sum == ams)
printf("%d is an Armstrong number.", ams);
else
printf("%d is not an Armstrong number.", ams);

return 0;
}
A palindrome number is a number that remains the same when
digits are reversed.
#include<stdio.h>
main()
{
int num,rem,rev=0,temp;
clrscr();
printf("enter the number");
scanf("%d",&num);
temp=num;
while(temp>0)
{
rem=temp%10;
rev=rev*10+rem;
temp=temp/10;
}
if(num==rev)
printf("given number is palindrome number");
else
printf("given number is not palindrome number");
getch();
}
do – while loop :
• Usually for and while loop checks the condition at the starting of the loop. But the do – while
loop checks the condition at the ending (bottom) of the loop.
• So it is also known as Exit controlled statement.
• do – while loop will execute at least one time.
• Syntax :
….
do {
statements / body of loop;
} while (condition);
• First the statements inside do while loop will execute, after that the while condition is
evaluated. If the while condition is TRUE, then the body will execute otherwise the statements
after the loop will execute.
• To repeat the loop we have to give an updating statement, otherwise it will be an infinite loop.
• Infinite do – while loop : if the do - while condition is always true, then the loop will execute
forever.
//Natural Numbers.
#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}
//print table for the given number
#include<stdio.h>
int main(){
int i=1,number;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
for loop :
• Syntax :
for ( initialization ; condition ; increment / decrement ) {
statements / body of the loop;
}
• The initialization statement is executed only once.
• Then the condition is evaluated. If it is FALSE, the loop for loop will terminate.
• If it is TRUE, then body of loop will execute. Then it will go to increment /
decrement.
• Again the loop will repeat until the condition is FALSE.
• Infinite for loop : if the condition in for loop is always true, then the loop will
execute forever.
Difference between loops:
//Factorial Program
#include<stdio.h>
int main()
{
int i,fact=1,num;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++){
fact=fact*i;
}
printf("Factorial of %d is %d",num,fact);
return 0;
}
//Fibonacci Series
#include<stdio.h>
int main()
{
int f1=0,f2=1,f3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",f1,f2);
for(i=2;i<number;++i)
{
f3=f1+f2;
printf(" %d",f3);
f1=f2;
f2=f3;
}
return 0;
}
Nesting of loop
When a loop written inside the body of another loop then, it is known as nesting of loop. Any type of loop
can be nested in any type such as while, do while, for. For example nesting of for loop can be represented as
void main()
{

int i,j;

for(i=0;i<2;i++)

for(j=0;j<5; j++) printf(“%d %d”, i, j);


}
Output:
i=0
j=0 1 2 3 4
i=1
j=0 1 2 3 4
Unconditional statements
It is a Keyword which is used to terminate from a loop / block and the
statements after the loop / block will execute.
1. break
2. continue
3. goto
For example,
If we use break inside a while loop, then the loop will terminate.
If we use break inside a nested while loop, then the inner while loop
only will terminate.
break :
• The break keyword is used to get control out of the loop.
• It is used inside loops or switch statement.
• It breaks one loop and executes the statement after the loop.
• If it is a nested loop, then only inside loop will break.
EX: #include <stdio.h>
int main() {
int i;
for (i = 1; i < 10; i++)
{
printf("%d\n", i);
if (i == 4)
break;
}
return 0;
}
Output: 1 2 3 4
continue :
• It is similar to break keyword.
• But instead of terminating the loop, it will just go to the next iteration.
• That means, it skips the current iteration and proceeds to the next.
• It is also used inside of loops.
EX:
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 5; i++) {
if (i == 3)
continue;
printf("%d\n", i);
}
}
Output: 1 2 4
goto :
• It is used to transfer the control from one place to another statement.
• In this we have to use a label.
• Label purpose is to identify the place where the control has to be transferred.
• There are two ways to use label forward jump and backward jump
goto label;
….
….
label :
….
….
label:
….
….
goto label;
….
….
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
#include <stdio.h>
int main() {
printf("hello\n");
goto g1;
printf("how are you");
g1:
printf("Hi\n");
return 0;
}
Difference between break and continue statement:
Top-down design
Top-down design is a software engineering and problem-solving approach that
starts with a high-level view of a system or problem and then progressively breaks
it down into smaller and more manageable components or modules.
Here's an overview of the top-down design process:
 Start with a Problem or System Overview: Begin by understanding the overall
problem you need to solve or the system you want to build. Define the main
goals and objectives.
 Decompose into Modules: Identify the major components or modules needed
to achieve the system's goals. These are often represented as high-level
functions or procedures.
 Refine Each Module: For each major module identified, break it down
further into smaller sub-modules or functions. Continue this process
until you have a detailed and hierarchical structure of modules.
 Define Interfaces: Clearly define the interfaces between the modules,
specifying how they will communicate and exchange data. This helps
ensure that each module can work independently and can be easily
integrated into the overall system.
 Implement the Modules: Begin implementing the individual modules,
starting with the top-level ones. This allows you to work on the most
critical parts of the system first and gradually fill in the details.
 Test and Debug: As you implement each module, test it thoroughly
to ensure it performs its intended function correctly. Debug and fix
any issues that arise.
 Integrate and Test the Whole System: Once all the modules are
developed and tested individually, integrate them into the complete
system. Test the entire system to ensure that it functions as expected
and meets the overall goals.
 Refine and Iterate: It's common for the design to evolve as you
implement and test the system. Be prepared to refine and iterate on
both the high-level design and individual modules as needed to
address any issues that arise during development.
Top-down design has several advantages:

● Modularity

● Clarity

● Parallel Development

● Debugging and Testing

● Scalability
Introduction to problem solving
Algorithms are step-by-step sets of instructions or rules for solving a particular problem or
performing a specific task. They are fundamental in computer science and mathematics and play
a crucial role in various fields, including computer programming, data analysis, artificial
intelligence, and more. Here are some key points to understand about algorithms:

Purpose: Algorithms are designed to solve specific problems or accomplish particular tasks
efficiently and effectively. They can be used to perform calculations, sort data, search for
information, make decisions, and much more.

Steps: Algorithms consist of a finite sequence of well-defined steps or instructions. Each step
is clear and unambiguous, with a specific purpose or operation.

Input and Output: Algorithms take some input, process it according to the defined steps, and
produce an output. The input could be data, variables, or other information relevant to the
problem being solved.
Efficiency: One of the key considerations in designing algorithms is
efficiency. An efficient algorithm should use as few resources (such as
time and memory) as possible to produce the desired output. This is
particularly important in computer science and related fields.

Correctness: An algorithm must produce the correct output for all


valid inputs. Ensuring the correctness of an algorithm is essential to
avoid errors and unexpected behavior.

Termination: Algorithms must terminate after a finite number of


steps. Infinite loops or processes that never end are not considered
valid algorithms.
How to write an algorithm or implementation of algorithm:
1. First define the problem you want the algorithm to solve.
For example, suppose we want to write an algorithm to find the maximum value from a list of numbers.
2. Break the problem down into smaller, manageable steps.
• Initialize the 'max' variable to the first value in the list.
• For each subsequent value in the list, compare with "max".
• If the value is greater than "max", set "max" to that value.
• Continue doing this until every value in the list has been compared.
• Returns the final "max" value.
FLOW CHART
Flowcharts are a graphical representation of a program's logic or a set of steps to solve a specific problem. They are not specific to the C programming language but can be used
to design algorithms and understand the flow of control in C programs. Here's how you can create a basic flowchart for a C program:
Example 1:
Design a flowchart for adding two numbers entered by the user.
Example 2:
Design a flowchart for finding the largest among three numbers entered by the user.
Example 3:
Draw a flowchart to calculate the average of two numbers.
Program verification and the efficiency of algorithms are two important aspects of software
development and computer science.

Program Verification:
Program verification is the process of ensuring that a program or software system behaves as
intended, meets its specifications, and does not have any critical bugs or errors. This is crucial
for building reliable and safe software.

There are several techniques and tools for program verification:


● Testing: This is the most common form of program verification. It involves running the
program with various inputs and checking whether the output matches the expected
results. While testing can find many bugs, it cannot prove the absence of all errors.
● Static Analysis: Static analysis tools examine the program's source code without
executing it. They can detect potential issues such as null pointer dereferences, buffer
overflows, and code that violates coding standards. However, they may produce false
positives and false negatives.
● Formal Methods: Formal methods involve mathematically proving the correctness
of a program. This can be done through techniques like formal specification
languages (e.g., Z or TLA+), model checking, and theorem proving. Formal methods
are especially useful for critical systems like aerospace or medical software.
● Type Systems: Type systems in programming languages can catch certain classes of
errors at compile time. Languages with strong type systems, like Haskell or Rust,
provide a level of program verification by design.
Program verification is essential for ensuring the reliability and correctness of software,
particularly in safety-critical applications.
Efficiency of Algorithms:
The efficiency of algorithms is concerned with how well a particular algorithm solves a
problem in terms of time and space resources. Efficient algorithms are crucial for
optimizing software performance. Here are some key considerations:
● Time Complexity: This measures the amount of time an algorithm takes to solve a
problem as a function of the problem's size (usually denoted as "Big O" notation).
Algorithms with lower time complexity are more efficient.
● Space Complexity: This measures the amount of memory an algorithm requires to
solve a problem. Efficient algorithms use minimal memory resources.
● Algorithm Design: The choice of algorithm can significantly impact efficiency.
Different algorithms may have different time and space complexities for the same
problem. For example, quicksort is generally faster than bubblesort for sorting large
lists.
● Data Structures: Efficient data structures, like hash tables or balanced trees, can
improve the efficiency of algorithms for specific tasks, such as searching or indexing.
● Optimization Techniques: Algorithm optimization involves improving the
performance of existing algorithms. This can include techniques like memoization,
dynamic programming, or parallelization.
Efficient algorithms are essential for ensuring that software performs well in practice,
especially for large-scale applications and real-time systems.

You might also like