Programming For Engineers 1
Programming For Engineers 1
Programming For Engineers 1
Copyright Notice
Do not remove this notice.
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been produced and communicated to you by or on
behalf of the University of South Australia pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the
Act. Any further reproduction or communication of this material by you
may be the subject of copyright protection under the Act.
Do not remove this notice.
Required Reading
C How to Program, Deitel & Deitel
Chapter 3:
Structured Program Development in C
3.1 - 3.7, 3.11, 3.12
Chapter 4:
C Program Control
4.1 4.8, 4.10 4.12
C Functions
Random Number Generation
/* Fig. 5.7: Deitel & Deitel (Modified)
Deitel & Deitel. C How To Program. Fifth Edition.
Pearson Education, Inc. 2007.
*/
#include <stdlib.h>
int main()
{
Output:
int i;
66556
for (i = 1; i <= 20; i++)
51153
{
66242
printf("%d ", 1 + (rand() % 6) );
if (i % 5 == 0)
62341
printf("\n");
} /* end for */
return 0;
} /* end main */
/* (C) Copyright 1992-2007 by Deitel & Associates, Inc.
and Pearson Education, Inc. All Rights Reserved. */
This seed value gives the random number generator a new starting point.
This will generate a different sequence of numbers, however, will still generate
the same sequence every time the program is run.
For a different sequence of numbers each run, use the time function which
returns the time of the day in seconds.
You only need to do this once at the start of your program.
#include <time.h>
int main() {
int playerDie1;
int playerDie2;
int playerTotal;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;
Control Structures
Control Structures
Programs can be written using three control structures
(Bohn and Jacopini):
Sequence
Statements are executed one after the other in order.
if
if/else
switch
Repetition (doing the same thing over and over)
C has 3 types of repetition structures:
while
do/while
for
statement1;
statement2;
statement3;
is equal to
==
!=
<
<=
>
>=
Example of use:
if (x == 0)
:
is not equal to
is less than
is less than or equal to
is greater than
is greater than or equal to
while (x <= 0)
Logical Operators
Logical Operators (&& || !) combine comparisons
Used when either one, or both, of two (or more) conditions must
be satisfied.
if (it is 1.00 and I am hungry)
have lunch
and
or
not
Logical Operators
! (not) negates the value of the operand. That is, converts true to
false, and false to true.
&& (and) requires both a and b to be true for the whole expression
to be true. Otherwise, the value of the expression is false.
|| (or) requires one of a or b to be true for the whole expression to
be true. The expression is false only when neither a nor b is true.
Truth Table. Logical Operators.
a
0
0
1
1
b
0
1
0
1
a && b
0
0
0
1
a || b
0
1
1
1
!a
1
1
0
0
Logical Operators
Can also store the result of an expression.
For example:
int
int
int
int
x = 5;
y = 1;
z = 5;
res;
res
res
res
res
=
=
=
=
x
x
y
y
< y;
== z;
< x && z < y;
< x || y == z;
Logical Operators
Short Circuit Evaluation
When evaluating:
result = cond1 && cond2;
If cond1 is false result must be false so cond2 is not
evaluated.
Similarly, with:
result = cond1 || cond2;
Conditional Operator
Conditional Operator
Ternary operator. Has the general form:
condition ? value1 : value2
If the condition is true the expression returns value1, else
returns value2.
z = x > y ? x : y;
This is equivalent to the statement:
if (x > y)
z = x;
else
z = y;
Selection Structures
Making decisions
So far, we have seen programs that all start at the top and
execute each statement in order until the end is reached.
Execute different sections of code depending on the values of
data as the program runs.
Greater flexibility and therefore more powerful.
Lets look at ways a program can control the path of execution
Selection Structures
The if Selection Structure
A simple if statement has the following form:
Condition
True
False
Next statement
if (boolean expression)
true block
Statements
Selection Structures
If the expression (boolean expression) is true, the statement(s) in
the true block are executed.
If the expression is false, the program jumps immediately to the
statement following the true block.
If the expression is true execute the statement in the true block.
if (age >= 18)
printf("You can vote");
Selection Structures
Compound Statements
Statement can be a single statement or a compound statement.
Compound statements must be enclosed within { and }.
{
Statement
}
else
printf("No fine.");
IMPORTANT!
Indent the statements that are controlled by the condition.
Selection Structures
The if/else Selection Structure
Allows us to execute one set of statements if the
expression is true and a different set if the expression is
false. An if/else statement has the following form:
False
Condition
True
Statements
Statements
Next statement
if (boolean expression)
true block
else
else block
Selection Structures
The if/else Selection Structure
For Example:
if (mark >= 50)
printf("Passed");
else
printf("Failed");
Selection Structures
Combining comparisons
AND operator evaluates true only if both conditions are true - true
only if temperature is greater than zero and less than 40.
if (temperature > 0 && temperature < 40)
printf("Normal temperature");
else
printf("Extreme temperature");
OR operator evaluates false only if both conditions are false - true if
either of the conditions are true, that is, if it is raining or highUV.
raining = 1;
highUV = 1;
if (raining || highUV)
printf("Take an umbrella!");
Selection Structures
Nested if Statements
Used to achieve multiple tests.
Find the smallest of 3 integers.
int num1, num2, num3, min;
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
printf("Minimum: %d", min);
Selection Structures
Nesting if statements may be difficult to read.
Use linearly nested if statements to test against many
values.
if (mark >= 85)
printf ("HD");
else if (mark >= 75)
printf ("D");
else if (mark >= 65)
printf ("C");
else if (mark >= 55)
printf ("P1");
else if (mark >= 50)
printf ("P2");
else if (mark >= 40)
printf ("F1");
else
printf ("F2");
Selection Structures
Lets revisit our Blackjack program
Selection Structures
Answer
#include <stdlib.h>
#include <stdio.h>
int main() {
int playerDie1;
int playerDie2;
int playerTotal;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;
Selection Structures
The switch Selection Structure
x=?
=1
=2
=3
=4
st1;
st2;
st3;
st4;
break;
break;
break;
break;
Selection Structures
The switch Selection Structure
The syntax for switch is:
switch(expression){
case label 1 : body 1
case label 2 : body 2
:
case label n : body n
default : default body
}
Selection Structures
The switch Selection Structure
char idChar;
int aCount= 0, bCcount = 0, cCount = 0;
switch (idChar)
{
case 'A':
aCount = aCount + 1;
break;
case 'B':
bCount = bCount + 1;
break;
case 'C':
cCount = cCount + 1;
break;
default:
/* Optional */
printf("Error");
}
Omitting break would cause the next action to be executed.
Control Structures
Loops are used when you need to repeat a set
of instructions multiple times.
C supports three different types of loops:
for loop
while loop
do/while loop
for loop
Good choice when you know how many times you
need to repeat the loop.
while loop
Good choice when you need to keep repeating the
instructions until a criteria is met.
*/
while (a >= 0) {
printf("In while loop %d\n", a);
a -= 1; a = a 1;
}
printf("The end!");
Processing Input
Processing Input
An example (read and sum numbers until the user enters a negative
number):
#include <stdio.h>
int main()
{
int no;
int total = 0;
/* initialise loop control */
printf("Please enter a number (-1 to quit): ");
scanf("%d", &no);
/* test loop control */
while (no >= 0) {
printf("Number is: %d\n", no);
total = total + no;
/* update loop control */
printf("Please enter a number (-1 to quit): ");
scanf("%d", &no);
}
printf("\nSum of all numbers entered is: %d\n\n", total);
return 0;
}
Processing Input
An example (read and display menu commands until the user enters
'q' to quit):
#include <stdio.h>
int main()
{
char choice;
Processing Input
Lets revisit our Blackjack program now lets include code to play
out the players hand
Prompt for and read whether the player would like to hit (h) or stand
(s). Implement a loop which continues to simulate one die being
rolled until the user enters stand (s).
Display the value of die 1, die 2 and the total roll value as seen
below:
Player's hand is: 6 + 7 = 13
Play out player's hand...
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 13 + 5 = 18
Please enter h or s (h = Hit, s = Stand): s
Thanks for playing!
Processing Input
Lets revisit our Blackjack program
It does not make sense to continue rolling when the player busts
(exceeds 21).
Modify the loop developed in the previous stage so that it also stops
looping if the player busts (exceeds 21).
Player's hand is: 9 + 5 = 14
Play out player's hand...
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 14 + 1 = 15
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 15 + 10 = 25
Player busts!
Thanks for playing!
Processing Input
Answer
#include <stdlib.h>
#include <stdio.h>
int main() {
int playerDie1;
int playerDie2;
int playerTotal;
char play;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;
Processing Input
:
if (playerTotal == 21) {
printf("Blackjack! Player wins!");
}
else {
printf("Play out player's hand...");
printf("\nPlease enter h or s (h = Hit, s = Stand): ");
scanf(" %c", &play);
while (playerTotal < 21 && play == 'h') {
/* Roll again (one die only) */
playerDie1 = 1 + (rand()%11);
/* Display the player's hand to the screen */
printf("Player's hand is: %d + %d = %d\n", playerTotal, playerDie1, (playerTotal+playerDie1));
playerTotal = playerTotal + playerDie1;
/* Prompt again only if player has not busted (i.e. hand total has not exceeded 21). */
if (playerTotal < 21) {
printf("\nPlease enter h or s (h = Hit, s = Stand): ");
scanf(" %c", &play);
}
}
}
printf("\nThanks for playing!\n");
return 0;
}
Processing Input
A note on reading characters (please keep this in mind when
undertaking practical and assignment work):
The scanf function behaves differently when the %c format specifier is
used from when the %d conversion specifier is used. When the %d
conversion specifier is used, white space characters (blanks, tabs or
newlines, etc) are skipped until an integer is found. However, when the
%c conversion specifier is used, white space is not skipped, the next
character, white space or not, is read.
You may find that this causes your loops to 'skip' the prompt and not
provide you with an opportunity to enter a character at the prompt.
To fix this, leave a space before the %c as seen in the following scanf
statement.
Processing Input
A note on reading characters continued
#include <stdio.h>
int main() {
char playAgain = 'y';
while (playAgain == 'y') {
printf("\n\nDo stuff...
: )\n\n");
return 0;
}
Processing Input
Another common use for a while loop is error checking of user input.
A program that generates a random number between 1-10, asks the user to guess the
number.
int main() {
int randomNo;
int guess;
/* Random number 1 - 10 */
/* User's guess
*/
Processing Input
Another common use for a while loop is error checking of user input.
A program that reads and displays menu commands until the user enters 'q' to quit.
printf("Please enter [a, b, c or q to quit]: ");
scanf("%c", &choice);
/* check to confirm that user enters either 'a', 'b', 'c' or 'q' */
while (choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q') {
printf("\nInput must be a, b, c or q to quit!\nPlease try again...\n\n");
printf("Please enter [a, b, c or q to quit]: ");
scanf(" %c", &choice);
}
while (choice != 'q') {
printf("Choice entered was: %c\n", choice);
int sum = 0;
int number;
for (number = 1; number <= 100; number++) {
sum += number;
}
printf ("Sum: %d\n", sum);
It is possible to nest for loops.
Use while loops if you dont know how many times a loop needs to
execute.
int main() {
char playAgain = 'y';
while (playAgain == 'y') {
printf("In the play again loop!\n");
printf("Play Again? ");
scanf(" %c", &playAgain);
}
return 0;
}
Control Structures
End
Introduction to C (revision)
Control Structures
Deitel & Deitel. C How to Program. Fifth Edition. Pearson Education, Inc. 2007.
Introduction to C++
Developed by Bjarne Stroustrup at Bell Laboratories.
The name C++ includes Cs increment operator(++) to
indicate that C++ is an enhanced version of C.
Provides object-oriented programming capabilities.
C++ standard document Programming languages
C++ - ISO/IEC 14882-2011
#include <iostream>
using namespace std;
int main()
{
int number1;
cout << "Enter first integer\n";
cin >> number1;
// declaration
int number2;
int sum;
Comments
C++ allows 2 types of comment delimiters:
The C delimiters (/* and */).
The C++ double slash (//) which provides a comment
from the double slash to the end of the current line.
int main ()
In C, return-value-type is not necessary.
In C++, return-value-type is necessary for all
functions.
If not specified, the compiler will generate an
error.
Identifiers
C++ identifiers are the same as in C.
Defining Variables
C++ definitions are the same as in C.
However,
In C, variable definitions must be before executable
statements.
In C++, variable definitions placed almost anywhere inside
a block.
Keywords
C++ keywords
Keywords common to the C and C++ programming languages
auto
continue
break
default
case
do
char
double
const
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
C++ keywords
C++-only keywords
and
bool
and_eq
catch
asm
class
bitand
compl
bitor
const_cast
delete
dynamic_cast
explicit
export
false
friend
inline
mutable
namespace
new
not
not_eq
operator
or
or_eq
private
protected
public
reinterpret_cast static_cast
template
this
throw
true
try
typeid
typename
using
virtual
wchar_t
xor
xor_eq
(C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved.
char
int
float
double
- an 8-bit character
- an integer
- single precision floating point
- double precision floating point
Operators
C++ operators are the same as in C.
C does not have a boolean data type.
FALSE
TRUE
is represented by zero
is represented by any non-zero integer.
Operators continued
Scope Resolution Operator (::)
Unique to C++.
Provides access to variables that otherwise would be
masked within the current scope. For example:
int num = 100;
class AccumulateNum
{
int num;
public:
void setNum(int);
void printNum();
};
void AccumulateNum::printNum()
{
cout << local value of num is << num;
cout << external value of num is << ::num;
}
Control Structures
C++ control structures are the same as in C.
C++ allows declarations mixed with statements.
Define a control variable in the for loop. E.g:
for (int i = 0; i < 100; i++)
{ // i exists in this block
}
// i is unknown