0% found this document useful (0 votes)
20 views66 pages

ENCO101 - Unit 8

The document provides an overview of the C programming language, detailing its history, applications, and importance in software development. It includes a step-by-step guide on compiling a C application using Visual Studio, along with fundamental programming concepts such as variables, input/output operations, and structured programming. Additionally, it introduces secure programming practices and illustrates basic C programming through simple examples.

Uploaded by

rohan.shiksha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views66 pages

ENCO101 - Unit 8

The document provides an overview of the C programming language, detailing its history, applications, and importance in software development. It includes a step-by-step guide on compiling a C application using Visual Studio, along with fundamental programming concepts such as variables, input/output operations, and structured programming. Additionally, it introduces secure programming practices and illustrates basic C programming through simple examples.

Uploaded by

rohan.shiksha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

WELCOME

to The School of
Engineering and
Science

Presenter: Darryl Kucherera


The C Programming Language
• C programming is a powerful and versatile language that has been fundamental to the development of
software and systems for decades.
• It was developed in the early 1970s by Dennis Ritchie at Bell Labs and has since become one of the most
widely used programming languages in the world.
• C initially became widely known as the development language of the UNIX operating system.
• Many of today’s leading operating systems are written in C and/or C++.
• C is mostly hardware-independent—with careful design, it’s possible to write C programs that are portable
to most computers.
• By mastering C, you'll gain insights into how computers operate at a fundamental level, giving you a
deeper appreciation for software development and preparing you for more advanced programming
challenges.
• Whether you're interested in developing software, working on embedded systems, or exploring
computer science, learning C is an essential step in your programming journey.
Built for Performance

Application Description
Operating systems C’s portability and performance make it desirable for implementing
operating systems, such as Linux and portions of Microsoft’s
Windows and Google’s Android. Apple’s macOS is built in
Objective-C, which was derived from C.
Embedded systems Most of the microprocessors produced each year are embedded in
devices other than general-purpose computers. These embedded
systems include navigation systems, smart home appliances, home
security systems, smartphones, tablets, robots, intelligent traffic
intersections and more. C is one of the most popular programming
languages for developing embedded systems, which typically need
to run as fast as possible and conserve memory. For example, a
car’s antilock brakes must respond immediately to slow or stop the
car without skidding; video-game controllers should respond
instantaneously to prevent lag between the controller and the
game action.
Built for Performance

Application Description
Real-time systems Real-time systems are often used for “mission-critical” applications
that require nearly instantaneous and predictable response times.
Real-time systems need to work continuously. For example, an air-
traffic-control system must continuously monitor planes’ positions
Communications systems and velocities and report that information to air-traffic controllers
without delay so they can alert the planes to change course if
there’s a possibility of a collision.
Communications systems need to route massive amounts of data
to their destinations quickly to ensure that things such as audio
and video are delivered smoothly and without delay.
Compiling a C Application with
Visual Studio
1. Download Visual Studio
Visit the Website: Go to the official https://visualstudio.microsoft.com
Select Edition: Choose the appropriate edition (Community, Professional, or Enterprise). The Community edition is free
and suitable for most users.
Download Installer: Click "Download" to get the Visual Studio Installer.

2. Install Visual Studio


Run the Installer: Open the downloaded installer and run it.
Choose Workloads: In the installer, select the "Desktop development with C++" workload. This includes all necessary
tools for C programming.
Install: Click "Install" and wait for the process to complete.

3. Set Up a C Project
Launch Visual Studio: Open Visual Studio after installation.
Create a New Project: Click on "Create a new project" from the start window.
Select Project Type: Choose "Console App" under C++ and give your project a name.
Configure: Set the project location and other options as needed, then click "Create."
Compiling a C Application with
Visual Studio
4. Write and Run C Code
Open Code Editor: Once the project is created, Visual Studio will open the main code editor.
Write Code: Enter your C code in the main.cpp file (you can write C code even though the file extension is .cpp).
Build the Project: Click "Build" from the top menu, then "Build Solution" to compile the code.
Run the Program: After building, click "Debug" > "Start Without Debugging" to run your program and see the output.

5. Debugging and Error Handling


Use the Debugger: If you encounter issues, Visual Studio's built-in debugger allows you to step through code, set
breakpoints, and inspect variables.
Fix Errors: Review any errors or warnings in the Output or Error List windows and correct your code as needed.

6. Save and Exit


