At the end of this lecture students should be able to;
Define the operation of if, if-else, nested if-else, switch and conditional operator.
Justify the control flow of the program under the aforementioned C language constructs.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Describe the looping structures in C programming language.
Practice the control flow of different looping structures in C programming language.
Practice the variants in control flow of different looping structures in C programming language.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Describe the looping structures in C programming language.
Practice the control flow of different looping structures in C programming language.
Practice the variants in control flow of different looping structures in C programming language.
Apply taught concepts for writing programs.
In this video you will learn about
--Introduction to Algorithms
--Characteristics of an Algorithm
--Algorithms Analysis
--Priori Analysis
-- Posterior Analysis
-- Algorithm Efficiency
--Time Complexity
--Space Complexity
--Algorithm Design Tools
-- Pseudocode
--Flowchart
--Asymptotic Analysis/ Notations
--Big-Oh Notation
--Omega Notation
--Theta Notation
Operators and expressions in c languagetanmaymodi4
what is operator in c language
uses of operator in c language
syatax of operator in c language
program of operator in c language
what is expressions in c language
use of expressions in c language
syantax of expressions in c language
Best Techniques To Design Programs - Program Designing TechniquesTech
Now check the Powerpoint presentation about the best techniques to design programs and softwares. For more tutorials and guides visit : www.techora.net
These techniques are also known as the problem solving techniques.These are three types :
1- Pseudocode
2- Algorithm
3- Flowchart
Business value of business models
Requirements for software development
Requirements provide a description of what a proposed software application should do. Without detailed requirements, application development projects fail. Business models capture this detail in a way that is understandable to both the business users and the software developers. Business users do not need to understand how the system will be created; they need to understand how it will support their need. Business models are a better form of requirements for end users.
In this video you will learn about
--Introduction to Algorithms
--Characteristics of an Algorithm
--Algorithms Analysis
--Priori Analysis
-- Posterior Analysis
-- Algorithm Efficiency
--Time Complexity
--Space Complexity
--Algorithm Design Tools
-- Pseudocode
--Flowchart
--Asymptotic Analysis/ Notations
--Big-Oh Notation
--Omega Notation
--Theta Notation
Operators and expressions in c languagetanmaymodi4
what is operator in c language
uses of operator in c language
syatax of operator in c language
program of operator in c language
what is expressions in c language
use of expressions in c language
syantax of expressions in c language
Best Techniques To Design Programs - Program Designing TechniquesTech
Now check the Powerpoint presentation about the best techniques to design programs and softwares. For more tutorials and guides visit : www.techora.net
These techniques are also known as the problem solving techniques.These are three types :
1- Pseudocode
2- Algorithm
3- Flowchart
Business value of business models
Requirements for software development
Requirements provide a description of what a proposed software application should do. Without detailed requirements, application development projects fail. Business models capture this detail in a way that is understandable to both the business users and the software developers. Business users do not need to understand how the system will be created; they need to understand how it will support their need. Business models are a better form of requirements for end users.
At the end of this lecture students should be able to;
Define the C standard functions for managing file input output.
Apply taught concepts for writing programs.
Introduction to control structure in C Programming Language include decision making (if statement, if..else statement, if...else if...else statement, nested if...else statement, switch...case statement), Loop(for loop, while loop, do while loop, nested loop) and using keyword(break, continue and goto)
Detailing about basics of C language and its control structure for learning C Language for beginners. It covers looping statement , control statement etc.
BRANCHING STATEMENTS
if statement
if – else statement
if – else if ladder
Nested if
Goto
Switch case
programs
output
flowchart
Branching / Decision Making Statements
The statements in the program that helps to transfer the control from one part to other parts of the program.
Facilitates program in determining the flow of control
Involves decision making conditions
See whether the condition is satisfied or not
If statement; Execute a set of command line or one command line when the logical condition is true.
It has only one option
syntax with flowchart
If else if ladder; Number of logical statements are checked for executing various statement
If the first condition is true the compiler executes the block followed by first if condition.
If false it skips the block and checks for the next logical condition followed by else if.
Process is continued until a true condition is occurred or an else condition is satisfied.
Switch case; Multiway branch statement
It only requires one argument of any type, which is checked with number of cases.
If the value matches with the case constant, that particular case constant is executed. If not the default statement is executed.
Break statement – used to exit from current case structure
Nested if else; When a series of decisions are involved we use more than one if-else statement.
If condition is true control passes to first block i.e., if block. In this case there may be one more if block.
If condition is false control passes to else block. There we may have one more if block.
This page contains examples and source code on decision making in C programming (to choose a particular statement among many statements) and loops ( to perform repeated task ). To understand all the examples on this page, you should have knowledge of following topics:
if...else Statement
for Loop
while Loop
break and Continue Statement
switch...case
E1 – FundamentalsPlease refer to announcements for details about.docxjacksnathalie
E1 – Fundamentals
Please refer to announcements for details about this exam. Make sure you fill the information below to avoid not being graded properly;
Last Name
Thalheimer
First Name
Kristoffer
Student ID #
Thalheimer
Here is the grading matrix where the TA will leave feedback. If you scored 100%, you will most likely not see any feedback (
Question
# points
Feedback
Max
Scored
1
Tracing
3
2
Testing
2
3
Refactoring
2
4
Debugging
3
Question #1 – Tracing Programs
We are going to trace the following program, i.e. simulate in your head how it would execute on a computer. To help you, a trace table is provided for you to fill.
For each “execution step” of the program, write down in the table the line being executed along with the value of each variable which was modified.
Please note that we omitted the usual main function definition and other #include statements. We assume the following fragment to be inside a main function.
Program to Trace
1
int something = 5;
2
int data = 42;
3
int n = 0;
4
5
for( n = 0 ; data > 0 ; n++){
6
data -= something;
7
}
8
9
if( data < 0) n--;
Trace Table to Fill
Feel free to add / remove rows if necessary
Step #
Line #
Variables Values
Remarks
something
data
n
1
2
3
…
Question #2 – Testing Programs
You are going to write tests for the following program fragment which we assume to be inside a main function. Its requirements are to
· Prompt the user for two int numbers X and Y
· If Y is zero the program should display “Error #1” then exit.
· Otherwise, if any of the two input value is less or equal to zero, it should display “Error #2” then exit.
· Otherwise, it should display how many times Y goes into X.
This is the equivalent of the integer division of X by Y.
Your objective is to write tests which will guarantee
· The program conforms to the requirements
· All possible execution paths have been tested
· Your program does not feature any errors
Program to Test
1
int div = 0;
2
int data = 0;
3
int n = 0;
4
printf("Enter positive int to divide: ");
5
scanf("%d", &data);
6
7
printf("Enter positive int to divide it by: ");
8
scanf("%d", &div);
9
10
if(div == 0){
11
printf("Error #1\n");
12
exit(EXIT_FAILURE);
13
}
14
15
if((data <= 0) || (div <= 0)){
16
printf("Error #2\n");
17
exit(EXIT_FAILURE);
18
}
19
20
for( n = 0 ; data > 0 ; n++){
21
data -= div;
22
}
23
24
if( data < 0) n--;
25
26
printf("Ouput value is %d\n", n);
Tests Table to Fill
Feel free to add / remove rows if necessary
Test #
Inputs’ Values
Expected Results
Explanations;
What did you use this test for?
Why is it not redundant with others?
div
data
n
Error
1
2
3
…
Question #3 – Refactoring Programs
Refactor the following code to improve it in terms of readability, documentation, redundancy. Regarding redundancy, we really don’t like having twice the same printf/scanf but we don’t want a solution where the ...
Similar to COM1407: Program Control Structures – Decision Making & Branching (20)
At the end of this lecture students should be able to;
Define the declaration C strings.
Compare fixed length and variable length string.
Apply strings for functions.
Define string handling functions.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Define, initialize and access to the C stuctuers.
Develop programs using structures in arrays and functions.
Use structures within structures and structures as pointers.
Define, initialize and access to the C unions.
Compare and contrast C structures and unions.
Define memory allocation and de-allocation methods in C.
Develop programs using memory allocation functions.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Define the C standard functions for managing input output.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Define the C pointers and its usage in computer programming.
Describe pointer declaration and initialization.
Apply C pointers for expressions.
Experiment on pointer operations.
Identify NULL pointer concept.
Experiment on pointer to pointer, pointer arrays, arrays with pointers and functions with pointers.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Describe the C arrays.
Practice the declaration, initialization and access linear arrays.
Practice the declaration, initialization and access two dimensional arrays.
Apply taught concepts for writing programs.
At the end of this lecture students should be able to;
Define the terms operators, operands, operator precedence and associativity.
Describe operators in C programming language.
Practice the effect of different operators in C programming language.
Justify evaluation of expressions in programming.
Apply taught concepts for writing programs.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
COM1407: Program Control Structures – Decision Making & Branching
1. COM1407
Computer Programming
Lecture 06
Program Control Structures – Decision
Making & Branching
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
2. Objectives
• At the end of this lecture students should be able
to;
▫ Define the operation of if, if-else, nested if-else,
switch and conditional operator.
▫ Justify the control flow of the program under the
aforementioned C language constructs.
▫ Apply taught concepts for writing programs.
2
3. Decision Making with C
• The C programming language also provides
several decision-making constructs, which are:
▫ The if statement
▫ The switch statement
▫ The conditional operator
3
4. if Statement
• The general format of the ‘if’ statement is as follows:
if ( expression )
Program statement
or
if ( expression )
{
block of statements;
}
• Similarly, in the program statement
if ( count > COUNT_LIMIT )
printf ("Count limit exceededn");
• The printf statement is executed only if the value of count is greater
than the value of COUNT_LIMIT; otherwise, it is ignored.
4
5. if Statement (Cont…)
int main (void)
{
int number;
printf ("Type in your number: ");
scanf ("%i", &number);
if ( number < 0 )
{
number = -number;
}
printf ("The absolute value is %in", number);
return 0;
}
5
If entered number is < 0 the
controller passes in to the if
block and negate the value of
number. Then continue with
the printf statement.
If entered number is >= 0
the controller ignores the if
block and directly passes to
printf statement.
It is no need to specify the
scope using {} of the if block
if it has single statement.
6. if-else Construct
• The general format of the ‘if-else’ statement is as follows;
if (expression)
{
program statement 1;
}
else
{
program statement 2;
}
• The if-else is actually just an extension of the general
format of the if statement.
• If the result of the evaluation of expression is TRUE,
program statement 1, which immediately follows, is
executed; otherwise, program statement 2 is executed.
6
7. if-else Construct (Cont…)
• Similarly, in the program statement:
if ( count > COUNT_LIMIT )
printf ("Count limit exceededn");
else
printf ("Count limit is not exceededn");
• Count limit exceeded message is printed
only if the value of count is greater than the
value of COUNT_LIMIT; otherwise, it executes
the statement within the else block which is
Count limit is not exceeded.
7
8. if-else Construct (Cont…)
#include <stdio.h>
int main (void)
{
int number_to_test, remainder;
printf ("Enter your number to be tested.: ");
scanf ("%i", &number_to_test);
remainder = number_to_test % 2;
if ( remainder == 0 )
printf ("The number is even.n");
if ( remainder != 0 )
printf ("The number is odd.n");
return 0;
}
8
9. Compound Relational Test
• A compound relational test is simply one or more simple relational
tests joined by either the logical AND or the logical OR operator.
• These operators are represented by the character pairs && and ||,
respectively.
• As an example, the C statement
if ( grade >= 70 && grade <= 79 )
++grades_70_to_79;
• increments the value of grades_70_to_79 only if the value of grade
is greater than or equal to 70 and less than or equal to 79.
• In the same way, the statement
if ( index < 0 || index > 99 )
printf ("Error - index out of rangen");
• causes execution of the printf statement if index is less than 0 or
greater than 99.
9
10. Compound Relational Test (Cont…)
• The compound operators can be used to form
extremely complex expressions in C.
• The C language grants the programmer ultimate
flexibility in forming expressions.
• This flexibility is a capability that is often
abused.
• Simpler expressions are almost always easier to
read and debug.
10
11. Compound Relational Test (Cont…)
• When forming compound relational expressions,
liberally use parentheses to aid readability of the
expression and to avoid getting into trouble because
of a mistaken assumption about the precedence of
the operators in the expression.
• You can also use blank spaces to aid in the
expression’s readability.
• An extra blank space around the && and ||
operators visually sets these operators apart from
the expressions that are being joined by these
operators.
11
12. Compound Relational Test (Cont…)
• Candidate Selection ?
#include <stdio.h>
int main (void)
{
int appointmentNo,age,score;
printf ("Enter the appointment number : ");
scanf ("%i", &appointmentNo);
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( (appointmentNo <= 30 && age >= 18) || score >= 40 )
printf ("Ticket issued.n");
else
printf ("You are not eligible.n");
return 0;
}
12
13. Nested if Statement
• In the general format of the if statement, remember that if the
result of evaluating the expression inside the parentheses is
TRUE, the statement that immediately follows is executed.
• It is perfectly valid that this program statement be another if
statement, as in the following statement:
if ( score >= 40 )
if ( age >= 18 )
printf (“Issue Ticketn");
• If the value of score is >=40, the following statement is
executed, which is another if statement.
• This if statement compares the value of age >= 18.
• If the two values are equal, the message “Issue Ticket” is
displayed at the terminal.
13
14. Nested if Statement (Cont…)
• What happen if we add an else clause
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
• In this example else clause belongs to the closest
if statement.
14
15. Nested if Statement (Cont…)
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
return 0;
}
15
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
16. Nested if Statement (Cont…)
• Another approach:
if ( score >= 40 )
{
if ( age >= 18 )
{
printf ("Issue Ticketn");
}
}
else
{
printf ("Not in agen");
}
• In this example else clause belongs to the outer if
statement.
16
17. Nested if Statement (Cont…)
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
{
if ( age >= 18 )
{
printf ("Issue Ticketn");
}
}
else
{
printf ("Not in agen");
}
return 0;
}
17
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
18. Nested if Statement (Cont…)
• Complete version
#include <stdio.h>
int main (void)
{
int age,score;
printf ("Enter age : ");
scanf ("%i", &age);
printf ("Enter score : ");
scanf ("%i", &score);
if ( score >= 40 )
if ( age >= 18 )
printf ("Issue Ticketn");
else
printf ("Not in agen");
else
printf("Not scoredn");
return 0;
}
18
What happen when you
enter following details?
Score = 40 and age 18
Score =20 and age 18
Score = 40 and age 10
19. The else-if Statement
• Without if- else-if approach
if ( expression 1 )
program statement 1
else
if ( expression 2 )
program statement 2
else
program statement 3
19
Suppose you want to make three different decisions based on the value of an
input number. E.g. if the input number < 0, you execute program statement 1,
if the input number == 0, you execute program statement 2 and if the input
number > 0, you execute program statement 3.
if (input < 0 )
print (“-”);
else
if ( input == 0 )
print (“0”);
else
print (“+”);
20. The else-if Statement (Cont…)
20
• With if- else-if approach
if ( expression 1 )
program statement 1
else if ( expression 2 )
program statement 2
else
program statement 3
if (input < 0 )
print (“-”);
else if ( input == 0 )
print (“0”);
else
print (“+”);
This method of formatting improves the readability of the statement and makes it
clearer that a three-way decision is being made.
21. The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
char c;
printf ("Enter a single character:n");
scanf ("%c", &c);
if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
printf ("It's an alphabetic character.n");
else if ( c >= '0' && c <= '9' )
printf ("It's a digit.n");
else
printf ("It's a special character.n");
return 0;
}
21
22. The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
if ( operator == '+' )
printf ("%.2fn", value1 + value2);
else if ( operator == '-' )
printf ("%.2fn", value1 - value2);
else if ( operator == '*' )
printf ("%.2fn", value1 * value2);
else if ( operator == '/' )
printf ("%.2fn", value1 / value2);
return 0;
}
22
23. The else-if Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
if ( operator == '+' )
printf ("%.2fn", value1 + value2);
else if ( operator == '-' )
printf ("%.2fn", value1 - value2);
else if ( operator == '*' )
printf ("%.2fn", value1 * value2);
else if ( operator == '/' )
if ( value2 == 0 )
printf ("Division by zero.n");
else
printf ("%.2fn", value1 / value2);
else
printf ("Unknown operator.n");
return 0;
}
23
24. switch Statement
• Within the type of if-else statement chain the
value of a variable is successively compared
against different values.
• It is so commonly used when developing
programs that a special program statement
exists in the C language for performing precisely
this function.
• The name of the statement is the switch
statement.
24
26. switch Statement (Cont…)
• The expression enclosed within parentheses is
successively compared against the values value1,
value2, ..., valuen, which must be simple
constants or constant expressions.
• If a case is found whose value is equal to the
value of expression, the program statements that
follow the case are executed.
• Note that when more than one such program
statement is included, they do not have to be
enclosed within braces.
26
27. switch Statement (Cont…)
• The break statement signals the end of a
particular case and causes execution of the
switch statement to be terminated.
• Remember to include the break statement at the
end of every case.
• Forgetting to do so for a particular case causes
program execution to continue into the next case
whenever that case gets executed.
27
28. switch Statement (Cont…)
• The special optional case called default is
executed if the value of expression does not
match any of the case values.
• This is conceptually equivalent to the “fall
through” else that you used in the previous if-
else-if example.
28
29. switch Statement (Cont…)
#include <stdio.h>
int main (void)
{
float value1, value2;
char operator;
printf ("Type in your expression.n");
scanf ("%f %c %f", &value1, &operator, &value2);
switch (operator)
{
case '+':
printf ("%.2fn", value1 + value2);
break;
case '-':
printf ("%.2fn", value1 - value2);
break;
29
31. switch Statement (Cont…)
• It is a good programming habit to remember to
include the break at the end of every case.
• When writing a switch statement, bear in mind that
no two case values can be the same.
• However, you can associate more than one case
value with a particular set of program statements.
• This is done simply by listing the multiple case
values (with the keyword case before the value and
the colon after the value in each case) before the
common statements that are to be executed.
31
33. The Conditional Operator
• The conditional operator is a ternary operator;
that is, it takes three operands.
• The two symbols that are used to denote this
operator are the question mark (?) and the colon
(:).
• The first operand is placed before the ?, the
second between the ? and the :, and the third
after the :.
33
34. The Conditional Operator (Cont…)
• The general format of the conditional operator is:
condition ? expression1 : expression2
• Where condition is an expression, usually a relational
expression, that is evaluated first whenever the
conditional operator is encountered.
• If the result of the evaluation of condition is TRUE (that
is, nonzero), then expression1 is evaluated and the result
of the evaluation becomes the result of the operation.
• If condition evaluates FALSE (that is, zero), then
expression2 is evaluated and its result becomes the
result of the operation.
34
35. The Conditional Operator (Cont…)
• The conditional operator is most often used to
assign one of two values to a variable depending
upon some condition.
• For example, suppose you have an integer
variable x and another integer variable s.
• If you want to assign –1 to s if x were less than
zero, and the value of x2 to s otherwise, the
following statement could be written:
s = ( x < 0 ) ? -1 : x * x;
35
36. The Conditional Operator (Cont…)
• Examples
• State what happen in following statements;
maxValue = ( a > b ) ? a : b;
sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1);
printf ("Sign = %in",
( number < 0 ) ? –1 : ( number == 0 ) ? 0 : 1);
36
37. Objective Re-cap
• Now you should be able to:
▫ Define the operation of if, if-else, nested if-else,
switch and conditional operator.
▫ Justify the control flow of the program under the
aforementioned C language constructs.
▫ Apply taught concepts for writing programs.
37