0% found this document useful (0 votes)
4 views68 pages

Lecture03 OverviewOfC

The document provides an overview of the C programming language, including its structure, data types, variable declarations, and basic programming concepts. It outlines objectives for learning C, such as understanding data types, variable declarations, and input/output operations, and presents a case study for converting distances between miles and kilometers. Additionally, it discusses the syntax and rules for identifiers, assignment statements, and the use of standard library functions.

Uploaded by

EG JP
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)
4 views68 pages

Lecture03 OverviewOfC

The document provides an overview of the C programming language, including its structure, data types, variable declarations, and basic programming concepts. It outlines objectives for learning C, such as understanding data types, variable declarations, and input/output operations, and presents a case study for converting distances between miles and kilometers. Additionally, it discusses the syntax and rules for identifiers, assignment statements, and the use of standard library functions.

Uploaded by

EG JP
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/ 68

Overview of C

Objectives
‣ to become familiar with the general form of a C program and the basic
elements in a program

‣ to understand the use of data types and differences between them

‣ to know how to declare variables

‣ to understand how to write assignment statements to change the values


of variables

‣ to learn how C evaluates arithmetic expressions and how to write them in


C

‣ to learn how to read data values into a program and display results

‣ to understand how to write format strings for data entry and display

2
RECALL
Software Development Method
1. Problem Definition

2. Problem Analysis

3. Algorithm Design and Representation

4. Coding and Debugging

3
APPLYING THE SOFTWARE DEVELOPMENT METHOD

Case Study
Problem

Your summer surveying job requires you to study


some maps that give distances in kilometers and
some that use miles. You and your coworkers prefer
to deal in metric measurements. Write a program that
performs the necessary conversion.

4
APPLYING THE SOFTWARE DEVELOPMENT METHOD

Case Study
Analysis
‣ Convert from kilometers to miles? or miles to kilometers?

‣ What are the data of requirements? input to the


program? output of the program?

‣ What is the relationship of between miles and


kilometers?

5
APPLYING THE SOFTWARE DEVELOPMENT METHOD

Case Study
Analysis
‣ Convert from Miles to Kilometers

‣ Data of requirements

Input to the Program : the distance in miles


Output of the Program : the distance in kilometers

‣ 1 mile = 1.609 kilometers

6
APPLYING THE SOFTWARE DEVELOPMENT METHOD

Case Study
Algorithm
1. Get the distance in miles
2. Convert the distance to kilometers
3. Display the distance in kilometers

Algorithm with refinement


1. Get the distance in miles
2. Convert the distance to kilometers
2.1. Distance in kilometers is 1.609 multiplied with the distance in miles
3. Display the distance in kilometers

7
APPLYING THE SOFTWARE DEVELOPMENT METHOD

Case Study

Coding and Debugging

Implement the algorithm as a program using the C


programming language

8
Coding and
Debugging

9
C
‣ high-level programming language developed in
1972 by Dennis Ritchie at AT&T Bell Laboratories

‣ designed to write the UNIX operating system

‣ originally used primarily for systems programming

10
11
C LANGUAGE ELEMENTS
Preprocessor Directives
Preprocessor

‣ a system program that modifies a C program prior to its compilation

Preprocessor Directive

‣ a command that gives instruction to the preprocessor

