CHAPTER 3:
INTRODUCTION TO C PROGRAMMING
CSC 099
Edited by: Zaid Mujaiyid Putra
Learning Outcomes
At the end of this topic, students should be able to:
1. Describe the basic structure of C programming.
2. Declare variables in C programming.
3. Apply the concepts of data types, identifiers
and various operators used in C programming.
4. Use the standard input & output function.
5. Translate from an algorithm to programming.
Part I : C
Programming
Introduction
C language facilitates a structured and
disciplined approach to computer design
Its capabilities:
Permits to be written as a high-level
structured language
Provides to directly access the internal
hardware of a computer.
Example: C Program
Program
Output
Structure of C Program
//Written by: Nurhilyana Anuar
/*This program is to calculate the area of a cylinder*/
#include <stdio.h>
#define pi 3.142
Comments
Preprocessor
Header
directive
file
main()
function
int main()
{
float radius, height;,A_cyl;
printf(Please enter radius: );
scanf(%f,&radius);
printf(Please enter height: );
scanf(%f,&height);
printf(Area for the cylinder is %f , A_cyl);
Function
body
Variable
declaration
(local
declaration)
Statemen
ts
A_cyl = 2*pi*radius*height;
return 0;
Define constant pi with
value 3.142
Return
statement
Structure of C Program
7
Comments
Two format
Line comment
Two slashes (//) at the beginning of comment
Eg: //Written by : Rosmiza Wahida
Block comment
Consists of opening token(/*) and closing token (*/)
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
Structure of C Program
8
Preprocessor Directive
Will be read first before the program is compiled
Indicated by pound or hash sign (#)
#include to include the contents of another file
#define to define global variable/constant
** No space between # and include
#include <stdio.h>
stdio.h
Dot h (.h) header file
Allows printf() and scanf()
#define pi 3.142
pi - Name of constant
3.142 value of the constant
Structure of C Program
9
main() function
compulsory function
int
stands
for Integer.
indicates that the function sends an integer
back to operating system
main()
name of the function
MUST be followed by a set of braces ({ })
the beginning and ending of a function
Structure of C Program
10
Function Body
Enclosed by a set of braces ({ })
Function contains
Local declaration
Declaration
of variables used in that particular function
Example:
float radius, height;
Statements OR 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 has been executed
successfully
Common Programming Language
Elements
11
Syntax
Line
A line is a single line appear in the body of
program
Statement
Rules that must be followed when constructing a
program
A complete instruction that causes the computer to
perform some action
Keywords (Reserved Words)
Words that have special meaning and used for
intended purpose
Common Programming Language
Elements
12
Programmer-Defined Identifier
(Identifier)
Operators
Words/names defined by programmer.
Symbolic names refer to variables or functions
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
Punctuations
13
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;
Reserved Words/Keywords
14
Special words reserved for C Program
which have specific meaning and
purpose
CANNOT be used as identifiers or
variable name
C and C++ Reserved Words
auto in lower
do
goto
Appear
case
signed
union
break
case
char
const
continue
default
double
else
enum
extern
float
for
if
int
long
register
return
short
sizeof
static
struct
switch
typedef
unsigned
void
volatile
while
Identifiers
15
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 duplicate with any reserved word.
** C is CASE-SENSETIVE
this means that NUM1, Num1, num1, and NuM1 are
four completely different names.
16
Example of Valid & Invalid Identifiers
Valid Identifiers
A
student_name
_aSystemName
Pi
Al
stdntNm
anthrSysNm
PI
Invalid Identifiers
$sum // $ is illegal
2names // cant
start with 2
stdnt Nmbr // cant
have space
int // reserved word
Variables
17
Names correspond to locations in the
computer's memory
Has an IDENTIFIER, a DATA TYPE, a
SIZE and a VALUE
Created via a declaration:
int integer1, integer2, sum;
Values are replaced once received
input from scanf()
Variable Declaration
18
To reserve a specific space in memory
Variable needs to be declared FIRST before use
Syntax :
data_type variable_name;
Example:
int maxItems = 0;
float payRate;
double tax;
char code;
int a, b;
// equivalent to int a; int b;
19
Example of Variables in
Memory
long
int
Data Types
Determine the kind of
information stored in variables.
Classify variables.
Functions also have types which
determine by the data it returns.
5 Standard Data Types
21
Data
types
Amount Description
of
storage
Example
void
None/Nu
ll
Type of data that have no value
void display();
int
4 bytes
Represent numerical values
from
-2,147,483,648 to
+2,147,483,647
Whole number
int num = -28;
float
4 bytes
Referred as single precision
number and
the number contains decimal
point
Range values -1.4012984643e45 to 3.4028234663e+38
float length = 10.56;
float height = 1.5;
float area =
789.1557;
double
8 bytes
Referred as double precision
number
Range values
double dist=
546464.59;
Numeric Data Types
22
Numeric data types are divided into 2
categories :
Integer
Floating-point
Integer Data Type
23
To store WHOLE NUMBER without fraction
C program supports 3 different sizes of integer
short int
int
long int
Maximum Value
2
2
Minimum
Value
-32,768
0
int
unsigned int
long int
4
4
4
-2,147,483,648
0
-2,147,483,648
2,147,483,647
4,294,967,295
2,147,483,647
unsigned long int
4,294,967,295
Type
Byte Size
short int
unsigned short int
32,767
65,535
Floating Point Data Type
24
To store FLOATING-POINT number
C program supports 3 different sizes of integer
float
double
long double
Range
Type
Byte
Size
Precision
float
10-37 ..1038
double
15
10-307 ..10308
long double
10
19
10-4931 ..104932
Variable Initialization
25
To set first value of a variable
Syntax :
data_type
variable_name = value;
Example :
int count = 5;
int sum = 0;
int count=0 , sum = 0;
char letter = B;
Exercises
Identify valid and invalid variable name:
sum.of , 12345 , newbal , c123 , $balance
Write a declaration statement to declare that the variable
count will be used to keep an integer
Write a declaration statement to declare that the variable
grade will be used to keep a character
Write a declaration statements for the following :
i) tempA, tempB, and tempC used to assign integer
numbers
ii) price, yield, and coupon used to assign decimal
numbers
27
Standard Output & Input
Function
Output function printf()
To display information on the computer screen
Example :
printf(Programming is great FUN!! Loving IT!);
Input function scanf()
To read data that entered from a keyboard
Example :
printf(Please enter an integer value >>\n);
scanf(%d, &val1);
** MUST include <stdio.h> header file
Escape Sequence
28
backslash(\) in a string
Escape
Sequence
\n
\t
\a
\\
\
Description
Newline. Position the cursor at the
beginning of the next line.
Horizontal tab. Move the cursor to
the next tab stop.
Alert. Sound the system bell.
Backslash. Insert a backslash
character in a string.
Double quote. Insert a double-quote
character in a string.
Standard Output Function
29
2 Syntax of printf()
Write your message
here.
printf(FormatControlString);
Example :
printf (Hello Dear, \n);
Write your message
here.
printf(FormatControlString FormatSpecifier,
PrintList);
Example :
int year=2006;
printf(Year is %d, year);
FormatSpecifier for
printing an integer
value.
Position where the value
To read the value of an
integer from this variable
30
Common Output Format
Specifiers
Specifies the argument type
Data Type
Format Specifiers
int
%d
float
%f
double
%lf
char
%c
string
%s
Example : printf() function
31
printf( "Sum is %d\n", sum );
%d means the value of the mentioned
variable is printed here.
sum retrieve the value kept in variable
sum.
Question
Let say, the value kept in sum variable is
10, what is the actual output?
Different Ways of Formatting
printf()
32
Display normal message
printf("Hello Welcome to C");
Display space/tab
printf("\tWelcome");
Display new line
printf("\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()
33
Multiple format specifier
printf("I Love %c %s",'c',"Programming");
Display integer in different styles
printf(\n%d",1234);
printf(\n%3d",1234);
printf(\n%6d",1234);
printf(\n%-6d",1234);
printf(\n%06d",1234);
Output
1234
1234
##1234
1234##
001234
***Note:
# symbol is used to indicate
empty spaces
Different Ways of Formatting
printf()
34
Display fraction number in different styles
printf("\n%f",1234.12345);
printf("\n%.4f",1234.12345);
printf("\n%3.2f",1234.12345);
printf("\n%-15.2f",1234.12345);
printf("\n%15.2f",1234.12345);
Output
1234.123450
decimal
//by default, it prints 6 values after the
1234.1235
1234.12
1234.12########
(.)
########1234.12
(.)
// prints from left (-ve). 15 spaces including
// prints from right (+ve). 15 spaces including
Different Ways of Formatting
printf()
35
Display fraction number 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%15s",str);
// Display Complete String with RIGHT alignment
printf("\n%-15s",str); // Display Complete String with LEFT alignment
printf("\n%15.5s",str);
//Width=15 and show only first 5 characters with
RIGHT alignment
printf("\n%-15.5s",str);
//Width=15 and show only first 5 characters with
LEFT alignment
Output
Programming
Programming
####Programming
Programming####
##########Progr
Progr##########
Standard Input Function
36
Syntax of scanf()
scanf(FormatControlString, InputList);
Example:
int age;
scanf(%d, &age);
format specifiers
only
& indicates
address of the
variable
37
Common scanf() Format
Specifiers
Data Type
Format Specifiers
int
%d
float
%f
double
%lf
char
%c
string
%s
38
Example : scanf() Function
scanf( "%d", &integer1 );
%d - indicates data should be an integer value ONLY
&integer1 - location in memory to store variable
** When executing the program, this scanf reads
the value that entered by using a keyboard.
Question
Let say, the value entered is 12. Where is the
value stored?
Example : scanf() Function
39
double height, weight;
int year;
printf(Input height value : );
scanf(%lf, &height);
printf(Year : );
scanf(d, year); /* Syntax error!!
Why? */
printf(Input weight value : );
scanf(%lf, weight); /* Syntax error!!
Why? */
Example : Input Multiple Values with a
single scanf()
40
int height;
char ch;
double weight;
scanf(%d %c %lf, &height, &ch , &weight);
Put a space between the specifiers
** It is always better to use multiple scanf()s,
where each reads a single value
1 /* Fig. 2.5: fig02_05.c
2
Addition program */
3 #include <stdio.h>
4
41
5 int main()
6 {
7
int integer1, integer2, sum;
declaration
*/
8
9
printf( "Enter first integer\n" );
prompt
*/
10
scanf(
"%d", &integer1 );
read an
integer
*/ second integer\n" );
11
printf(
"Enter
prompt
*/
12
scanf(
"%d", &integer2 );
read an
*/ + integer2;
13
suminteger
= integer1
assignment
of "Sum
sum */
14
printf(
is %d\n", sum );
print sum */
15
16
return 0; /* indicate that program
successfully */
17}
Enter first integer
45
Enter second integer
72
Sum is 117
/* Line 7 Initialize
variables
/*
Line 9 to12 Input
/*
Statement
/*
/*
Line 13 Sum
/*
/* Line 14 Output
Statement
ended
Juliana Jaafar 2011/2012
Program Output
42
Example of C Program
#include <stdio.h>
int main()
{
int num1;
scanf(%d,&num1 );
printf(You key in %d\n,num1);
return 0;
}
Structure of a C Program
43
Exercises
Determine and correct the errors of the
following program.
include <stdio.h>
int main()
{
width = 15
area = length * width;
printf(The area is %d,
&area);
#include <stdio.h>
#Pi 3.142
int main()
{
float circum, rad
scanf(%lf,rad);
circum = 2 * Pi * rad;
printf(The circumference is %d,
&circum);
}
Answers
Determine and correct the errors of the
following program.
#include <stdio.h>
int main()
{
int width, area, length;
width = 15;
area = length * width;
printf(The area is %d,
area);
}
#include <stdio.h>
#define Pi 3.142
int main()
{
float circum, rad;
scanf(%lf, &rad);
circum = 2 * Pi * rad;
printf(The circumference is %d,
&circum);
}
Constants
46
Identifiers that CANNOT be changed.
Contrast to variables.
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
Literal Constants
47
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
3.1435 // a float literal
Hello
// a string literal
Defined Constants
48
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
int main()
{
const float service = 3.25;
float taxes, total, amount;
Define constant using preprocessor
Define constant using keyword const
printf("Enter the amount of purchased: ");
scanf("%f",&amount);
taxes = SALESTAX*amount*0.33;
total = amount+taxes+service;
printf("The total bill is RM%.2f", total);
}
Literal float 0.33
How to convert from Algorithm to Coding?
Write a program that inputs 2 integers n1 and n2.
Then, calculate and print the value of num12 and
num23
How to convert from Algorithm to Coding?
Analysis
Input : num1,
num2
Processes :
1.
num1_sq = num1 x
num1
2.
num2_cb = num2 x
num2 x num2
Output :
num1_sq ,
num2_cb
Algorithm
Start
Enter num1
and num2
Calculate,
num1_sq = num1 x num1
num2_cb = num2 x num2
x num2
Display
num1_sq and
num2_cb
End
How to convert from Algorithm to Coding?
#include <stdio.h>
Algorithm
Start
int main()
{
int num1, num2, num1_sq, num2_cb;
Enter num1
and num2
printf("Please enter 1st integer: ");
scanf("%d", &num1);
INPU
T
Calculate,
num1_sq = num1 x num1
num2_cb = num2 x num2
x num2
Display
num1_sq and
num2_cb
printf("Please enter 2nd integer: ");
scanf("%d", &num2);
num1_sq = num1*num1;
PROCES
num2_cb = num2*num2*num2; S
OUTPU
T
printf("n1 squared is : %d \n",
num1_sq );
printf("n2 cubed is : %d \n", num2_cb
);
End
return 0;
Part II :
Operators
Assignment Operator (=)
54
To assign the value of variable or
expression into a variable.
Example:
a = b;
A;
result = n1*n1; alphabet =
Arithmetic Operators
55
Use to manipulate numeric values and
perform arithmetic operation
Assume : int a=4, b= 5, d;
C
Operation
Arithmetic
Operator
C
Expression
Value of d after
assignment
Addition
d=a+b
Substraction
d=b-2
Multiplication
d=a*b
20
Division
d = a/2
Modulus
d = b%3
Arithmetic Operators Assignment
Operators
56
Assume :
int x = 4, y=5, z=8;
Assignment
Operator
Sample
Expression
Similar
Expression
Value of variable
after assignment
+=
x += 5
x=x+5
x=9
-=
y -= x
y=y-x
y=1
*=
x *= z
x = x*z
x=32
/=
z /=2
z = z/2
z=4
y = y%x
y=1
%=
y %=x
Arithmetic Operator Increment &
Decrement Operator
57
Operator
Called
Sample
Expression
Similar
Expression
Explanation
++
preincrement
++a
a = a +1
Increment a by 1, then use
the new value of a in
expression in which a reside
a += 1
++
postincrement
a++
a = a +1
a += 1
--
predecrement
--a
a = a -1
a -= 1
--
postdecrement
a--
a = a -1
a -= 1
Use the current value of a in
the expression which a
reside, then increment a by 1
Decrement a by 1, then use
the new value of a in
expression in which a reside
Use the current value of a in
the expression which a
reside, then decrement a by 1
Example : Increment & Decrement
Operator
58
prefix
int c=5;
printf( "%d", ++c );
postfix
int c=5;
++c;
printf( "%d", c );
Output:
6
char alphabet = 'D';
++alphabet;
printf ("\n%c", alphabet);
printf ("\n%c", ++alphabet);
Output:
E
int num = 5;
--num;
printf("%d\n",num);
printf("%d",--num);
c=5;
printf( "%d", c++ );
Output:
6
int c=5;
c++;
printf( "%d", c );
Output:
4
3
char alphabet = 'D';
alphabet++;
printf ("\n%c", alphabet);
printf ("\n%c", alphabet++);
int num = 5;
num--;
printf("%d",num--);
printf("%d",num);
Output:
5
Output:
6
Output:
E
E
Output:
4
3
Example Tracing : Increment & Decrement
Operator
Trace the output for the following snippet
int a = code:
5, z=10;
int count=3, loop;
char p ='K';
loop = count++;
++a;
a = ++z;
//p--;
++z;
printf("a=%d, z=%d, p=%c",a,z,p--);
printf("count =%d, loop=%d\n", count, loop);
Output:
loop= --count;
loop= loop--;
printf("count =%d, loop=%d\n", count, loop);
Output:
Decision Making : Relational &
Equality Operator
60
Assume :
int y=6, x=5;
Relational Operators
Sample Expression
Value
>
y>x
T (1)
<
y<2
F (0)
>=
x>=3
T (1)
<=
y<=x
F (0)
Equality Operators
Sample Expression
Value
==
x==5
T(1)
!=
y!=6
F(0)
Logical Operators
61
Logical Operators
Called
Sample Operation
&&
AND
expression1 && expression 2
||
OR
expression1 | | expression2
NOT
! expression
Example: NOT (!) operator
int x=50;
Sample
Expression
Expression
!Expression
!(x==60)
0 (False)
1 (True)
!(x!=60)
1 (True)
0 (False)
Logical Operator : AND (&&)
62
Assume:
int x=4, y = 5, z=8;
Expression1
Expression
2
Expression1
&&
Expression2
0 (False)
0 (False)
0 (False)
Sample
Expression
( y > 10) && ( z <
=x )
( z < = y) && ( x =
= 4)
( y ! = z) && ( z < x
)
Logical Operator : AND (&&)
63
Assume:
int x=4, y = 5, z=8;
Expression1
Expression
2
Expression1
&&
Expression2
( y > 10) && ( z <
=x )
0 (False)
0 (False)
0 (False)
( z < = y) && ( x =
= 4)
0 (False)
1 (True)
0 (False)
( y ! = z) && ( z < x
)
1 (True)
0 (False)
0 (False)
Sample
Expression
Logical Operator : OR (||)
64
Assume:
int x = 4, y=5, z=8;
Expression1
Expression
2
Expression1
&&
Expression2
0 (False)
0 (False)
0 (False)
Sample
Expression
( y > 10) || ( z < =x
)
( z < = y) || ( x = =
4)
( y ! = z) || ( z < x )
( z > = y ) || ( x ! =
Logical Operator : OR (||)
65
Assume:
int x = 4, y=5, z=8;
Expression1
Expression
2
Expression1
&&
Expression2
( y > 10) || ( z < =x
)
0 (False)
0 (False)
0 (False)
( z < = y) || ( x = =
4)
0 (False)
1 (True)
1 (True)
( y ! = z) || ( z < x )
1 (True)
0 (False)
1 (True)
( z > = y ) || ( x ! =
1 (True)
1 (True)
1 (True)
Sample
Expression
Operator Precedence
66
Operators
Associative
()
Left to right
++ - - + - !
Right to left
* / %
Left to right
+ -
Left to right
< <= > >=
Left to right
= = !=
Left to right
&&
Left to right
||
Left to right
= *= += - = /= %=
Right to left
Example: Logical Operator
Evaluate the following relational expression. Assume:
int i =5, k = 2, z = 4, c=6;
Expression
Equivalent Expression
Value
i + 2 == k -1
( i + 2) == (k 1)
0 or False
a + 1 == b
(a + 1) == b
1 or True
z % k != c % i
(z % b) != ( c % i)
1 or True
z%c*i
(z % c) * I
k % c * i && i % z * k
((k % c) * i) && (( i % z) * k)
c % i * z >10 || c /k *z < 5
(((c % i )* z) >10) ||( ((c /k)
*z) < 5)
20
1 or True
0 or False
68
Example : Operator
Precedence
Example 1
Example 2
int a=10, b=20, c=15, d=8;
a*b/(-c*31%13)*d
int a=15, b=6, c=5, d=4;
d *= ++b a/3 + c
1. a*b/(-15*31%13)*d
1. d *= ++b a/3+ c
2. a*b/(-15*31%13)*d
2. d*=7- a/3+c
3. a*b/(-465%13)*d
3. d*=7- 5+c
4. a*b/(-10)*d
4. d*=2 + c
5. 200/(-10)*d
5. d*= 7
6. -200*d
6. d = d*7
7. -1600
7. d = 28
Exercises
i)
ii)
iii)
Write a relational expression to express the following condition (use your own
variable name)
A persons height is less than 6 feet
A length is greater than 2 and less equal than 3 feet
A persons is older than 50 or has been employed at the company for at
least 5 years
Write a snippet code that can receive 3 input decimal numbers from user
and prints the average of the numbers.
Assign the sum of value variable marks1 , marks 2, and marks3 to variable
totalMarks
Trace the output of the program:
int mystery = 5;
mystery = 10 -2 % mystery;
++mystery;
printf(%d\n,mystery++);
Exercises (Answer)
i)
ii)
Write a relational expression to express the following condition (use
your own variable name).
A persons height is less than 6 feet > height < 6
A length is greater than 2 feet and less equal than 3 feet > (length >
2) && (length <= 3)
iii)
A persons is older than 50 years or has been employed at the
company for at least 5 years > (age > 50) || (year_employed >= 5)
Write a snippet code that receive 3 input decimal numbers from
user and prints the average of the numbers.
float no1, no2, no3, average;
printf(Enter 3 decimal numbers:);
Scanf(%f %f %f, &no1, &no2, &no3);
average = (no1 + no2 + no3) / 3;
printf(The average is %.2f, average);
Exercises (Answer)
Assign the sum of value variable marks1, marks2, and
marks3 to variable totalMarks.
totalMarks = marks1 + marks2 + marks3;
Trace the output of the program:
int mystery = 5;
mystery = 10 - 2 % mystery;
++mystery;
printf(%d\n,mystery++);
Answer is :
9