Save Your Work: Always save your project before closing.
Exit Visual Studio: You can close Visual Studio once you’ve completed your work.
These steps will get you started with C programming using Visual Studio, allowing you to write, compile, and debug your
code effectively.
Covered
■ Use simple input and output statements.
■ Use the fundamental data types.
■ Learn computer memory concepts.
■ Use arithmetic operators.
■ Learn the precedence of arithmetic operators.
■ Write simple decision-making statements.
■ Begin focusing on secure C programming practices.
Introduction
• The C language facilitates a structured and disciplined approach to computer-program design.
• This chapter introduces C programming and presents several examples illustrating many fundamental C
features.
• We analyze each example one statement at a time.
• In Chapters 3 and 4, we introduce structured programming—a methodology that will help you produce
clear, easy-to-maintain programs.
• We then use the structured approach throughout the remainder of the text.
• This chapter concludes with the first of our “Secure C Programming” sections.
A Simple C Program: Printing a Line
of Text
• We begin with a simple C program that prints a line of text.
• The program and its screen output are shown in Fig. 2.1
A Simple C Program: Printing a Line
of Text
Comments
• Lines 1 and 2
• // fig02_01.c
• // A first program in C.
• begin with //, indicating that these two lines are comments.
• You insert comments to document programs and improve program readability.
• Comments do not cause the computer to perform actions when you execute
programs—they’re simply ignored.
• It’s our convention in each program to use the line 1 comment to specify the file-
name, and the line 2 comment to describe the program’s purpose.
• Comments also help other people read and understand your program.
• You can also use /*…*/ multi-line comments in which everything from /* on the first
line to */ at the end of the last line is a comment.
• We prefer the shorter // comments because they eliminate common programming
errors that occur with /*…*/ comments, such as accidentally omitting the closing */.
A Simple C Program: Printing a Line
of Text
#include Preprocessor Directive
• Line 3
• #include <stdio.h> is a C preprocessor directive.
• The preprocessor handles lines beginning with # before compilation.
• Line 3 tells the preprocessor to include the contents of the standard
input/output header (<stdio.h>).
• This is a file containing information the compiler uses to ensure that you
correctly use standard input/output library functions such as printf (line 7).
A Simple C Program: Printing a Line
of Text
The main Function
• Line 6 int main(void) { is a part of every C program.
• The parentheses after main indicate that main is a program building block
called a function.
• C programs consist of functions, one of which must be main.
• Every program begins executing at the function main.
• As a good practice, precede every function by a comment (as in line 5)
stating the function’s purpose.
• Functions can return information.
• The keyword int to the left of main indicates that main “returns” an integer
(whole number) value.
• We’ll explain what it means for a function to “return a value” in Chapter 4
when we use a math function to perform a calculation and in Chapter 5
when we create custom functions.
A Simple C Program: Printing a Line
of Text
The main Function
• For now, simply include the keyword int to the left of main in each of your
programs.
• Functions also can receive information when they’re called upon to execute.
• The void in parentheses here means that main does not receive any
information.
• In Chapter 15, we’ll show an example of main receiving information.
• A left brace, {, begins each function’s body (end of line 6).
• A corresponding right brace, }, ends each function’s body (line 8).
• When a program reaches main’s closing right brace, the program terminates.
• The braces and the portion of the program between them form a block—an
important program unit that we’ll discuss more in subsequent chapters.
A Simple C Program: Printing a Line
of Text
An Output Statement
• Line 7
• printf("Welcome to C!\n"); instructs the computer to perform an action,
namely to display on the screen the string of characters enclosed in the
quotation marks.
• A string is sometimes called a character string, a message or a literal.
• The entire line 7—including the “call” to the printf function to perform its
task, the printf’s argument within the parentheses and the semicolon (;)—is
called a statement.
• Every statement must end with a semicolon statement terminator.
• The “f” in printf stands for “formatted.”
• When line 7 executes, it displays the message Welcome to C! on the screen.
• The characters usually print as they appear between the double quotes, but
notice that the characters \n were not displayed.
A Simple C Program: Printing a Line
of Text
Escape Sequences
• In a string, the backslash (\) is an escape character.
• It indicates that printf should do something out of the ordinary.
• In a string, the compiler combines a backslash with the next character to
form an escape sequence.
• The escape sequence \n means newline.
• When printf encounters a newline in a string, it positions the output cursor
to the beginning of the next line.
• Some common escape sequences are listed below:
A Simple C Program: Printing a Line
of Text
The Linker and Executables
• Standard library functions like printf and scanf are not part of the C
programming language.
• For example, the compiler cannot find a spelling error in printf or scanf.
• When compiling a printf statement, the compiler merely provides space in
the object program for a “call” to the library function.
• But the compiler does not know where the library functions are—the linker
does.
• When the linker runs, it locates the library functions and inserts the proper
calls to these functions in the object program.
• Now the object program is complete and ready to execute. The linked
program is called an executable.
• If the function name is misspelled, the linker will spot the error—it will not
be able to match the name in the program with the name of any known
function in the libraries.
A Simple C Program: Printing a Line
of Text
Using Multiple printfs
• The printf function can display Welcome to C! several different ways. For
example, Fig. 2.2 uses two statements to produce the same output as Fig.
2.1.
• This works because each printf resumes printing where the previous one
finished.
• Line 7 displays Welcome followed by a space (but no newline).
• Line 8’s printf begins printing on the same line immediately following the
space.
A Simple C Program: Printing a Line
of Text
Displaying Multiple Lines with a Single printf
• One printf can display several lines, as in Fig.
• Each \n moves the output cursor to the beginning of the next line.
Another Simple C Program: Adding
Two Integers
Another Simple C Program: Adding Two Integers
• Variables are containers for storing data values, like numbers and
characters.
• In C, there are different types of variables (defined with different
keywords), for example:
• int - stores integers (whole numbers), without decimals, such as 123
or -123
• float - stores floating point numbers, with decimals, such as 19.99 or
-19.99
• char - stores single characters, such as 'a' or 'B'. Characters are
surrounded by single quotes
Another Simple C Program: Adding
Two Integers
Another Simple C Program: Adding Two Integers
• Our next program uses the scanf standard library function to obtain
two integers typed by a user at the keyboard, then computes their sum
and displays the result using printf.
• The program and sample output are shown in Fig. 2.4.
• In the input/output dialog box of Fig. 2.4, we emphasize the numbers
entered by the user in bold.
• The comment in line 2 states the program’s purpose.
• Again, the program begins execution with main (lines 6–20)—the
braces at lines 6 and 20 mark the beginning and end of main’s body,
respectively.
Another Simple C Program: Adding
Two Integers
Variables and Variable Definitions
• Lines 7 and 8
int integer1 = 0; // will hold first number user enters
int integer2 = 0; // will hold second number user enters
• are definitions.
• The names integer1 and integer2 are variables—locations in memory
where the program can store values for later use.
• These definitions specify that integer1 and integer2 have type int.
• This means they’ll hold whole-number integer values, such as 7, –11, 0
and 31914. Lines 7 and 8 initialize each variable to 0 by following the
variable’s name with an = and a value.
• Although it’s not necessary to explicitly initialize every variable, doing
so will help avoid many common problems.
Another Simple C Program: Adding
Two Integers
Define Variables Before They Are Used
• All variables must be defined with a name and a type before they can
be used in a program.
• You can place each variable definition anywhere in main before that
variable’s first use in the code.
• In general, you should define variables close to their first use.
Another Simple C Program: Adding
Two Integers
• Identifiers and Case Sensitivity
• Variable Naming Rules in C
• Valid Characters: Letters, digits, underscores (_); cannot start with a digit.
• Case Sensitivity: a1 ≠ A1.
• Start with lowercase (special meanings for uppercase-start or ALL_CAPS later).
• Use camelCase (e.g., totalCommissions) or underscores (e.g.,
total_commissions) (Prefer camelCase)
• Choose meaningful names for self-documenting code.
• Avoid leading _ to prevent conflicts.
Another Simple C Program: Adding
Two Integers
Prompting Messages
• Line 10
• printf("Enter first integer: "); // prompt
• displays "Enter first integer: ".
• This message is called a prompt because it tells the user to take a
specific action.
Another Simple C Program: Adding
Two Integers
The scanf Function and Formatted Inputs
• Line 11
• scanf("%d", &integer1); // read an integer
• uses scanf to obtain a value from the user.
• The function reads from the standard input, which is usually the
keyboard.
• The “f” in scanf stands for “formatted.” This scanf has two
arguments—"%d“ and &integer1.
• The "%d" is the format control string.
• It indicates the type of data the user should enter.
• The %d conversion specification specifies that the data should be an
integer—the d stands for “decimal integer”.
• A % character begins each conversion specification.
• scanf’s second argument begins with an ampersand (&) followed by
the variable name.
Another Simple C Program: Adding
Two Integers
The scanf Function and Formatted Inputs (continued)
• The & is the address operator and, when combined with the variable
name, tells scanf the location (or address) in memory of the variable
integer1.
• scanf then stores the value the user enters at that memory location.
• Using the ampersand (&) is often confusing to novice programmers
and people who have programmed in other languages that do not
require this notation.
• For now, just remember to precede each variable in every call to scanf
with an ampersand.
• Some exceptions to this rule are discussed in Chapters 6 and 7. The use
of & will become clear after we study pointers in Chapter 7.
• Forgetting the ampersand (&) before a variable in a scanf statement
typically results in an execution-time error.
• On many systems, this causes a “segmentation fault” or “access
violation.”
Another Simple C Program: Adding
Two Integers
The scanf Function and Formatted Inputs (continued)
• Such an error occurs when a user’s program attempts to access a part
of the computer’s memory to which it does not have access privileges.
• The precise cause of this error will be explained in Chapter 7.
• When line 11 executes, the computer waits for the user to enter a
value for integer1.
• The user types an integer, then presses the Enter key (or Return key) to
send the number to the computer.
• The computer then places the number (or value) in integer1.
• Any subsequent references to integer1 in the program use this same
value.
Another Simple C Program: Adding
Two Integers
Prompting for and Inputting the Second Integer
• Line 13
• printf("Enter second integer: "); // prompt
• prompts the user to enter the second integer, then line 14
• scanf("%d", &integer2); // read an integer
• obtains a value for variable integer2 from the user.
Defining the sum Variable
• Line 16
• int sum = 0; // variable in which sum will be stored
• defines the int variable sum and initializes it to 0 before we use sum in line 17.
Assignment Statement
• The assignment statement in line 17
• sum = integer1 + integer2; // assign total to sum
• calculates the total of variables integer1 and integer2, then assigns the result
to variable sum using the assignment operator (=).
• The statement is read as, “sum gets the value of the expression integer1 +
integer2.”
• Most calculations are performed in assignments.
Another Simple C Program: Adding
Two Integers
Binary Operators
• The = operator and the + operator are binary operators—each has two
operands.
• The + operator’s operands are integer1 and integer2.
• The = operator’s operands are sum and the value of the expression
integer1 + integer2.
• Place spaces on either side of a binary operator to make the operator
stand out and make the program more readable.
Printing with a Format Control String
• The format control string "Sum is %d\n" in line 19
• printf("Sum is %d\n", sum); // print sum
• contains some literal characters to display ("Sum is ") and the conversion
specification %d, which is a placeholder for an integer.
• The sum is the value to insert in place of %d.
• The conversion specification for an integer (%d) is the same in both printf
and scanf—this is true for most, but not all, C data types.
Another Simple C Program: Adding
Two Integers
Combining a Variable Definition and Assignment Statement
• You can initialize a variable in its definition.
• For example, lines 16 and 17 can add the variables integer1 and integer2,
then initialize the variable sum with the result:
• int sum = integer1 + integer2; // assign total to sum

Calculations in printf Statements


• Actually, we do not need the variable sum, because we can perform the
calculation in the printf statement.
• So, lines 16–19 can be replaced with printf("Sum is %d\n", integer1 +
integer2);
Arithmetic in C
• Most C programs perform calculations using the following binary
arithmetic operators:
• Note the use of various special symbols not used in algebra. The asterisk
(*) indicates multiplication, and the percent sign (%) denotes the
remainder operator (introduced below).
• In algebra, to multiply a times b, we place these single-letter variable
names side-by-side, as in ab.
• In C, ab would be interpreted as a single, two-letter name (or identifier).
• Most programming languages denote multiplication by using the *
operator, as in a * b.
Arithmetic in C
• Let’s consider the evaluation of several expressions.
• Each example lists an algebraic expression and its C equivalent.
• The following expression calculates the average (arithmetic mean) of five terms:

• In the C statement, parentheses are required to group the additions because division has higher precedence
than addition.
• The entire quantity (a + b + c + d + e) should be divided by 5.
• If we erroneously omit the parentheses, we obtain a + b + c + d + e /5, which evaluates incorrectly as
• The following expression is the equation of a straight line:
Arithmetic in C
• No parentheses are required.
• Multiplication evaluates first because it has higher precedence than addition.
• The following expression contains remainder (%), multiplication, division, addition, subtraction and
assignment operations:

• The circled numbers indicate the order in which C evaluates the operators.
• The multiplication, remainder and division evaluate first left-to-right (that is, they group left-to-right)
because they have higher precedence than addition and subtraction.
• Next, the addition and subtraction evaluate left-to-right.
• Finally, the result is assigned to z.
Decision Making: Equality and Relational
Operators
• Executable statements either perform
actions like calculations, input and output, or,
as you’re about to see, make decisions.
• For example, a program might determine
whether a person’s grade on an exam is
greater than or equal to 60, so it can decide
whether to print the message
“Congratulations! You passed.”
• A condition is an expression that can be true
(that is, the condition is met) or false (that is,
the condition isn’t met).
• This section introduces the if statement,
which allows a program to make a decision
based on a condition’s value.
• If the condition is true, the statement in the if
statement’s body executes; otherwise, it
does not.
Decision Making: Equality and Relational
Operators
Confusing the Equality Operator == with the
Assignment Operator
• Confusing == with the assignment operator (=) is a
common programming error.
• To avoid this confusion, read the equality operator as
“double equals” and the assignment operator as
“gets” or “is assigned the value of.”
• As you’ll see, confusing these operators can cause
difficult-to-find logic errors rather than compilation
errors.
Demonstrating the if Statement
• Figure 2.5 uses six if statements to compare two
numbers entered by the user.
• For each if statement with a true condition, the
corresponding printf executes.
• The program and three sample execution outputs are
shown in the figure.
Demonstrating the if Statement
Even and Odd numbers
Heart Rate Monitor
Introduction
■ Use basic problem-solving techniques.
■ Develop algorithms through the process of top-down, stepwise
refinement.
■ Select actions to execute based on a condition using the if and if…else
selection statements.
■ Execute statements in a program repeatedly using the while iteration
statement.
■ Use counter-controlled iteration and sentinel-controlled iteration.
■ Use structured programming techniques.
■ Use increment, decrement and assignment operators.
Algorithms
• The solution to any computing problem involves executing a series of actions in a
specific order.
• An algorithm is a procedure for solving a problem in terms of
1. the actions to execute, and
2. the order in which these actions should execute.
• The following example shows that correctly specifying the order in which the
actions should execute is important.
• Consider the “rise-and-shine algorithm” followed by one junior executive for
getting out of bed and going to work:
1. Get out of bed,
2. take-off pyjamas,
3. take a shower,
4. get dressed,
5. eat breakfast, and
6. carpool to work.
• This routine gets the executive to work well prepared to make critical
decisions.
• Suppose that the same steps are performed in a slightly different order:
Algorithms
• Suppose that the same steps are performed in a slightly
different order:
1. Get out of bed,
2. take-off pyjamas,
3. get dressed,
4. take a shower,
5. eat breakfast,
6. carpool to work.
• In this case, our junior executive shows up for work soaking wet.
• Specifying the order in which statements should execute in a computer
program is called program control.
• In this and the next chapter, we investigate C’s program control
capabilities.
Pseudocode
• Pseudocode is an informal artificial language similar to everyday English that helps you
develop algorithms before converting them to structured C programs.
• Pseudocode is convenient and user friendly.
• It helps you “think out” a program before writing it in a programming language.
• Computers do not execute pseudocode.
• Pseudocode consists purely of characters, so you may type it in any text editor.
• Pseudocode describes the actions and decisions that will execute once you convert the
pseudocode to C and run the program.
• Definitions are not executable statements they’re simply messages to the compiler.
• For example, the definition
• int i = 0;
• tells the compiler variable i’s type, instructs the compiler to reserve space in memory for
the variable and initializes it to 0.
• But this definition does not perform an action when the program executes, such as
input, output, a calculation or a comparison.
• So, some programmers do not include definitions in their pseudocode.
• Others choose to list each variable and briefly mention its purpose.
Control Structures
• Böhm and Jacopini’s work demonstrated that all programs could be written in
terms of three control structures, namely the sequence structure, the
selection structure and the iteration structure.
• The sequence structure is simple—unless directed otherwise, the computer
executes C statements one after the other in the order in which they’re
written.
• Flowcharts
• A flowchart is a graphical representation of an algorithm or of a portion of an
algorithm.
• You draw flowcharts using certain special-purpose symbols such as rectangles,
diamonds, rounded rectangles, and small circles, connected by arrows called
flowlines.
• Flowcharts help you develop and represent algorithms.
• Flowcharts clearly show how control structures operate.
• Consider the following flowchart for a sequence structure in a portion of an
algorithm that calculates the class average on a quiz:
Control Structures

• The rectangle (or action) symbol indicates any action, such as a calculation,
input or output.
• The flowlines indicate the order in which to perform the actions.
• This program segment first adds grade to total, then adds 1 to counter.
• As we’ll soon see, anywhere in a program a single action may be placed, you
may place several actions in sequence.
• When drawing a flowchart for a complete algorithm, the first symbol is a
rounded rectangle symbol containing “Begin”, and the last is a rounded
rectangle containing “End”.
• When drawing only a portion of an algorithm, we omit the rounded rectangle
symbols in favor of using small circles called connector symbols.
Control Structures

The if Selection Statement


C provides three types of selection structures in the form of statements:
• The if single-selection statement selects (performs) an action (or group
of actions) only if a condition is true.
• The if…else double-selection statement performs one action (or group of
actions) if a condition is true and a different action (or group of actions) if
the condition is false.
• The switch multiple-selection statement (discussed in the next chapter)
performs one of many different actions, depending on the value of an
expression.
Iteration Statements in C
• C provides three types of iteration structures in the form of statements,
namely while (Section 3.7), do…while, and for.
• These statements perform tasks repeatedly.
• We discuss do…while and for in the next chapter.
The if Selection Statement
• Selection statements choose among alternative courses of action.
• For example, suppose the passing grade on an exam is 60.
• The following pseudocode statement determines whether the condition “student’s
grade is greater than or equal to 60” is true or false:
• If student’s grade is greater than or equal to 60
• Print “Passed”
• If true, then “Passed” is printed, and the next pseudocode statement in order is
“performed.”
• Remember that pseudocode isn’t a real programming language.
• If false, the printing is ignored, and the next pseudocode statement in order is
performed.
• The preceding pseudocode is written in C as
if (grade >= 60)
{
puts("Passed");
} // end if
• Of course, you’ll also need to declare the int variable grade, but the C if statement code
corresponds closely to the pseudocode.
if Statement Flowchart
• It contains perhaps the most important flowchart
symbol—the diamond (or decision) symbol, which
indicates a decision is to be made.
• The decision symbol’s expression typically is a
condition that can be true or false.
• The two flowlines emerging from it indicate the paths
to take when the expression is true or false.
• Decisions can be based on any expression’s value—
zero is false, and nonzero is true.
• The if statement is a single-entry/single-exit
statement.
• We’ll soon learn that the flowchart segment for the
remaining control structures also can contain
rectangle symbols to indicate the actions to be
performed and diamond symbols to indicate decisions
to be made.
• This is the action/decision model of programming
we’ve been emphasizing.
The if else Selection
Statement
• The if…else selection statement specifies different actions to perform when the
• condition is true or false. For example, the pseudocode statement
• If student’s grade is greater than or equal to 60
• Print “Passed”
• else
• Print “Failed”
• prints “Passed” if the student’s grade is greater than or equal to 60; otherwise, it prints
• “Failed.” In either case, after printing, the next pseudocode statement in sequence
• “executes.” The else’s body also is indented. If there are several levels of indentation
• in a program, each should be indented the same additional amount of space. The preceding
• pseudocode may be written in C as
• if (grade >= 60) {
• puts("Passed");
• } // end if
• else {
• puts("Failed");
• } // end else
if…else Statement Flowchart
• The if…else selection statement specifies different actions to
perform when the condition is true or false. For example, the
pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
• prints “Passed” if the student’s grade is greater than or equal
to 60; otherwise, it prints “Failed.”
• In either case, after printing, the next pseudocode statement
in sequence “executes.”
• The else’s body also is indented.
• If there are several levels of indentation in a program, each
should be indented the same additional amount of space.
if (grade >= 60) {
puts("Passed");
} // end if
else {
puts("Failed");
} // end else
Conditional Expressions
• The conditional operator (?:) is closely related to the if…else statement.
• This operator is C’s only ternary operator—that is, it takes three operands.
• A conditional operator and its three operands form a conditional expression.
• The first operand is a condition.
• The second is the conditional expression’s value if the condition is true.
• The third is the conditional expression’s value if the condition is false.
• For example, the conditional-expression argument to the following puts
statement evaluates to the string "Passed" if the condition grade >= 60 is true;
otherwise, it evaluates to the string "Failed":
puts((grade >= 60) ? "Passed" : "Failed");
• Conditional operators can be used in places where if…else statements cannot,
including expressions and arguments to functions (such as printf).
• Use expressions of the same type for the second and third operands of the
conditional operator (?:) to avoid subtle errors.
• false true
• print “Failed” grade >= 60 print “Passed”
The while Repetition Statement
• Nested if…else statements test for multiple cases by placing if…else statements
inside if…else statements.
• For example, the following pseudocode statement prints:
• A for grades greater than or equal to 90, B for grades greater than or equal to
80 (but less than 90), C for grades greater than or equal to 70 (but less than
80), D for grades greater than or equal to 60 (but less than 70), and F for all
other grades.
• If the variable grade is greater than or equal to 90, all four conditions are true,
but only the puts statement after the first test executes.
• Then, the else part of the “outer” if…else statement is skipped, bypassing the
rest of the nested if…else statement.
Blocks and Compound Statements
• To include several statements in an if’s body, you must • If grade is less than 60, both puts statements in the
enclose the statements in braces ({ and }). else execute and the code prints:
Failed.
• A set of statements contained within a pair of braces
You must take this course again.
is called a compound statement or a block.
• A compound statement can be placed anywhere in a • The braces surrounding the two statements in the else
program that a single statement can be placed. clause are important.
• The following if…else statement’s else part includes a • Without them, the statement puts("You must take this
compound statement containing two statements to course again."); would be outside the else’s body (and
execute if the condition is false: outside the if…else statement) and would execute
regardless of whether the grade was less than 60, so
if (grade >= 60) { even a passing student would have to take the course
puts("Passed."); again.
} // end if
else { • To avoid problems like this, always include your
puts("Failed."); control statements’ bodies in braces ({ and }), even if
puts("You must take this course again."); those bodies contain only a single statement.
} // end else • This solves the “dangling-else” problem, which we
discuss in this chapter’s exercises.
The while Iteration
Statement
• An iteration statement (also called a repetition statement or loop)
repeats an action while some condition remains true.
• The pseudocode statement
While there are more items on my shopping list
Purchase next item and cross it off my list

• describes the iteration that occurs during a shopping trip.


• The condition “there are more items on my shopping list” may be true or
false.
• If it’s true, the shopper performs the action “Purchase next item and
cross it off my list” repeatedly while the condition remains true.
• Eventually, the condition will become false (when the last item on the
shopping list has been purchased and crossed off the list).
• At this point, the iteration terminates, and the first pseudocode
statement after the iteration statement “executes.”
Calculating the First Power of 3 Greater
Than 100
• As a while statement example, consider a program segment
that finds the first power of 3 larger than 100.
• The integer variable product is initialized to 3.
• When the following code segment finishes executing,
product will contain the desired answer:
• int product = 3;
• while (product <= 100) {
• product = 3 * product;
• }
• The loop repeatedly multiplies product by 3, so it takes on
the values 9, 27 and 81 successively.
• When product becomes 243, the condition product <= 100
becomes false, terminating the iteration—product’s final
value is 243.
• Execution continues with the next statement after the while.
An action in the while statement’s body must eventually
cause the condition to become false; otherwise, the loop will
never terminate— a logic error called an infinite loop.
• The statement(s) contained in a while iteration statement
constitute its body, which may be a single statement or a
compound statement.
Formulating Algorithms Case Study 1: Counter-
Controlled Iteration

• To illustrate how algorithms are developed, we solve two variations of a


class-averaging problem in this section and the next.
• Consider the following problem statement:
A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz
are available to you. Determine the class average on the quiz.

• The class average is the sum of the grades divided by the number of
students.
• The algorithm to solve this problem must input the grades, then calculate
and display the class average.
Pseudocode for the Class-Average Problem
• Let’s use pseudocode to list the actions to execute
and specify the order in which they should execute.
• We use counter-controlled iteration to input the
grades one at a time.
• This technique uses a variable called a counter to
specify the number of times a set of statements
should execute. In this example, we know that ten
students took a quiz, so we need to input 10 grades.
• Iteration terminates when the counter exceeds 10.
• In this case study, we simply present the final
pseudocode algorithm (Fig. 3.1) and the
corresponding C program (Fig. 3.2).
• In the next case study, we show how to develop
pseudocode algorithms.
• Counter-controlled iteration is often called definite
iteration because the number of iterations is known
before the loop begins executing.
Class-average problem with
counter-controlled iteration
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

• Let’s generalize the class-average problem. Consider the following problem:


Develop a class-averaging program that will process an arbitrary number of grades each time the
program is run.
• In the first class-average example, we knew there were 10 grades in advance.
• In this example, no indication is given of how many grades the user might
input.
• The program must process an arbitrary number of grades.
• How can the program determine when to stop inputting grades?
• How will it know when to calculate and print the class average?
Sentinel Values
• One way is to use a sentinel value to indicate “end of data entry.” A sentinel
value also is called a signal value, a dummy value, or a flag value.
• The user types grades until all legitimate grades have been entered.
• The user then types the sentinel value to indicate “the last grade has been
entered.”
• Sentinel-controlled iteration is often called indefinite iteration because the
number of iterations isn’t known before the loop begins executing.
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

• You should choose a sentinel value that cannot be confused with an


acceptable input value.
• Grades on a quiz are non-negative integers, so –1 is an acceptable
sentinel value for this problem.
• Thus, a run of the class-average program might process a stream of
inputs such as 95, 96, 75, 74, 89 and –1.
• The program would then compute and print the class average for the
grades 95, 96, 75, 74, and 89.
• The sentinel value –1 should not enter into the averaging calculation.
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

• We approach the class-average program with a technique called top-down,


stepwise refinement, which is essential to developing well-structured
programs.
• We begin with a pseudocode representation of the top:
• Determine the class average for the quiz
• The top is a single statement that conveys the program’s overall function.
• As such, the top is, in effect, a complete representation of a program.
• We divide the top into smaller tasks listed in the order in which they need to
be performed.
• This results in the following first refinement:
• Initialize variables
• Input, sum, and count the quiz grades
• Calculate and print the class average
• Here, only the sequence structure has been used—the steps listed should
execute in order, one after the other.
• Each refinement, as well as the top itself, is a complete specification of the
algorithm. Only the level of detail varies.
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

• Second Refinement
• To proceed to the next level of refinement, i.e., the second refinement, we commit to
specific variables. We need:
• a running total of the grades,
• a count of how many grades have been processed,
• a variable to receive the value of each grade as it is input and
• a variable to hold the calculated average.
• The pseudocode statement
• Initialize variables
• can be refined as follows:
• Initialize total to zero
• Initialize counter to zero
• Only the total and counter need to be initialized.
• The variables for the calculated average and the grade the user inputs need not be
initialized because their values will be calculated and input from the user, respectively.
• The pseudocode statement
• Input, sum, and count the quiz grades
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

• The program will test for this value after each grade is input and will terminate the loop when
the sentinel is entered.
• The refinement of the preceding pseudocode statement is then
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
• In pseudocode, we do not use braces around the set of statements that form a loop’s body.
• We simply indent the body statements under the while.
• Again, pseudocode is an informal program-development aid.
• The pseudocode statement
Calculate and print the class average
• may be refined as follows:
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Formulating Algorithms with Top-Down, Stepwise
Refinement Case Study 2: Sentinel-Controlled
Iteration

Initialize total to zero


Initialize counter to zero

Input the first grade (possibly the sentinel)


While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)