‣ begins with a number symbol (#) as its first nonblank character

Library

‣ a collection of useful functions and symbols that may be accessed by a


program

‣ has a standard header file whose name ends with the symbols .h

12
C LANGUAGE ELEMENTS
Preprocessor Directives
#include Directive

‣ causes the preprocessor to insert definitions from a standard


header file into a program before compilation

‣ gives the program access to a library

‣ tells the preprocessor where to find the meanings of standard


identifiers used in the program

Syntax: #include<standard header file>

Example: #include<stdio.h>
#include<math.h>
13
C LANGUAGE ELEMENTS
Preprocessor Directives
#define Directive

‣ notifies the C preprocessor to replace each occurrence of the identifier NAME by


value

‣ C program statements cannot change the value associated with the NAME

constant macro

‣ name that is replaced by a particular constant value before the program is sent to
the compiler

‣ an executing C program cannot change the value of a name defined as a constant


macro

Syntax: #define NAME value

Example: #define KMS_PER_MILE 1.609

14
C LANGUAGE ELEMENTS
Function main
‣ every C program has a main function

‣ marks the point where program execution begins

Function Body

‣ remaining lines of the program enclosed in curly brackets

Two parts: 1. Declarations


2. Executable Statements
Syntax:

int main(void){
function body
}

15
C LANGUAGE ELEMENTS
Reserved Words
‣ a word that has special meaning in C and cannot be
used for other purposes

‣ all reserved words appear in lowercase

‣ here is a complete list specified by ANSI (American


National Standards Institute) C

16
C LANGUAGE ELEMENTS
Identifiers
Standard Identifiers

‣ a word that have special meaning but one that can be


redefined and used by a programmer for other
purposes

‣ redefinition is not recommended because C will no


longer be able to use it for its original purpose

Example: printf
scanf

17
C LANGUAGE ELEMENTS
Identifiers
User-Defined Identifiers

‣ identifiers chosen by a programmer to name memory


cells that will hold data and program results

Example: KMS_PER_MILE
miles
kms

18
C LANGUAGE ELEMENTS
Identifiers
Syntax Rules

1. An identifier must consist only of letters, digits and underscores

2. An identifier cannot begin with a digit. It can begin with a letter or an


underscore. However, it is discouraged to start an identifier with an underscore
because it can conflict with system names.

3. A C reserved word cannot be used as an identifier

4. C compiler is case sensitive, identifiers that are composed of the same


characters and symbols but differ in their uppercase and lowercase letters are
considered different identifiers

5. There is no rule on the length of an identifier. However, the first 31 characters of


identifiers are discriminated by the compiler. So, the first 31 letters of two
identifiers in a program should be different.

19
C LANGUAGE ELEMENTS
Identifiers
Good programming practice when choosing identifier names,

1. Pick a meaningful name for user-defined identifiers so its use


is easy to understand

2. Choose identifiers long enough to convey meaning but avoid


excessively long names because you are more likely to
make a typing error in longer names

3. Do not choose names that are similar to each other

4. Avoid selecting two names that are different only in their


uppercase and lowercase letters

20
C LANGUAGE ELEMENTS
Identifiers
Which of the following are valid identifiers?
1Letter
MAX_ENTRIES
TWO*FOUR
_variable2
joe’s
double
xYZ123
part#2
XyZ123

this_is_a_long_one

21
C LANGUAGE ELEMENTS
Identifiers
Which of the following are valid identifiers?
1Letter invalid, cannot begin with a digit

MAX_ENTRIES valid
TWO*FOUR invalid, char * is not allowed
_variable2 valid, not recommended
joe’s invalid, char ‘ is not allowed
double invalid, reserved word
xYZ123 valid
part#2 invalid, char # is not allowed
XyZ123 valid

this_is_a_long_one valid

22
C LANGUAGE ELEMENTS
Identifiers
Which of the following are valid identifiers?
4score
color12
CONST_TIME
helloworld
two!s
for
static
@twitter
Gender

_x2y1z0

23
C LANGUAGE ELEMENTS
Identifiers
Which of the following are valid identifiers?
4score invalid, cannot begin with a digit

color12 valid
CONST_TIME valid
helloworld valid
two!s invalid, char ! is not allowed
for invalid, reserved word
static invalid, reserved word
@twitter invalid, char @ is not allowed
Gender valid

_x2y1z0 valid, not recommended

24
Variable Declarations and Data Types

Variable

‣ a name associated with a memory cell whose value can


change as the program executes

Variable Declarations

‣ statements that communicate to the compiler the names of


variables in the program, the kind of information stored in
each variable and how that information will be represented in
memory

25
Variable Declarations and Data Types
Syntax:

<data_type> <variable_list>;

Examples:

int count, large;

double rate, time;

char middle_initial;

char answer;

int age;

26
Variable Declarations and Data Types
Data Type

‣ a set of values and operations that can be performed on those values

‣ knowledge of the data type of an item (variable or value) enables the


C compiler to correctly specify operation on that item

‣ objects of a data type can be variables or constants

Standard Data Types in C

‣ predefined data types

e.g int
char
double
27
Variable Declarations and Data Types

Data Type int

‣ used to represent integers in C

‣ integers are positive and negative real numbers

‣ whole numbers are integers

‣ because of the finite size of a memory cell, not all integers


can be represented

‣ ANSI C specifies that that the range must include atleast the
values -32767 through 32767

28
Variable Declarations and Data Types

Data Type double

‣ used to represent real numbers in C

‣ real numbers has an integral part and a fractional part that are
separated by a decimal point

‣ scientific notation can be used to represent real numbers

e.g 123000.0
1.23 x 105 Normal Scientific Notation
*1.23e5 or *1.23E5 C Scientific Notation

* you can read ‘E’ or ‘e’ as “times 10 to the power”

29
Variable Declarations and Data Types

Data Type char

‣ used to represent an individual character value - a


letter, a digit or a special symbol

‣ each value is enclosed in single quotes

‣ represented in the memory as an integer whose value


is determined by the code used by the C compiler

e.g ‘A’ ‘z’ ‘2’ ‘9’ ‘*’ ‘ ’

30
Variable Declarations and Data Types

ASCII (American Standard Code for Information Interchange)

‣ most common code used to specify the integer representing


each char value

31
Variable Declarations and Data Types
Indicate which of the following are valid type int, double, or char constants
in C and which are not. Identify the data type of each valid constant.
‘PQR'
15E-2
35
‘h'
-37.491
.912
4,719
‘true’
‘$’
&
4.5e3
32
Variable Declarations and Data Types
Indicate which of the following are valid type int, double, or char constants
in C and which are not. Identify the data type of each valid constant.
‘PQR' invalid, single letter
15E-2 valid, double
35 valid, int
‘h' valid, char
-37.491 valid, double
.912 valid, double
4,719 invalid, comma not allowed
‘true’ invalid, single letter
‘$’ valid, char
& invalid, should be enclosed with single quotes
4.5e3 valid, double
33
Variable Declarations and Data Types
What data types would you use to represent the following items:

number of children at school

a letter grade on an exam

average number of school days a student is


absent each year

first letter of your last name

number of cars passing through an


intersection in an hour

area of a circle in square inches

34
Variable Declarations and Data Types
What data types would you use to represent the following items:

number of children at school int

a letter grade on an exam char

average number of school days a student is


absent each year double

first letter of your last name char

number of cars passing through an


intersection in an hour int

area of a circle in square inches double

35
Executable Statements
‣ follow after the declarations in a function

‣ C statements used to write or code the algorithm and


its refinements

‣ C compiler translates these into executable machine


language; the computer executes the machine
language version of these statements when we run the
program

36
Executable Statements
Assignment Statement

‣ an instruction that stores a value or a computational


result in a variable

‣ used to perform most arithmetic operations in a


program

‣ In C, the symbol ‘=’ is the assignment operator and is


read as “becomes”, “gets”, “take the value of”

37
Executable Statements
Assignment Statement

‣ an instruction that stores a value or a computational


result in a variable

‣ used to perform most arithmetic operations in a


program

‣ In C, the symbol ‘=’ is the assignment operator and is


read as “becomes”, “gets”, “take the value of”

variable = expression;

38
Executable Statements
Assignment Statement

kms = KMS_PER_MILE * miles;

39
Executable Statements
Assignment Statement

sum = sum + item;

40
Executable Statements
Assignment Statement

A single char variable next_letter is assigned the


character value ‘A’ by the assignment statement

next_letter = ‘A’;

41
Executable Statements
I/O Operations and Functions

‣ alternative way of storing values or computational results into a


variable

‣ done by copying data from an input device into a variable

Input Operation

‣ an instruction that copies data from an input device into memory

Output Operation

‣ an instruction that displays information stored in memory

42
Executable Statements
I/O Functions

‣ C functions that perform input and output operations

‣ the most common functions are supplied as part of the C standard input/
output library to which we gain access through the preprocessor directive

Function Call

‣ activating a function

‣ analogous to asking a friend to perform an urgent task. You tell them what
to do (not how to do it) and wait for your friend to report back that the task
is finished. After hearing from your friend, you can go and do something
else.

‣ consist of 2 parts: 1. function name


2. function arguments

43
Executable Statements
Calling the printf Function

function arguments

‣ enclosed in round brackets following the function name

‣ provides information needed by the function

print list

‣ variables or expressions whose values are displayed

‣ if the print list has several variables, the format string should contain the same
number of placeholders

44
Executable Statements
Calling the printf Function

Syntax: printf(format string, print list);


printf(format string);

Example:
printf(“I am %d years old, and my gpa is %f\n", age, gpa);
printf(“Enter the object mass in grams>” );

format string

‣ sequence of characters enclosed in quotes which specifies the form of the


output

placeholder

‣ a symbol beginning with a % in a format string that indicates where to display


the output value

‣ an abbreviation for the type of data it represents


45
Executable Statements
Calling the scanf Function

‣ copies into memory data typed at the keyboard by the program user
during program execution

Syntax: scanf(format string, input list);


Example: scanf(“%lf”, &miles);
scanf(“%c%d”, &first_initial, &age);

‣ The format string is a quoted sequence of placeholders, one


placeholder for each variable in the input list

‣ Each int, double or char variable in the input list should be preceded by
the address-of operator - &.

‣ The order of the placeholders should correspond to the order of


variables in the input list

46
Executable Statements
Multiple Placeholders

‣ format strings can have multiple placeholders

‣ C matches variables with placeholders in left-to-right


order

47
Executable Statements
Formatting Numbers in Program Output

‣ the number of columns used to display a value is called field width

‣ digits are displayed right-justified

Formatting Values of Type int

48
Executable Statements
Formatting Values of Type double

‣ must indicate both the total field width needed and the
number of decimal places desired

49
Executable Statements
return Statement

Syntax: return expression;

Example: return 0;

‣ transfers control from a function back to the activator/


caller of the function

‣ the value of expression is returned as the result of the


function execution

50
Executable Statements
1. Show the output displayed by the following program lines when the data
entered are 5 and 7:

printf("Enter two integers> “);


scanf("%d%d", &m, &n);
m = m + 5;
n = 3 * n;
printf("m = %d\nn = %d\n", m, n);

2. Write a statement that asks the user to type three integer and another
statement that stores the user responses into first, second, third

3. Write a program that asks the user to enter the radius of a circle and then
computes and displays the circle’s area. Use the formula

Area = PI x Radius x Radius

where PI is the constant macro 3.14159

51
Executable Statements

4. List 3 standard data types of C

5. The average pH of citrus fruits is 2.2, and this value


has been stored in the variable avg_citrus_pH
Provide a statement to display this information in a
readable way.

6. Write an algorithm that allows for the input of an


integer value, doubles it, subtracts 10, and displays
the result.

52
General Form of a C Program

preprocessor directives

main function heading


{

declarations

executable statements

53
Arithmetic Expressions
Arithmetic Operators

‣ each operator manipulate two operands, which may be


constants, variables or other arithmetic expressions

54
Arithmetic Expressions
Division Operator ( / )

‣ will compute the integral part of the result when applied to two positive integer
operands

‣ when used with a positive and negative operands, the result may vary from one
C implementation to another. Thus, avoid using division with negative integers

55
Arithmetic Expressions
Remainder Operator ( % )

‣ also known as the Modulo Operator

‣ returns the integer remainder of the result of dividing its first operand by its second
operand

‣ the magnitude of m % n must always be less than the divisor

56
Arithmetic Expressions
Unary Operator

‣ are operator with one operand

e.g. negation ( - )
plus ( + )

Binary Operator

‣ an operator with two operands

57
Arithmetic Expressions
Data Type of an Expression

‣ depends on the type(s) of its operands

Mixed-Type Expression

‣ an expression with operands of different types

Mixed-Type Assignment

‣ the expression being evaluated and the variable to which it is assigned have
different data types

m = 3;
n = 2;
p = 2.0;
x = m / p;
y = m / n;
58
Arithmetic Expressions
Rules for Evaluating Expressions

1. Parentheses rule

‣ all expressions in parentheses must be evaluated separately.

‣ nested parenthesized expressions must be evaluated from inside out, with the innermost
expression evaluated first

2. Operator precedence rule

‣ operators in the same expression are evaluated in the following order:

unary +,- first


* , /, % next
binary +, - last

3. Associativity rule

‣ Unary operators in the same subexpression and at the same precedence level are
evaluated right to left (right associativity)

‣ Binary operators in the same subexpression and at the same precedence level are
evaluated left to right (left associativity)
59
Arithmetic Expressions
z - (a + b / 2) + w * -y

60
Arithmetic Expressions

The formula for the average velocity, v, of particle


travelling on a line between points p1 and p2 in time t1 to
t2 is,

61
Arithmetic Expressions

62
Arithmetic Expressions

‣ always specify multiplication explicitly by using the operator * where needed

‣ use parentheses when required to control the order of operator evaluation

‣ two arithmetic operators can be written in succession if the second is a unary


operator

63
Arithmetic Expressions
Given the following declarations,

#define PI 3.14159
#define MAX_I 1000
double x, y;
int a, b, i;

Indicate which of the following statements are valid, and find


the value stored by each valid statement. Also indicate which
are invalid and why. Assume that a is 3, b is 4, and y is -1.0

64
Arithmetic Expressions
1. i=a%b; 10. i=(MAX_I−990)/a;

2. i=(989−MAX_I)/a; 11. x=a/y;

3. i=b%a; 12. i=PI*a;

4. x=PI*y; 13. x = PI / y;

5. i=a/−b; 14. x=b/a;

6. x=a/b; 15. i=(MAX_I−990)%a;

7. x=a%(a/b); 16. i=a%0;

8. i=b/0; 17. i=a%(MAX_I−990);

9. i=a%(990−MAX_I); 18. x=(double)a/b;

65
Programming Exercises
1. Write a program to compute the average of three given
numbers

2. Write a program to compute the seconds from a given


age

3. Write a program to swap values of two integer


variables

66
Write pseudocode versions of the following:
1. An algorithm that gets three data values x, y, and z as
input and outputs the average of those three values

2. An algorithm that gets the amount of electricity used in


kilowatt-hours and the cost of electricity per kilowatt-
hour. Its output is the total amount of the electric bill,
including an 8% sales tax

3. An algorithm that is given three numbers corresponding


to the number of times a race car driver has finished first,
second, and third. The algorithm computes and displays
how many points that driver has earned given 5 points
for a first, 3 points for a second, and 1 point for a third
place finish
67
Questions?

68

You might also like