ECE102
Engineering Problem Solving
What’s in a Program?
Chapter 2
Simple C Programs
• Basic C Program Structure
• The basic steps of programming problems
1. Get input data
#include < >
2. Check the validity of data
#define
3. Perform computations
int main ( )
4. Display results
{
/***********************************************
* Header Comments
************************************************/
include files
global declarations
• The basic structure of a
main program
int main( )
{
declarations;
• The basic C syntax!
executable statements;
return 0;
}/%end block of main%/
ECE102
}
declare variables
get input data
calculation
display results
return 0;
• Apply the five-step problem solving method
2-1
A Simple Program
ECE102
2-2
Straight-line Distance Between Two Points
/* This program computes the distance between two points */
#include
#include
#include
int main(void)
{ /*declare and initialize variables */
double x1 = 1, y1 = 5, x2 = 4, y2 = 7;
double side_1, side_2, distance;
/* compute sides of a right triangle */
side_1 = x2 ‐ x1;
side_2 = y2 ‐ y1;
/*calculate the distance */
distance = sqrt(side_1*side_1 + side_2*side_2);
/*print the distance */
printf("The distance between the two points is %5.2f
\n", distance);
system("pause");
return 0;
}
ECE102
2-3
ECE102
2-4
Pay Attention to Syntax!!!
Comments
• When learning a new language or a new concept in a language,
remember to pay attention to the syntax
– Syntax is the “grammar” of programming languages.
• Used to document
programs
• Comments help people
read programs, but are
ignored by the compiler.
• Review the example program and try to guess what things
are the syntax
– What is the syntax: special characters, order of things,
– Remember to follow the syntax when writing your own programs
• Use ; (semicolon) at the end of every command,
• Well-conceived and wellplaced comments enhance
the readability of the
source code.
• Syntax:
– Identify where semicolon should not be used
/* ------- */ (one line)
/* -----------(multiple lines)
-------------*/
/*----------------------------*/
/* This program computes the distance between two
points */
#include
#include
#include
int main(void)
{
/*declare and initialize variables */
double x1 = 1, y1 = 5, x2 = 4, y2 = 7;
double side_1, side_2, distance;
/* compute sides of a right triangle */
side_1 = x2 ‐ x1;
side_2 = y2 ‐ y1;
/*calculate the distance */
distance = sqrt(side_1*side_1 +
side_2*side_2);
/*print the distance */
printf("The distance between the two
points is %5.2f \n", distance);
system("pause");
return 0;
}
ECE102
2-5
ECE102
What to Comment on
#include Preprocessor Directives
• Initial comments (header comments)
–
–
–
–
–
• The preprocessor reads and modifies the source code
before it is passed to the compiler.
Describe the general purpose of the program
List of inputs and outputs
Author
Date
Copyright
• C itself did not have easy input, output, math, and other
routines built in. These functions are provided in standard
libraries.
• #include includes library files to give access to a library.
#include
#include
• Comments within the program
– Describe the meaning of the variables, if applicable
– Functionality of blocks of lines
• Math.h contains elementary math functions such as sin(x),
cos(x), sqrt(x), pow(x,y), abs(x), …
• Good programming style requires that comments be used
throughout a program to improve the readability and to
document the computations.
ECE102
2-6
2-7
ECE102
2-8
The main Function
Keywords (Reserved words)
• Keywords are reserved words with special meaning to the C
compiler
• Syntax (grammar rules of a programming language)
preprocessing directives
int main (void )
{
/*function body*/
declarations
statements
• Keywords cannot be used for any other purpose
• They always mean what they are defined to mean in C
• Improper use of keywords result in an error that prevents
the program from compiling
return 0;
• Keywords are listed in Table 2.1 (typo: ints should be int)
}
• Braces { } mark the beginning and the end of the program.
• Find the keywords in the sample program
• Every C program has ONE and only one main function
ECE102
int, double, return
2-9
ECE102
2-10
Computer Memory
Data Type
• Four basic types
01010001
• Terminology:
01001101
– Memory is divided into numbered locations called bytes.
– A byte is a sequence of 8 bits.
– A bit is a binary digit (0 or 1).
– The location number associated with a byte is called the
address.
– A group of consecutive bytes is used for storing the binary
representation of a data item, such as a number or a character.
ECE102
2-11
type
size
description
char
1 byte
character
int
2 or 4
bytes
whole number
float
4 bytes
floating point number (6 digit
precision)
double 8 bytes
• Examples:
double precision floating point
number (15 digit precision)
data type int
-1
data type double -1.0
ECE102
435
4.35
+5
32767
+5.9e4 0.3e-5
2-12
Numeric Data Type
Example Data-Type Limits
• Compiler dependent
• In Visual Studio 2013
Type Name Bytes
Other Names
Range of Values
int
4
signed
–2,147,483,648 to 2,147,483,647
char
1
none
–128 to 127 by default
0 to 255 when compiled by using /J
short
2
unsigned
short
2
short int, signed short –32,768 to 32,767
int
unsigned short int
0 to 65,535
long
4
long int, signed long int –2,147,483,648 to 2,147,483,647
unsigned
long
float
4
unsigned long int
0 to 4,294,967,295
4
none
3.4E +/- 38 (7 digits)
double
8
none
1.7E +/- 308 (15 digits)
long double same as none
double
ECE102
2-13
Same as double
ECE102
Example Data-Type Limits
2-14
Scientific Notation
• Compact notation used for very large or very small numbers
• Numbers are stored as mantissa and exponential form
234.56 = 2.3456 X 102
2.3456e2
exponent
-0.00045= - 4.5 X 10-4
= - 4.5e-4
• Exercise:
1.03e-5 =
-50000 =
-3.552e6 =
10,000,028 =
• Precision: the number of digits in the decimal portion of the
mantissa
ECE102
2-15
ECE102
2-16
Data Type char
• Examples:
‘A’
‘z’
‘*’
Variables
• We use variables to represent values in C programs.
‘9’
• Stores ASCII values
• Variables are memory locations that are assigned a name or
identifier.
• Interprets the number stored in that variable as a
character rather than a number
– Character ‘3’ is different from the integer 3.
• The identifier or variable name is used to reference the
value of the variable or, what is stored in the memory
location.
• Character types only store ONE character
• Appendix B lists the ASCII characters
• Everything needs a name or identifier!
• ASCII – American Standard Code for Information
Interchange
– Variables
– Functions
– Files
• Non-conventional characters:
– Newline, \n
– Tab, \t
ECE102
2-17
ECE102
2-18
User-Defined Identifiers
User-Defined Identifiers
• User-defined identifiers are identifiers that the
programmer makes up
• User-Defined Identifier Suggestions for Readability
– User-defined identifiers should be meaningful
Example:
use miles rather than x
use area rather than a
• User-defined identifiers are used for constants, variable
names, and most function names
– Use the underscore _ to put space between words
• Rules for User-Defined Identifiers
– Use uppercase letters to denote constants, lower case to
denote variables
–
–
–
–
–
Consist of letters, numbers, and underscores
Must begin with a letter or underscore
Cannot begin with a digit
Cannot be a keyword
Only first 31 characters used to distinguish it from other
identifiers
– An identifier defined in a C standard library should not be
redefined
– Case sensitive
ECE102
• Examples:
–
–
–
–
–
2-19
ECE102
1Letter
Letter_1
Variable
Double
house footage
2-20
Variable Declaration
Variable Declaration
• All variables must be declared before they can be used
• Each data type has a specific size in memory and a specific
way of representing the number or letter
• Variables must also have a unique name
• Declarations define memory locations, including type of data
to be stored, identifer (i.e., name), and possibly an initial
value.
• General Form to declare variables:
data_type identifier_list;
• Examples:
char ch=‘q’;
int age = 20;
double x1=1, y1=5, x2=4, y2=7;
(initialized as well)
double side_1, side_2, distance;
(not initialized,
do not have values yet)
ECE102
2-21
ECE102
2-22
Constant
Assignment Statements
• Constants are specific values that do not change
• Examples of constants
6,371
(radius of earth)
3.1416
• Syntax
variable = expression;
(π)
• Used to assign a value to a variable
• Assignment is directional
• Symbolic constants are used to name values which do not
change during the execution of the program.
variable expression
• The computer evaluates the expression on the right and
places its value in the memory location represented by the
variable on the left
• Are always initialized at declaration.
• syntax: (no semicolon here)
#define identifier
value
• Example 1:
• Examples:
#define PI 3.1415926
#define C 2.99792e8
ECE102
side_1 = x2 - x1;
– The value 3.0 (=4-1) is placed in the memory location used by
the variable side_1. In other words, side_1 equals 3.0 now.
• Remember, what is on the right of the ‘=‘ is placed in the
variable on the left
2-23
ECE102
2-24
Assignment Operator:
=
Output to the Screen
• Example 2:
• We use the printf function to write to the screen
sum = 10; item = 5;
sum = sum + item;
/* item =?
– Syntax
printf( “format string”, print list);
sum =?
*/
– Example
printf(“The distance between the two points is %5.2f
\n”, distance);
• The following equation doesn’t make sense to C. Why?
y2-y1 = side_2;
• Example 3: multiple assignments
int x, y, z;
x=y=0;
z=2;
• The \n (backslash n) is a line feed. Instructs the computer
to print any text that follows on the next line.
y=z;
x
y
z
x
0
0
y
z
0
• The %f is a placeholder for the value of distance, which we
would like to see on the screen.
?
?
2
ECE102
2-25
ECE102
Conversion Specifiers for Output Statements
2-26
Display Format
• We can specify the field width.
• Example:
printf(“Results: %3d meters = %4d feet.\n”, meters,
feet);
Output:
Results: _21 meters = __68 feet.
• If the number contains more digits than the field width, the
field width is ignored.
• For a double or float number, the field width includes the
decimal point. The precision is the number of digits after
the decimal point
• The form is %field_width.precisionf
• Example:
printf(“kilometers = %6.3f\n”, kms);
Output (Assume kms = 4.3):
kilometers = _4.300
ECE102
2-27
ECE102
2-28
Exercise: printf
Example: Conversion
• What will the following commands print?
#include
/*printf, scanf definitions */
#include
#define KMS_PER_MILE 1.609 /*conversion constant*/
int main(void)
{
double miles,
/*distance in miles
*/
kms; /*equivalent distance in km*/
age = 25; gpa = 4.0;
printf(“Here is the first line\n”);
printf(“I am %d years old, and my GPA is
%f\n”, age, gpa);
/*Get the distance in miles*/
printf("Enter the distance in miles> ");
scanf("%lf",&miles);
/*Convert the distance to kilometers*/
kms = KMS_PER_MILE * miles;
• %f, by default, means to print a number as a floating point
number with 6 digits after the decimal point
/*Display the distance in kilometers*/
printf("That equals %f kilometers.\n", kms);
system("pause");
return 0;
• How do you print out the two points on the screen?
– x1=1, y1=5, x2=4, y2=7;
ECE102
}
2-29
ECE102
Use scanf_s instead of scanf
2-30
Input from the Keyboard
• Can obtain input from the keyboard using the scanf function
• Microsoft Visual Studio gives the following error when
compiling scanf
– error C4996: 'scanf': This function or variable may be unsafe. Consider
using scanf_s instead.
– Syntax:
scanf(format string, input list);
– Example: scanf(“%lf”, &miles);
• Therefore, use scanf_s in your programs instead of scanf.
• When scanf executes, the program pauses until the required
data are entered and the key is pressed.
• The syntax for these two commands is the same.
• Note: the format string is what the function expects to see
from the keyboard. We must use:
Format
Type of variable
%c
char
%d, %i
int
%f, %e
float
%lf, %le
double
ECE102
2-31
ECE102
2-32
Input from the Keyboard
Displaying Prompting Message
• Use the ampersand (&) in front of the variable names.
• scanf does not tell the user what is expected.
• The & is the “address of” operator. It returns the address
in memory of that variable
• scanf can get inputs for multiple variables
scanf(“%c%d”, &first_initial, &age);
• When scanf executes, the program pauses until the required
data are entered and the key is pressed.
– scanf expects to be given addresses for variables
– It will treat whatever value it is given as an address
– This could result in computer crashes and other problems as
data is written to a random location
2-33
More Formatting
• Right justified (%+):
• Left justified (%-): %-d
ECE102
2-34
Problem Solving Applied: Velocity Computation
%+.2f
• Problem statement: during a test flight of an unducted fan
(UDF)-powered aircraft, the test pilot has set the engine
power level at 40,000 N (newtons), which causes the
20,000-kg aircraft to attain a cruise speed of 180 m/s. The
engine throttles are then set to a power level of 60,000 N
and the aircraft begins to accelerate. As the speed of the
plane increases, the aerodynamic drag increases in
proportion to the square of the airspeed. Eventually, the
aircraft reaches a new cruise speed where the thrust from
the UDF engine is just offset by the drag. The equations
used to estimate the velocity and acceleration of the
aircraft from the time that the throttle is reset until the
plane reaches its new cruise speed are the following:
• Escape character \
–
–
–
–
printf("Enter the distance in miles> ");
scanf("%lf",&miles);
• It is important to have a prompt to go with the scanf
command.
• If you forget the &, what will happen?
ECE102
• Displaying prompt: when input data are needed in an
interactive program, use the printf function to display a
prompting message that tells the user what data to enter.
To print backlash: \\
printf(“3\\5”);
Question mark: \? printf(“What is your name\?”);
Single quote: \’
Double quote: \”
printf(“He said, \”Howdy!\”);
• Sound bell \a
printf(“The bell rings like this. \a”);
Velocity 0.0001 time 3 0.0048 time 2 0.75795 time 181.3566;
Acceleration 3 0.000062 velocity 2
ECE102
2-35
ECE102
2-36
Problem Solving Applied: Velocity Computation
Problem Solving Applied: Velocity Computation
• Write a program that asks the user to enter a time value
that represents the time elapsed (in seconds) since the
power level was increased. Compute and print the
corresponding acceleration and velocity of the aircraft at
the new time value.
Step 2: Analysis:
– Input:
– Output: Time in seconds
– Relevant formulas
Acceleration and velocity
Step 1: Problem definition
Velocity 0.0001 time 3 0.0048 time 2 0.75795 time 181.3566;
on 3 0.000062 velocity 2
– Accelerati
Problem constants:
– Constraints:
Visualize the solution: what a user sees who the program is run.
None
Time >= 0
ECE102
2-37
ECE102
Problem Solving Applied: Velocity Computation
2-38
Algorithms
Step 3: Hand examples
• An algorithm is the sequence of steps needed to solve a
problem
Time = 50 seconds
Velocity = 208.3 m/s
Acceleration = 0.31 m/s2
• Top-down design approach to programming: break a solution
into steps, then further refine each one
Time =
• Generic algorithm for many programs:
Velocity =
Acceleration =
–
–
–
–
Get inputs
Check validity of inputs
Calculate result(s)
Display the result(s)
• A modular program would consist of functions that
implement each step
ECE102
2-39
ECE102
2-40
Problem Solving Applied: Velocity Computation
Problem Solving Applied: Velocity Computation
Step 4a: Pseudo-code (algorithm): step-by-step outline (use variables
names in the pseudo-code)
1. Get input data time
2. Computations
– Calculate velocity,
» Velocity = …
– Calculate acceleration,
» Acceleration = …
3. Display velocity and acceleration (specify the details here)
- display Velocity = ……
- display Acceleration = ……
•
Step 4b: Implementation
#include
#include
int main(void)
{
double time, velocity, acceleration; /*declare input and outputs*/
/* Get time value from the keyboard. */
printf("Enter new time value in seconds: \n");
scanf("%lf",&time);
/* Compute velocity and acceleration. */
velocity = 0.00001*pow(time,3) - 0.00488*pow(time,2)
+ 0.75795*time + 181.3566;
acceleration = 3 - 0.000062*velocity*velocity;
/* Print velocity and acceleration. */
printf("Velocity = %8.3f m/s \n",velocity);
printf("Acceleration = %8.3f m/s^2 \n",acceleration);
Requirement in this class:
–
–
Pseudo-code needs to contain specific information so that
someone else can write a program based on it alone.
Use variable names picked up in Step 2 (Analysis).
ECE102
}
2-41
system (“pause”);
return 0;
ECE102
Problem Solving Applied: Velocity Computation
Arithmetic Operators
Step 5: Testing
•
•
•
•
Enter new time value in seconds:
50
Velocity = 208.304 m/s
Acceleration =
0.310m/s^2
Press any key to continue
Addition
Subtraction
Multiplication
Division
• Modulus
+
*
/
%
– Modulus returns the remainder of division between two
integers
– Example
5%2 returns a value of 1
9%3 returns a value of 0
8%5 =
17%3 =
Enter new time value in seconds:
100
Velocity = 218.352 m/s
Acceleration = 0.044 m/s^2
Press any key to continue . . .
ECE102
2-42
2-43
ECE102
2-44
Integer Division
Priority of Operators
• Division between two integers results in an integer.
• The result is truncated, not rounded
• Example:
•
•
•
•
5/3 is equal to 1
3/6 is equal to 0
• How to get 5/3=1.666…?
5.0/3
or 5/3.0
Convert one number to a floating point using .0!
7+3*5–2=
(7 + 3) * 5 – 2 =
4+7/3
8%3*6
• Priority of operators
1. Parentheses
2. Unary operators (+ -)
Inner most first
Right to left
3. Binary operators (* / %)
Left to right
4. Binary operators
(+ -)
Left to right
• Cast operator: (double) 5 / 3
Convert 5 to double before proceeding with the calculation.
ECE102
2-45
ECE102
2-46
Math Expressions in C
Overflow and Underflow
• Add parentheses to ensure the order in which the operators
are performed.
• Every data type has a limit on the range of allowed values:
int
maximum = 2,147,483,647
• Overflow
– answer too large to store
– Example: using 16 bits for integers
– result = 32000 +532;
1
1
1
1
R1 R2 R3
• Use parentheses and spaces to enhance the readability of
the program.
R
• Exponent overflow
– answer’s exponent too large
– Example: using float, with exponent range –38 to 38
– result = 3.25e28 * 1.0e15;
• Exponent underflow
P2 P1
ECE102
– answer’s exponent to small
– Example: using float, with exponent range –38 to 38
– Result = 3.25e-28 *1.0e-15;
v22 ( A22 A12 )
A12
2-47
ECE102
2-48
Data Range : System Limitations
/* This program prints the system limitations.
#include
#include
#include
int main(void)
{ /* Print integer type maximums. */
printf("short maximum: %i \n",SHRT_MAX);
printf("int maximum: %i \n",INT_MAX);
printf("long maximum: %li \n\n",LONG_MAX);
Increment and Decrement Operators
*/
• Increment Operator ++
• post incrementx++;
• pre increment ++x;
• Decrement Operator - • post decrement
• pre decrement --x;
/* Print float precision, range, maximum. */
printf("float precision digits: %i \n",FLT_DIG);
printf("float maximum exponent: %i \n",
FLT_MAX_10_EXP);
printf("float maximum: %e \n\n",FLT_MAX);
}
x--;
• For example,
•
•
•
•
k
k
x
x
= 5; m= ++k;
both m and k become 6
=5; n = k--;
n becomes 5 and k becomes 4
= 3, y = 4; W = ++x – y; w=?
= 3, y = 4; W = x++ – y; w=?
getchar();
return 0;
ECE102
2-49
ECE102
Abbreviated Assignment Operator
• operator
+=
-=
*=
/=
%=
• Example:
b += c + d;
x = 2; y = 4;
x = 2; y = 4;
ECE102
example
x
x
x
x
x
Precedence of Arithmetic and Assignment
Operators
equivalent statement
+= 2;
-= 2;
*= y;
/= y;
%= y;
2-50
x = x+2;
x = x-2;
x = x*y;
x = x/y;
x = x%y;
b = ?
y %= x;
x += y;
y = ?
y = ?
2-51
ECE102
2-52
Functions in
fabs(x)
computes absolute value of x
sqrt(x)
computes square root of x, where x >=0
pow(x,y)
computes xy
ceil(x)
nearest integer larger than x
floor(x)
nearest integer smaller than x
exp(x)
computes ex
log(x)
computes ln x, where x >0
log10(x)
computes log10x, where x>0
sin(x)
sine of x, where x is in radians
cos(x)
cosine of x, where x is in radians
tan(x)
tangent of x, where x is in radians
ECE102
2-53