If the counter is not equal to zero


Set the average to the total divided by the counter
Print the average

else
Print “No grades were entered”
Phases in a Basic Program

• Many programs can be divided logically into three phases:


• an initialization phase that initializes the program variables,
• a processing phase that inputs data values and adjusts program variables accordingly, and
• a termination phase that calculates and prints the final results.
Number of Pseudocode Refinements
• The pseudocode algorithm solves the more general class-average problem.
• This algorithm was developed after only two levels of refinement.
• Sometimes more levels are necessary.
• You terminate the top-down, stepwise refinement process when the pseudocode algorithm
provides sufficient detail for you to convert the pseudocode to C.
• The most challenging part of solving a problem on a computer is developing the algorithm for the
solution.
• Once a correct algorithm has been specified, producing a working C program usually is
straightforward.
• Many programmers write programs without ever using program-development tools such as
pseudocode.
• They feel their ultimate goal is to solve the problem and that writing pseudocode merely delays
producing final outputs.
• This may work for small programs you develop for your own use.
• But for the substantial programs and software systems you’ll likely work on in industry, a formal
development process is essential.
Assignment Operators
• C provides several assignment operators for
abbreviating assignment expressions.
• For example, the statement
c = c + 3;
• can be abbreviated with the addition assignment
operator += as
c += 3;
• The += operator adds the value of the expression
on the operator’s right to the value of the variable
on the operator’s left then stores the result in the
variable on the left.
• So, the assignment c += 3 adds 3 to c’s current
value.
• The following table shows the arithmetic
assignment operators, sample expressions using
these operators, and explanations:
Increment and Decrement Operators
• The unary increment operator (++) and the unary decrement operator
(--) add one to and subtract one from an integer variable, respectively.
• The following table summarizes the two versions of each operator:
• To increment the variable c by 1, you can use the operator ++ rather
than the expressions c = c + 1 or c += 1.
• If you place ++ or -- before a variable (i.e., prefixed), they’re referred to
as the preincrement or predecrement operators.
• If you place ++ or – after a variable (i.e., postfixed), they’re referred to
as the postincrement or postdecrement operators.
• By convention, unary operators should be placed next to their
operands with no intervening spaces.
• Figure demonstrates the difference between the preincrementing and
the post incrementing versions of the ++ operator.
• Post incrementing the variable c causes it to be incremented after it’s
used in the printf statement.
• Preincrementing the variable c causes it to be incremented before it’s
used in the printf statement.
• The program displays the value of c before and after using ++.
• The decrement operator (--) works similarly.

You might also like