0% found this document useful (0 votes)
51 views49 pages

EE1005-L02-An Overview of C

C was designed in the early 1970s for writing systems software for UNIX. It has since evolved into ANSI C and has many descendants like C++ and Java. This document provides an overview of C including its history, basic elements like variables and constants, expressions and statements, and examples of simple C programs. The examples demonstrate printing output, adding two numbers, and calculating the volume of a cylinder by getting user input. Key concepts covered are data types, functions, comments, preprocessor directives, and input/output functions like printf and scanf.

Uploaded by

Shilin Zhang
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)
51 views49 pages

EE1005-L02-An Overview of C

C was designed in the early 1970s for writing systems software for UNIX. It has since evolved into ANSI C and has many descendants like C++ and Java. This document provides an overview of C including its history, basic elements like variables and constants, expressions and statements, and examples of simple C programs. The examples demonstrate printing output, adding two numbers, and calculating the volume of a cylinder by getting user input. Key concepts covered are data types, functions, comments, preprocessor directives, and input/output functions like printf and scanf.

Uploaded by

Shilin Zhang
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/ 49

EE1005 From Computational

Thinking to Programming

Lesson 2
An Overview of C
(Reference: Harry H. Cheng, Chapter 2, 3 and 7)

Dr. Tan Chee Wah, Wesley (CoPaCE/School of EEE)


