Sunteți pe pagina 1din 52

Chapter 3:

Introduction to C Programming
PART ONE

PREPARED BY: TEH FARADILLA ABDUL RAHMAN

Student Learning Time Hours


Lecture 2
Test 1
Project 3
Assignment 2

CSC 099
LEARNING OUTCOMES
At the end of this lesson, students should be
able to
1. illustrate the basic structure of C program

2. apply the concepts of


- Data types
- Identifiers : variables & constants
- standard input & output function
- different ways of writing output statement
Introduction
 Initially developed in 1970s at AT&T Bell
Laboratories by Ken Thompson, Dennis Ritchie and
Brian Kernighan
 C language facilitates a structured and disciplined
approach to computer design
 It has an extensive set of capabilities that permits it
to be written as a high-level structured language,
while providing abilities to directly access the
internal hardware of a computer.
Example: C Program

Program
Output
Structure of C Program
/*Written by: Nurul Syatrah*/
Comments
//This program is to calculate the area of a cylinder

#include <stdio.h> Preprocessor directive Header file


Define constant pi with value
#define pi 3.142 3.142

int main() main() function


{ Variable declaration
float radius, height, Area_cylinder; (local declaration)
printf(”Please enter radius: “);
scanf(“%f”,&radius);
Function
printf(”Please enter height: “);
body scanf(“%f”,&height); Statements

Area_cylinder = 2*pi*radius*height;

printf(”Area for the cylinder is %f “, Area_cylinder);

return 0;
Return statement
}
Structure of C Program
6
Comments
 Two format
 Line comment
 Marked by two slashes (//) at the beginning of comment
 For short comment  in a single line
 Example: //Written by : Rosmiza Wahida
 Block comment
 Marked by opening token(/*) and closing token (*/)
 For long comment
 Example : /*This program is to calculate the area of a cylinder*/
 Comments CANNOT be nested (comments inside comments)
 Use : to document programs and improve program readability
 Help other people read and understand others program
 IGNORED by C compiler and DO NOT cause any machine-language object code to be generated.
 DO NOT cause the computer to perform any action when the program is run.
 CAN be put ANYWHERE in the program
Structure of C Program
7
Preprocessor Directive
 Will be read first before the program is compiled
 Indicated by hash sign (#) together with keyword
 #include – to include the contents of another file
 #define – to define global variable/constant
** No space between # and include
#include <stdio.h>
 stdio.h
 Is the name of the file that is to be included.
 Dot h indicates the type of the file – header file
 Allow C program to display output on the screen – printf() and read input from the
keyboard – scanf()
#define pi 3.142
 pi - Name of constant
 3.142 – value of the constant
Structure of C Program
8

main() function
 C Program can have one or more functions, exactly one MUST
be main() function
int main()
int – stands for Integer. It indicates that the function sends an
integer back to operating system when it is finished
executing
main() – the name of the function

MUST be followed by set of braces ({ }) – indicates a block, the


beginning and ending of a function
 All statements (function body) that make up a function are enclosed in a
set of braces
Structure of C Program
9

Function Body
 Enclosed by a set of braces ({ })
 Function contains
 Local declaration
 Declaration of data that will be used for the function/program
 Example :
float radius, height;
 Statements @ Program body
 Set of instructions of what the function/program should do
 Return Statement
 Return value that sends back to operating system
 Example :
return 0;
** 0 usually indicates that a program executes successfully
Common Programming Language
Elements
10

 Syntax
 Rules that must be followed when constructing a program
 Lines
 A “line” is a single line appear in the body of program
 Statement
 A complete instruction that causes the computer to perform
some action
 Keywords (Reserve Words)
 Words that have special meaning and used for intended
purpose
Common Programming Language
Elements
11

 Programmer-Defined Identifier (Identifier)


 Words/names defined by programmer. Symbolic
names refer to variables or functions
 Operators
 Operator perform operations on one or more operands
 Punctuations
 Punctuation
characters mark the beginning or ending of
a statement, or separate item in a list
12
Punctuations
 Comma (,)  use to separate item in a list
 Use to separate item in a list
 Example :
float radius, height;
 Semicolon (;)
 Use at the end of a complete instruction
 Example :
float radius, height;
printf(“Please enter radius: ”);
A_cyl = 2*pi*radius*height;
return 0;
13
Reserve Word/Keyword
 Special words reserve for C Program which have
specific meaning and purpose
 CANNOT be used as identifiers or variable name
 Appear in lower case
C and C++ Reserved Words
auto do goto signed union
break double if sizeof unsigned
case else int static void
char enum long struct volatile
const extern register switch while
continue float return typedef
default for short
Identifiers
14

 Allows programmers to NAME data and other objects in


the program
 variable, constant, function etc.
 Rules in naming identifiers
 MUST consist ONLY of alphabetic characters (uppercase or
lower case), digits and underscores (_)
 First character MUST be alphabetic character or underscore

 CANNOT contain spaces

 CANNOT be any reserved word

** C is CASE-SENSETIVE
 this means that average, Average, AveraGe and averaGe
are four completely different name.
15

Example of Valid & Invalid Identifiers

Valid Identifiers Invalid Identifiers

 X  *multiply // * is illegal
 student_name  4300zipcode2 // can’t
 _aSystemName start with number
 Pi  Area of circle// can’t have
space
 Aminah
 int // reserved word
 campusCode
 password43
 Birth0608day
Exercise
 Decide whether or not each of the following is a
valid C identifier

• _hello • km_per_hour
• Hello37 • speed!
• one+two • sensible$name
• Subject#1 • _num_incorrect
• M • 12oclock
• double • big long_name
17
Variables
 Variable names correspond to locations in the computer's
memory
 Every variable has a NAME, a DATA TYPE, a SIZE and a
VALUE
 A variable is created via a declaration where its name
and type are specified.
 Example :
 int integer1, integer2, sum;
 Whenever a new value is placed into a variable (through
scanf(), for example, it replaces (and destroys) the
previous value
Data Types
18

 Variables are classified according to their data type


 Determine the kind of information stored in
variables
 Address, phone numbers, price, distance, and etc.

 Functions also have types which determine by the


data it returns
 C Program have 5 standard data types:-
Data Types
‘C’ Data Amount of Description Example
19
type storage
void None Type of data that have no value void display();

int 4 bytes •Represent numerical value from int num = -28;


-2,147,483,648 to +2,147,483,647
•Whole number
float 4 bytes •Referred as single precision number and float length = 10.56;
the number contains decimal point float height = 1.5;
•Range values -1.4012984643e-45 to float area = 789.1557;
3.4028234663e+38
double 8 bytes •Referred as double precision number double dist= 546464.59;
•Range values -4.9406564584124654e-
324 to 1.7976931348623158e+308

char 1 byte for •Represent non numeric data Single character


each •Two type character data: single char grade = ‘A’;
character character and string String character
char status [5]=“PASS”;
Numeric Data Type
20
 Numeric data types are broken into 2 categories :
Integer and Floating-point
 Primary consideration for selecting data type:-
 The largest and smallest number that maybe stored in
the variable
 How much memory does the variable use

 Whether the variable stores signed or unsigned numbers

 The number of decimal places of precision the variable


has
 The size of variable is the number of bytes of
memory it uses. (> variable  > range can hold)
21
Integer Data Type
 To store WHOLE NUMBER without fraction
 C program supports 3 different sizes of integer
 short int

 int

 long int

Type Byte Size Minimum Maximum Value


Value
short int 2 -32,768 32,767
unsigned short int 2 0 65,535
int 4 -2,147,483,648 2,147,483,647
unsigned int 4 0 4,294,967,295
long int 4 -2,147,483,648 2,147,483,647

unsigned long int 4 0 4,294,967,295


22
Floating Point Data Type
 To store FLOATING-POINT number
 C program supports 3 different sizes of fraction number
 float

 double

 long double
Type Byte Precision Range
Size
float 4 6 10-37 ..1038

double 8 15 10-307 ..10308

long double 10 19 10-4931 ..104932


Variable Declaration
23
 Specifies in the memory to reserve a specific space for the
variable that have the specific location and can store specific
data type.
 Syntax Valid name

Types introduced
earlier are the Ends with
number types int can_per_pack ; a
int and semicolon
double
Variable Declaration
 Syntax :
data_type variable_name ;
Example
int maxItems;
float payRate;
double tax;
char code;
int a, b; // equivalent to int a; int b;
Example
Data
of Variable in Memory
25
identifier
type
Program code Memory
char blood_type ; A blood_type ;

int age ; 19 age ;

long int current_debt 1000299123 current_debt

float height; 1.45 height;

double acceleration ; 3.01892725 acceleration ;


26
Variable Initialization
 To establish the first value that the variable will
contain
 Syntax :
data_type variable_name = value;
 Example :
 int count = 5;
 int sum = 0;

 int count = 5 , sum = 0;

 char letter = ‘B’;


Common Error:
Using Undefined Variables
 MUST be declared before the executable of the statement
 Variable need to FIRST declare before it being used

 Example:
double can_volume;
can_volume = 12 * litter_per_ounce;
double litter_per_ounce = 0.0296;
Common Error:
Using Uninitialized Variables
 Using a variable without initializing it, then the prior
value will be used, yielding unpredictable result.
 Example
int bottles; //forgot to initialize
int bottle_volume;
bottle_volume = bottles * 2;
 It is impossible to know what value will be computed
 Plausible value will happen to appear when you run the
program
Exercise
 Identify valid and invalid variable name:
sum.of , 12345 , newbal , c123 , @balance
 Write a declaration statement to declare the variable count
that will be used to store an integer
 Write a declaration statement to declare the variable choice
that will be used to store a character
 Write a declaration statements for the following :

i) tempA, tempB, and tempC used to store double- precision


number
ii) price, yield, and coupon used to store single- precision
numbers
30
Constants
 To define values that CANNOT be changed during
the execution of a program
 Types of constant: Integer constant, Float constant
Character constant ,String constant and Symbolic
constant
 3 ways of defining a constant
 Literal
Constant
 Defined Constant – using preprocessor

 Defined Constant – using const


31
Literal Constants
 An unnamed constant used to specify data
 If the data CANNOT be changed, it can simply code
the value itself in a statement
 Example :
 ‘A’ // a char literal
5 // a numeric literal 5
a + 5 // numeric literal
 Tax = price * 0.06 // numeric literal
 3.1435 // a float literal
 “Hello” // a string literal
32
Defined Constants
 2 ways :-
 Using preprocessor : #define
 Example :
#define pi 3.142
 Using keyword : const
 Example
const int a = 1;
Example: Constant
#include <stdio.h>
#define SALESTAX 0.05 Define constant using preprocessor
int main()
{
const float service = 3.25; Define constant using keyword const
float taxes, total, amount;

printf("Enter the amount of purchased: ");


scanf("%f",&amount);

taxes = SALESTAX*amount*0.33; Literal float 0.33


total = amount+taxes+service;

printf("The total bill is RM%.2f", total);


}
Exercise
 Give the preprocessor directives to assign symbolic
constant for these constants:
8
 Speed of light is 2.99792 X 10 m/s
 #define LIGHT_SPEED 2.99792e08
 Neutron Mass is 1.674920 x10-24 gram
 #define mass_of_nuetron 1.674920e-24
 Gravity, g = 9.8 m/s
 #define gravity 9.8
 Unit of length, given unit_length = ‘m’
 #define unit_length ‘m’
 Unit of time, given unit_time = ‘s’
 #define unit_time ‘s’
Standard Input Function
35

 Syntax of scanf()
 scanf(FormatControlString, InputList);
 Example: int number_of_student_in_a_class;
scanf(“%d”, &number_of_student_in_a_class);
** FormatControlString MUST consist of format specifiers
only
** Each element in InputList must be an ADDRESS to a
memory location for which it must be made into
** Address of memory location is specified by prefixing the
variable name with an ampersand character (&) address
operator
Common scanf() Format Specifiers
36

Data Type Format Specifiers


int
float
double
char
string
37
Example : scanf() Function
int shoeSize;
scanf( "%d", &shoeSize );

 %d - indicates data should be an integer value


 &shoeSize - location in memory to store variable

** When executing the program the user responds to the


scanf() statement by typing in a number, then pressing
the enter (return) key
Example : scanf() Function
38

double height;
int year;
scanf(“%lf”, &height);
scanf(“%d”, &year);
scanf(“%lf”, height); /* This is an error!! */
Example : Inputting Multiple Values with
39
a single scanf()
int height;
char ch;
double weight;

scanf(“%d %c %lf”, &height, &ch , &weight);

Put space between the specifiers


** It is always better to use multiple scanf()s, where each
reads a single value
Escape Sequence
40

 Indicates that printf() should do something out of the


ordinary
 When encountering a backslash(\) in a string, the
compiler looks ahead at the next character and
combines it with the backslash to form an escape
sequence.
Standard Output Function
41

 The syntax of printf()


When we want to
1. printf(FormatControlString); display only sentences
Example : printf (“Hello Dear, \n”); without any values

2. printf(FormatControlString Format specifier, PrintList);


 Example : int year=2006;
printf(“Year is %d”, year);

Specifier for printing an integer To read the value of an integer


value from this variable
Common Output Format Specifiers
42

 Specifies the argument type


Data Type Format Specifiers
int %d
float %f
double %lf
char %c
string %s
Example : printf() function
43

int sum, x = 5, y = 5;
sum = x + y;
printf( "Sum is %d\n", sum );
%d means an integer will be sum specifies what integer-value will
printed be printed

float average;
average = 435 / 10;
printf( “Average is %f\n", average );
 %f means decimal number will be printed
 average specifies what value will be printed
Programming Example
 Write a full C program that allows user to enter two
integers, calculate and display the total of the two
integers.
1 /*
2 Addition program */
3 #include <stdio.h>
4
545 int main()
6 { variables declarations
7 int integer1, integer2, sum; //
declaration
8 */
9 printf( "Enter first integer\n" ); //
10 scanf( "%d", &integer1 ); // input
teger printf(
11 */ "Enter second integer\n" ); //
prompt
12 */
scanf( "%d", &integer2 ); // Calculate sum
integer
13 sum*/= integer1 + integer2; // • 2.1 Sum
assignment
14 printf(of "Sum
sum */
is %d\n", sum ); //
print sum
print sum */
15
16 return 0; // indicate that program ended
successfully */
17}

Enter first integer • Program Output


45
Enter second integer
72
Sum is 117 Juliana Jaafar 2011/2012
Exercise
 Write C program that calculates and display
the area of triangle.

 Write C program that multiplies the value of num1


by 2, adds the value of num2 to it, and then stores
the results in newNum. Then, write a C statement
that outputs the value of newNum.
Different Ways of Formatting printf()
47

 Display normal message


printf("Hello Welcome to C Programming Class");
 Display space
printf("\tWelcome");
 Display new line
printf("\nHello Everyone\n");
 Printing value of variable
printf("Addition of two Numbers : %d", sum);
 Printing value of the calculation
printf("Addition of two Numbers : %d", num1+num2);
Different Ways of Formatting printf()
48

 Multiple format specifier


printf("I get %c in %s",‘A’,“Programming”);
int age = 45;
float height = 1.72;
printf(“My age is %d and height is %f", age, height)
 Display integer in different styles
printf(“\n%d",1234); 1234
***Note:
printf(“\n%3d",1234); 1234 ‘#’ symbol is used to
printf(“\n%6d",1234); ##1234 indicate empty
spaces
printf(“\n%-6d",1234); 1234##
printf(“\n%06d",1234); 001234
Different Ways of Formatting printf()
49

 Display fraction number in different styles


printf("\n%f",1234.12345);
printf("\n%.4f",1234.12345);
printf("\n%3.2f",1234.12345);
printf("\n%-10.2f",1234.12345);
printf("\n%10.2f",1234.12345);
Output
1234.123450 //by default, it will print 6 values after the decimal
1234.1235
1234.12
1234.12###
###1234.12
Different Ways of Formatting printf()
50
• Display string in different styles
char str[]="Programming"; // Length = 11
printf("\n%s",str); // Display Complete String
printf("\n%10s",str); // 10 < string Length, thus display Complete String
printf("\n%13s",str); // Display Complete String with RIGHT alignment
printf("\n%-13s",str); // Display Complete String with LEFT alignment
printf("\n%7.5s",str); //Width=7 and show only first 5 characters with
RIGHT alignment
printf("\n%-7.5s",str); //Width=7 and show only first 5 characters with
LEFT alignment
Output
Programming
Programming
##Programming
Programming##
##Progr
Progr###
Standard Output & Input Function
51

 Output function  printf()


 To display message on the computer’s screen
 Example :
printf(“Programming is great FUN!! Loving IT!”);
printf(“*************************************”);

 Input function  scanf()


 To get data typed by user from the keyboard
 Example :
printf(“Please enter an integer value >>\n”);
scanf(“%d”, &value);

** MUST include <stdio.h> header file


Exercise
Figure 1 shows a rim of a flat washer.
Write a program to find the area of the
rim. Get the value of d1 and d2 from
the user. Display the output in two
decimal number format.

S-ar putea să vă placă și