Email: [email protected]
Office: S1-B1b-54
Phone: 6790 6009
2-1
“Be Prepared, Give Feedback”
Alternative Place for Practice
At Home
– **Get CodeBlocks (Free from
http://www.codeblocks.org/downloads/binaries
– Get Microsoft Visual Studio Express Edition (Free from
Microsoft)
– Get Chide (Free from
www.softintegration.com/docs/ch/chide/)
– Get Microsoft Visual Studio Professional (Free from
https://imagine.microsoft.com/en-
us/custom/Dreamspark)

In School
– Your Tutorial/Practical Laboratory
(if available) 2-2
– ihub (EEE, S2.2-B4-05)
2
History of C

C was designed by Dennis


Ritchie of the Bell Laboratories in
the early 1970s for writing
systems software for the UNIX
OS.

C was evolved from B!


B was created from BCPL (Basic
Combined Programming Language)
which was designed by Martin
Richards (Cambridge) in 1967. 2-3
ANSI C
In 1989, the American National Standards
Institute (ANSI) approved a standard for C
known as ANSI C, or Standard C (known as
C89). It was also accepted as an ISO standard
and is known as ANSI/ISO C.

New standard: C11

ANSI C is a mature, important, general purpose


language that is widely available.

We will use ANSI C in this course.

2-4
C’s Descendents & Relatives:
• C++ : a superset of C
C with Object-Oriented extensions

• Java (created by Sun Microsystems)


- Very popular language
Uses a lot of C/C++ syntax
Internet & platform-independent programming

• C# : for Microsoft’s .NET platform


2-5
Variables, Identifiers & Keywords
Variable – a named data storage location in
RAM.

Identifier – name of a variable.

Keywords – predefined words with special


meanings, e.g. int, void, float
Keyword definitions cannot be changed.

Full list of Keywords for C89 (a total of 32


words) is given in the next slide.
2-6
C89 Keywords

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

Note: Not all keywords will be covered in this


course. 2-7
Rules for naming identifiers:
• It can contain letters, digits, and the
underscore character (_).
• It must start with a letter or the underscore.

• It is case sensitive.

• C keywords cannot be used.

Valid names: sum, number_1, exam_mark


Invalid names: 1st, metric#, exam mark,
float space NOT allowed

Always choose meaningful names.


2-8
Constants
C has several types of constants:
• Integer constants: -25, 1000
• Floating-point constants:
3.14159265, -1.5E-2, 1.5e-2
• Character constants which are enclosed
within a pair of single quotation marks:
'A', '1', '$'
• String constants which are enclosed within
a pair of double quotation marks:
"This is a string constant."

2-9
Expressions & Statements
An expression consists of variables, constants,
and operators (such as +, -, *, /, etc) written
according to the syntax of the C language.
Some examples of C expressions:
a+b, x+y*z/w, cos(x)

In C, every expression has a value of a certain


type that can be assigned to a variable:
e.g. for a+b, a=1.2, b=2.3, and a+b=3.5 can be
assigned to variable c

C statements can be formed from expressions:


2-10
e.g. y = a+b*cos(x);
Program 2.1
/* This C program will print a message
on the computer screen. */
#include <stdio.h>
int main(void)
{ printf("This is my first program.\n");
printf("Programming is easy.");
return 0;
}

Screen Output:

2-11
Dissection of Program 2.1:

/* This is a comment */
• You can insert comments between /* and */.
• Computer will ignore all the comment
statements.
• It is important to insert comments at suitable
places in the program to explain what the
statements are doing. This is part of program
documentation.

2-12
Dissection(continued):
#include <stdio.h>
stdio.h = standard input-output header file
• A part of all C development environments.
• Provides functions to perform I/O operations
(such as printf here).
• # sign : preprocessor directive. Tells the
preprocessor to do something before compiling.
• #include <stdio.h> tells preprocessor to
include the contents of the file stdio.h into our
program before compilation. 2-13
preprocessor is a program that processes its input data to produce output that is used as input to another
program.
Dissection (continued):
int main(void)
• Starting point for program execution.
• One and only one main() function.
• The parentheses after main enclose a definition
of the input data to be provided to main() when it
starts executing. The word void means that no
input data needs to be provided to main().
What is a C function?
• A collection of statements for doing a specific task.
• Can call the function name to execute the
statements 2-14
Dissection (continued):
int main(void)
• A mathematical function has at least one
argument (input data) whereas a C function
may have 0 or more arguments.
• void means the function has no argument.
• A function may also return an output value to
its caller.
• Here main() returns an integer value to the
operating system.
• int and void are C keywords.
2-15
Dissection (continued):

printf("This is my first program.\n");

• printf() is a function with arguments.


• For the above, "This is my first program.\n"
is the argument.
•It sends the string constant, enclosed by " and ":
This is my first program.
to the screen.
• It is provided by <stdio.h>. 2-16
Dissection (continued):

\n : newline character. Moves screen cursor to


beginning of next line.
Suppose it is not used in printf():
printf("This is my first program. ");
printf("Programming is easy.");

Output (Both sentences will be in a single line):


This is my first program. Programming is easy.
2-17
Dissection (continued):

; The semi-colon indicates the end of a C


statement.
return 0;
This means main() returns the value 0 to the
caller (the Operating System in this case). The
return value is not used in this course. Treat the
statement as a requirement under ANSI/ISO C.
{ } marks the beginning and end of a block of
statements (in this case, the function body).

2-18
Program 2.2

/* This program adds two integers. */


#include <stdio.h>

int main(void)
{ int number1, number2, sum;
number1 = 20;
number2 = 30;
sum = number1 + number2;
printf("The sum of %d and %d is %d.",
number1, number2, sum);
return 0;
} 2-19
Declaration of Variables
The line:
int number1, number2, sum;
is called a declaration statement.

The purpose is to ask the computer to reserve


3 memory locations to store values. These
locations are called number1, number2,
sum and they will be used to store integer
numbers (numbers without a fractional part,
or without a decimal point). The statement
declares 3 integer variables.

Syntax: data_type variable_name 2-20


number1 = 20; number2 = 30; Sum = number1
+ number2;

20 30 50

number1 number2 sum


printf("The sum of %d and %d is %d.",
number1, number2, sum);
Output:
The sum of 20 and 30 is 50. 2-21
Conversion/Format Specifiers

printf("The sum of %d and %d is %d.",


number1, number2, sum);

When displaying output, we need to tell the


computer what and how to output. Since our
output are integers, we use the conversion or
format specifier %d (to indicate integer format)
which is also described as a placeholder.
Each integer value (from number1, number2,
sum) requires one %d and each value will be
displayed at the corresponding location of the
placeholder in the order specified. 2-22
Program 2.3
/* Calculate volume of a cylinder */
#include <stdio.h>

int main(void)
{
float radius, height, volume;

printf("This program computes the


volume of a cylinder.\n\n");
printf("Input the radius => ");
scanf("%f", &radius);
2-23
Program 2.3 (Continued):

printf("Input the height => ");


scanf("%f", &height);

/* Compute the volume. */


volume = 3.14159*radius*radius*height;
printf("The volume is %f.", volume);

return 0;
}

2-24
3 new items:
(1) float radius, height, volume;
The keyword float is for declaring variables
which take floating-point values (numbers with a
decimal point). Conversion specifier is %f.

(2) scanf("%f", &radius);


scanf() is for capturing user input.
Syntax: scanf ("format_specifier", address_of_variable)
Note the input will be represented as a float (%f) value
and ampersand (&)character in front of radius means
value will be stored at a location named by radius 2-25
(3) The asterisk (*) denotes
multiplication.

Screen Output:
This program computes the volume of a
cylinder.

Input the radius => 1.5 Entered by


Input the height => 5 user
The volume is 35.342888.

Default: 6 decimal places. 2-26


Program 2.4
/* Solution of a*x*x + b*x + c = 0 */
#include <stdio.h>
#include <math.h>

int main(void)
{
double a, b, c, root1, root2;
printf("Input the coefficient a => ");
scanf("%lf", &a);
printf("Input the coefficient b => ");
scanf("%lf", &b);
printf("Input the coefficient c => ");
scanf("%lf", &c); 2-27
Program 2.4 (Continued)

/* Compute the roots. */

root1 = (- b + sqrt(b*b-4*a*c))/(2*a);
root2 = (- b - sqrt(b*b-4*a*c))/(2*a);

printf("The first root is %8.3f\n", root1);


printf("The second root is %8.3f\n", root2);

return 0;
}

2-28
New items

#include <math.h>
This provides the sqrt() function.

double a, b, c, root1, root2;


The double data type is similar to float but it
represents real numbers with higher precision
and a much wider range.
The conversion specifier in scanf() is now
%lf.

2-29
Suppose we input: There are 2 space characters
+
The remaining 6 characters
a = 2, b = 6, c = 1 are ‘-’, ‘0’, ‘.’, ‘1’, ‘7’ and ’7’
Screen Output: ll
Thus, there are
The first root is –0.177 8 characters in
The second root is –2.823 total

%8.3f gives 3 decimal places and the output is


allocated (a minimum of) 8 character slots.
Note that this is for formatting of output; do
not write statements such as
scanf("%8.3f", &a);
2-30
scanf("%f\n", &a);
Program Statement Layout
It is important that you type your program so
that the structure is clear. Use indentations
(i.e., leave a space before the first word of
each line of statement within a function body).

int main(void)
{
float radius, height, volume;
printf("This program . . .");
printf("Input the radius => ");
scanf("%f", &radius); 2-31
Single and Multi-Line Comments
/* This is a
multi-line
comment
*/

// This is a single line comment


(new in C99, supported by CodeBlocks too)

2-32
Note about Program 2.4

Program 2.4 fails if the user enters 0 for the


coefficient a.
We should test the value of a given by the
user to see whether it is zero or not, before
proceeding with the actual computation.
This is done using the if-else decision
making structure as in Program 2.5. (Refer to
Lesson 6 for a more detailed discussion on if-
else.)

2-33
Program 2.5 (quadratic equation)
if (a == 0) /* If coefficient a is
zero, do the below. Note the double
equal or == sign */
{
printf("You have entered a = 0.\n");
printf("Only one root: %8.3f", -c/b);
}
else //otherwise do the below
{ root1 = (-b + sqrt (…))/(2*a);
. . . 2-34
}
Notes on Program 2.5
Note that the double equal or == sign is used
for checking equality of two values. This will
be discussed again in Lesson 6.

if statement has one pair of braces or { } to


enclose its associated block of statements.
Similarly, else statement also has another
pair of braces or { } to enclose its associated
block of statements.

2-35
Pseudocode Example 3 (Lesson 1)
INPUT max_time, interval
SET accel = 9.8, time = 0
PRINT Table Title
WHILE time <= max_time
distance = 0.5*accel*time*time
OUTPUT time, distance
SET time = time + interval
END WHILE

We’ll implement a version of this algorithm


without user-input in the next example.
2-36
Program 2.6
/* Distance travelled by a particle falling under
gravity. Initial velocity = 0 */

#include <stdio.h>

int main(void)
{
double time = 0, max_time = 4, interval = 0.5,
acceleration = 9.8, distance;

printf("Time Elapsed Distance Travelled\n" );


printf("--------------------------------\n" );

2-37
Program 2.6

while (time <= max_time)


{
distance = 0.5*acceleration*time*time;
printf("%8.2f %8.2f\n", time, distance);
time = time + interval;
}
return 0;
}

2-38
Screen Output

Time Elapsed Distance Travelled


----------------------------------
0.00 0.00
0.50 1.23
1.00 4.90
1.50 11.03
2.00 19.60
2.50 30.63
3.00 44.10
3.50 60.03
4.00 78.40

2-39
New Concept: the while loop

while (time <= max_time)


{ . . .
}

The loop body (The part enclosed within the


braces or {}) will be executed as long as the
condition (time <= max_time) is TRUE.
Loops will be discussed in detail in Lesson 7.

2-40
Exercises
(1) Modify the program so that max_time
and interval are both user-input values
(as specified in the algorithm).
(2) Modify the program assuming that the
particle has an initial velocity u that will
be entered by the user. The formula is
1 2
=
s ut + at
2

You will have a chance to do the above in


Practical Lesson 3.
2-41
Preprocessor Directives & Macros
# indicates a preprocessor directive.
Example: #include <stdio.h>

There is another preprocessor directive:


#define that is frequently used to define
constants. It is also said to define a macro.

Example:
#define PI 3.14159
#define GST 0.07

2-42
Preprocessor Directives & Macros
The PI and GST defined previously are also
known as symbolic constants and the names
are usually typed in capital letters.

General Form:
#define macro_name replacement_text

This is purely a text replacement command. The


preprocessor will replace the macro_name in
our program with the replacement_text. If we
use the symbolic constant PI, Program 2.3 is
modified as shown in the next slide: 2-43
Program 2.3 (Using a macro)
#include <stdio.h>
#define PI 3.14159
int main(void)
{ . . .
/* Compute the volume. */
volume = PI*radius*radius*height;
Note: During preprocessing, the computer will replace
all occurrences of PI (except those in comments and
quoted strings) with 3.14159. Hence the statement for
the calculation of volume will be changed by the
preprocessor to:
volume = 3.14159*radius*radius*height;
2-44
Preprocessor Directives & Macros
Advantages:
(1) Macros may make programs easier to
understand because a meaningful name used
(like PI, GST) is easier to understand than a
number.

(2) If there is a need to change the value, we


only need to change the #define
statement. This is very useful if the same
constant is used many, many times in a
program.
2-45
Parameterized Macros
Macros can have input parameters, like Functions
which you will learn later. General Form:
#define macro_name(parameters) replacement_text

Example:
#define CIRCLE_AREA(r) (3.14159*(r)*(r))
This means CIRCLE_AREA(r) will be replaced by
(3.14159*(r)*(r)), where the value of r is provided
by you.
r = 2.5 here
In other words, when you write the below statement:
volume = CIRCLE_AREA(2.5)*height;
This statement will become
volume = (3.14159*(2.5)*(2.5))*height; 2-46
after preprocessing.
Parameterized Macros
Why are there so many parentheses (brackets)?
#define CIRCLE_AREA(r) (3.14159*(r)*(r))

This is to guard against mistakes when the parameter r


is to be replaced by another expression such as (2+a).

E.g. We now want to calculate the area of a circle with


radius as (2+a). We assign a = 1.

Using the above macro, CIRCLE_AREA(2+a)


will give (3.14159*(2+a)*(2+a))
Since a = 1, the result will be (3.14159*(2+1)*(2+1))
= (3.14159*(3)*(3)) Area of circle with radius 2-47
(2+a) where a=1
Parameterized Macros
Let’s now see what happens when there are no
parentheses () enclosing r. This means:
#define CIRCLE_AREA(r) (3.14159*r*r)

To calculate the area of a circle with radius as (2+a),


where a = 1, using the above macro,
CIRCLE_AREA(2+a) will give (3.14159*2+a*2+a)

Since a = 1, the result will be (3.14159*2+1*2+1)


= (6.28318+2+1)
* is at a higher
precedence level and will
NOT the area of circle with be executed ahead of +
radius (2+a) where a=1 2-48
Summary
1. Terminology
• Variables, identifiers, keywords
• Constants
• Expression and statement
2. Six Examples of C program that illustrate:
• Printing to computer screen
• Using variables and performing calculations
• Getting input from user
• Using C mathematical functions
• Using if-else structure
• Using while-loop structure
3. Preprocessor Directives and Macros

2-49

You might also like