Subject : COMP6047
ALGORITHM AND PROGRAMMING
Year : 2019
Introduction to C Programming II
Learning Outcomes
At the end of this session, student will be able to:
• Define element and structure of C programming language (LO1
& LO2)
COMP6047 - Algorithm and Programming 2
Variable
• Identifier for storing data/information
• Each variable has its name, address (L-value), type, size and
data (R-value)
• Data or variable value can be modified at run time
• Declaration format:
<data type> <variable name>;
<data type> <variable name> = <initial value>;
• Example:
int a, b, c, total;
float salary, bonus;
int num_students = 20;
COMP6047 - Algorithm and Programming 3
Variable
• Example:
address
char ch=65 Memory
ch 65 123456
Range of value:
name -128 – 127
value
COMP6047 - Algorithm and Programming 4
Variable
• Variable Declaration:
– Variable can be declared at every statement block
– Block statement or compound statement is statement exists
between { and } sign
– Example:
int x;
int y;
int z;
or:
int x, y, z;
or:
int x; int y; int z;
COMP6047 - Algorithm and Programming 5
Data Type
• In C, there are 5 data types and 4 modifiers
Data types:
– Character char
– Integer int
– Floating point float
– Double floating point double
– Void void
Modifiers:
- signed
- unsigned
- long
- short
COMP6047 - Algorithm and Programming 6
Data Type
• Data type in C is a combination of basic data type and its
modifier
Example:
signed char
unsigned int
long int
etc.
COMP6047 - Algorithm and Programming 7
Data Type
DATA TYPE SYNTAX MEMORY RANGE
character char 1 byte -128 to 127
unsigned char 1 byte
Data type and its range on TURBO C 02.0
to 255
(DOS)
integer int 4 byte –2,147,483,648 to 2,147,483,647
unsigned int 4 byte 0 to 4,294,967,295
short int 2 byte –32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte –2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
long long 8 byte –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
unsigned long long 8 byte 0 to 18,446,744,073,709,551,615
float float 4 byte 3.4E-38 to 3.4E+38
double 8 byte 1.7E-308 to 1.7E+308
long double 8 byte
COMP6047 - Algorithm 1.7E-308 to 1.7E+308
and Programming 8
Data Type
• Why char data range between -128 to 127 ?
• 1 Byte = 8-bit
00000000 to 01111111 (MSB=>0 = Positive value)
MSB = Most Significant Bit (most left)
10000000 to 11111111 (MSB=>1 = Negative value)
-128 -128 32 8 4 2 1
64 16
Total = -128 Total = -1
COMP6047 - Algorithm and Programming 9
Data Type
• Beside used in function identifier type as no return value,
keyword void also used as data type in variable.
• Void data type: is data type that can be transform into any data
type (will be discussed later in pointer)
COMP6047 - Algorithm and Programming 10
Casting
• Casting is a process to convert data type in C
• Syntax : (data type)
• Example :
int x;
float f = 3.134;
x = (int) f;
casting
COMP6047 - Algorithm and Programming 11
Symbolic Constant
• Symbolic constant is an identifier which only have R-Value, and
its value is unchangeable at runtime
• Symbolic constant does not have address (L-Value)
• Symbolic constant declaration does not need memory allocation
• To declare symbolic constant, can be done by using pre-
processor directive #define or keyword const
• Example :
const float Pi=3.14;
#define Pi 3.14
COMP6047 - Algorithm and Programming 12
Symbolic Constant
#define Pi 3.14 int main()
int main() {
{ const float Pi=3.14;
Pi=3.1475; //Error Pi=3.1475; //Error
return 0; return 0;
} }
#define Pi 3.14
int main()
{
float PHI=3.14;
PHI = 3.1475; //OK (variable)
Pi=3.1475; //Error
return 0;
}
COMP6047 - Algorithm and Programming 13
Constant
Constant / symbolic constant does not have address (only value) and its value
can not be changed at run time.
Constant type:
Integer constant -5
Floating-point constant 3.14
Character constant 'C' '1' '$'
Escape sequence \n \t \''
String constant ''BiNus''
⑥ Symbolic constant #define PHI 3.14
const float PHI=3.14;
'H‘ is a character constant
''H'‘ is a string constant
1 is a integer constant
'1‘ is a character constant
const float Pi= 3.1415926; Pi is a symbolic constant
COMP6047 - Algorithm and Programming 14
Program Example
• Addition of two numbers
Data has put on the memory. Result of the addition saved on
the memory (variable)
/* Addition Program */ /*comments */
int x,y,z; /*Global variable*/
int main()
{ /*start main program*/
x = 20; /*Statement 1*/
y = 30; /*Statement 2*/
z = x + y; /*Statement 3*/
return 0; /*Statement 4*/
} /*end of main program*/
COMP6047 - Algorithm and Programming 15
Program Example
• Calculating area of a circle
Radius value input from keyboard. Print out the
result.
/*----------------------------------
Program circle area
----------------------------------*/
#include <stdio.h>
const float Pi = 3.14; /*Constant declaration*/
int main() /*start main program*/
{
float r; /*local variable*/
float area;
scanf(“%f”,&r); /*r input from keyboard*/
area = Pi * r * r;
printf(“ Circle area = %5.2f”, area); /*print out to screen*/
return (0);
} /*end of main program*/
COMP6047 - Algorithm and Programming 16
Sizeof
• sizeof is an operator to find out size of a data
type in C language
• Syntax: sizeof expression
• Example :
sizeof(int) = 4 => Dev-V (Windows)
sizeof(int) = 2 => Turbo C ver 2.0 (DOS)
COMP6047 - Algorithm and Programming 17
Suffix
• C provides suffix for floating point constant:
– F or f for float data type
– L or l for long double data type
– Default double data type
• Example :
– 3.14 (double)
– 3.14f (float)
– 3.14L (long double)
COMP6047 - Algorithm and Programming 18
Suffix
• C provides suffix for a constant integer:
– U or u for unsigned integer
– L or l for long integer
– UL or ul or LU or lu for unsigned long integer
– Default integer
• Example :
– 174 (integer)
– 174u (unsigned integer)
– 174L (long integer)
– 174ul (unsigned long integer)
COMP6047 - Algorithm and Programming 19
Suffix
• Some compilers will give warning for differ in data type, as can be
seen from the following example Visual C++:
• Example :
float x;
x = 3.14;
warning: truncation from 'const double' to 'float’
• How to deal with the issue? You may use casting or suffix
float x;
x = (float)3.14; // casting
x = 3.14f;// or suffix
COMP6047 - Algorithm and Programming 20
Suffix
#include <stdio.h>
int main()
{
printf(“Size of Floating Point Constant :\n");
printf(" – using suffix f = %d\n",sizeof(3.14f));
printf(" – without suffix = %d\n",sizeof(3.14));
printf(" – using suffix L = %d\n",sizeof(3.14L));
getch();
return 0;
}
Output:
Size of Floating Point Constant :
- using suffix f = 4
- without suffix = 8
- using suffix L = 12
COMP6047 - Algorithm and Programming 21
Output Operation
• To show data on the display screen/monitor. Some of standard
library function in C :
printf();
putchar();
puts();
etc.
COMP6047 - Algorithm and Programming 22
Output Operation: printf function
• To display some data on the standard output, using certain
format
• Standard output is the monitor.
• Syntax:
printf(const char *format[,argument, …]);
• Header file : stdio.h
COMP6047 - Algorithm and Programming 23
Output Operation: printf() function
/* A first program in C */
#include <stdio.h>
void main()
{
printf (“Welcome to C!\n”);
}
/*Printing on one line with two printf statements*/
#include <stdio.h>
int main(void){
printf (“Welcome”);
printf (“to C!\n”);
return 0;
}
COMP6047 - Algorithm and Programming 24
Output Formatting
• Output also has formatted specification:
%[flags][width][.precision] type
width : number of columns provided
type :
precision : digit number d –or- i : signed decimal
flags : o : unsigned octal
can be changed into: u : unsigned decimal
none : right justify x : unsigned hexadecimal
- : left justify f : floating point
- + : for positive & negative value e : floating point (exponent)
c : single character
s : string
% : % character
p : pointer
COMP6047 - Algorithm and Programming 25
Output Formatting
• For long data type, add l at the front of data type:
– long double ( “ %lf “)
– unsigned long int ( “ %lu “)
– long int ( “ %ld “)
COMP6047 - Algorithm and Programming 26
Output Example
• Example 1:
printf (“%6d”, 34); ….34
printf (”%-6d”, 34); 34….
• Example 2
printf (“%10s”, “BINUS”); …..BINUS
printf (“%-10s”, “BINUS”); BINUS…..
printf (“%8.2f”, 3.14159 ); ….3.14
printf (“%-8.3f”, 3.14159 ); 3.141…
COMP6047 - Algorithm and Programming 27
Output Example
• Example 3:
printf ("%c\n",65); // print A
printf ("%x\n",'A'); // print 41
printf ("%o\n",65); // print 101
printf ("%+d\n",34); // print +34
printf ("%+d\n",-45); // print -45
printf ("%e\n",3.14); // print 3.140000e+000
COMP6047 - Algorithm and Programming 28
Output Example
• Example 4:
#include <stdio.h>
int main(){
char ss[]="Selamat Datang";
printf("123456789012345678901234567890\n");
printf("%.10s di Binus\n",ss);
printf("%10s di Binus\n",ss);
printf("%-10s di Binus\n",ss);
printf("%.20s di Binus\n",ss);
printf("%20s di Binus\n",ss);
printf("%-20s di Binus\n",ss);
printf("%20.10s di Binus\n",ss);
printf("%-20.10s di Binus\n",ss);
return 0;
}
COMP6047 - Algorithm and Programming 29
Output Example
• Example 4:
Output:
123456789012345678901234567890
Selamat Da di Binus
Selamat Datang di Binus
Selamat Datang di Binus
Selamat Datang di Binus
Selamat Datang di Binus
Selamat Datang di Binus
Selamat Da di Binus
Selamat Da di Binus
COMP6047 - Algorithm and Programming 30
Output Operation: putchar() function
• Syntax:
int putchar(int c)
• Functionality:
– Displaying character on the monitor at cursor position. After
display, cursor will move to the next position
– Return EOF if error, and return the displayed character after
successfully done
– putchar is a macro similar to : putc(c, stdout )
– Header File : stdio.h
• Example :
char ch=’A’;
putchar(ch);
COMP6047 - Algorithm and Programming 31
Output Operation: puts() function
• Syntax:
int puts(const char *str);
• Functionality :
– Display string to the monitor and move the cursor to new line
– Return non-negative value when successful and EOF if error
– Header file: stdio.h
• Example :
puts(”Welcome”);
puts(”to Binus”);
Output on monitor:
Welcome
to Binus
COMP6047 - Algorithm and Programming 32
Input Operation
• Standard library function that is related to input operations are:
scanf();
getchar();
getch();
getche();
gets();
etc.
• Input operation: function/operation of getting the data into the
memory using standard I/O devices (keyboard, disk, etc.)
COMP6047 - Algorithm and Programming 33
Input Operation: scanf() function
• Header file: stdio.h
• Format:
int scanf( const char *format [,argument]... );
• All the argument type are pointers (address of a variable)
• To get the address of a variable use “&” sign
• Example :
int aValue;
scanf(”%d”,&aValue);
• Input format: ”%type”
where type can be substituted with one of the following list:
(next page)
COMP6047 - Algorithm and Programming 34
Input Operation: scanf() function
• Format Type:
Type Used to scan
d integer
u unsigned integer
x hexadecimal
e, f, g floating point
C single character
s string ended with whit space
O data unsigned octal
[…] string ended with non of the value inside [...]
[^..] string ended with the value inside [...]
COMP6047 - Algorithm and Programming 35
Input Operation: scanf() function
• If exist an x integer variable, state the difference of x and &x?
Variable Name Address Value
X 45678 234
Answer:
x : 234
&x : 45678
COMP6047 - Algorithm and Programming 36
Input Operation: scanf() function
• scanf() function returns an integer that stated how many fields
are successfully assigned
• Example :
int x,y,z,w;
x = scanf("%d %d %d",&y,&z,&w);
– Input three values of integer 6 7 8, then x = 3;
– Input four values 6 7 8 9 then x = 3 (successfully assign
3 variables y z w)
COMP6047 - Algorithm and Programming 37
Input Operation: scanf() function
/* Program Calculating rectangle area v1*/
#include <stdio.h>
int main(){
int width, height, area;
scanf(”%d”,&width);
scanf(”%d”,&height);
area = width*height;
return(0);
} scanf()
function
/* Program Calculating rectangle area v2*/ can use
#include <stdio.h>
int main(){ more than
int width, height, area; one
scanf(“%d %d”,&width, &height); argument
area = width * height;
return(0);
}
COMP6047 - Algorithm and Programming 38
Input Operation: scanf() function
/* Program different argument*/
#include <stdio.h>
int main()
{
int number; char initial; float money;
scanf(“%d %c %f” ,&number, &initial, &money);
//other statements
return(0); Data type
} for each
variable in
the function
argument
can be
COMP6047 - Algorithm and Programming
different 39
Input Operation: scanf() function
• Getting string data from keyboard using scanf() using format:
%s
• Example :
char ss[40];
scanf(”%s”, ss);
• Note for the example above, as the ss variable is a pointer than
we need not putting extra & sign (&ss) in the function
argument
(pointer will be discussed later separately)
• String takes only till the first whitespace found
COMP6047 - Algorithm and Programming 40
Input Formatting
• Space char, tab, linefeed, carriage-return, form-feed, vertical-
tab, and new-line entitle ”white-space characters”
• Example :
– Using previous example, if a string “good
morning every one” entered then ss value will
only contain “good”
COMP6047 - Algorithm and Programming 41
Input Formatting & Example
• To get string that ended with certain character for example
Enter, use scanf() with format: [^\n]
• Example 1:
char ss[40];
scanf(”%[^\n]”,ss);
• Using the previous example, if a string “good morning every
one” then ENTER, the ss variable will contain “good morning
every one”
COMP6047 - Algorithm and Programming 42
Input Formatting & Example
• Example 2:
char ss[40];
scanf(”%[a-z]”, ss);
• Using the example above, if the string is:
http://binusmaya.binus.ac.id then ENTER, ss variable will
only contain: http.
This is caused by character (:) is not within a to z, thus (:)
accounted as the end of the string
COMP6047 - Algorithm and Programming 43
Input Formatting & Example
• Example 3 :
int x;
scanf("%o", &x);
• Using the above code, if input value: 44 followed by enter then
x will contain: 36 in decimal, as 44 is an octal number system
COMP6047 - Algorithm and Programming 44
Input Formatting & Example
• Example 4:
int x;
scanf("%x", &x);
• Using the above code, if input value: 44 followed by enter then
x will contain: 68 in decimal, as 44 is a hexadecimal number
system
COMP6047 - Algorithm and Programming 45
Input Operation: getchar() function
• Syntax:
int getchar(void);
• Functionality:
– Return the next ASCII character from keyboard buffer
– Shown on the monitor screen
– Awaiting for ENTER pressed
– Header file: stdio.h
• Example :
char ch;
ch = getchar();
COMP6047 - Algorithm and Programming 46
Input Operation: gets() function
• Syntax:
char *gets(char *buffer)
• Functionality :
– read a string from keyboard till find new-line and save in buffer
– new-line will later on replace with null character
– will return NULL if error and return its argument (buffer) if success
• Example :
char buffer[40];
char *ptr;
ptr = gets(buffer);
COMP6047 - Algorithm and Programming 47
Exercise
1. int x,y,z,w;
x=scanf("%d %d %d",&y,&z,&w);
a. What happen if input was 2 integer values from the keyboard?
b. What is x value if 3 character values given as the input?
2. char ss1[40];
char ss2[40];
x=scanf(”%s %s”,ss1,ss2);
c. What is ss1 and ss2, if the input from keyboard is ”Good morning
everyone” ?
d. What is x if the input : ”Class 1PAT” ?
COMP6047 - Algorithm and Programming 48
Exercise
3. char ss[40];
scanf(”%4s”, ss);
What is ss value, if the input : ”Good morning” ?
4. char ch;
ch = getchar();
What is ch value, if the input : Binus ?
5. char ch1, ch2;
ch1 = getchar(); // input word “Binus” here!
ch2 = getchar();
What is the value of ch1 and ch2, if the input : Binus ?
COMP6047 - Algorithm and Programming 49
Exercise
6. Create a program in C to receive input from standard input
(keyboard) for the following data:
– Assignment Score
– Mid Exam Score
– Final Exam Score
Calculate and display Final Score using :
Final Score = 20%*Assignment + 30%*Mid +
50%*Final
COMP6047 - Algorithm and Programming 50
Exercise
7.
#include <stdio.h>
int main()
{
char name[40];
int nim;
char gender;
printf(“Name:"); scanf("%[^\n]",name);
printf(“StudentNum :"); scanf("%d",&nim);
printf(“Gender (M/F):"); gender=getchar();
return 0;
}
After entering name and student number, program will exit to prompt.
gender=getchar() seems to be never executed. Explain why?
COMP6047 - Algorithm and Programming 51
Exercise
8.
#include <stdio.h>
int main(){
char ss[]="10 % 3 = 1\n";
char str[]=“Welcome to Binus everyone\n";
printf(ss);
printf("%s",ss);
printf(str);
printf("%s",str);
return 0;
}
What is the output of the above code ?
COMP6047 - Algorithm and Programming 52
Summary
• Syntax for Output:
printf, putchar, putch, puts
• Syntax for Input:
scanf, getchar, getch, getche, gets
• The screen (DOS mode) divided into row and column, normally
max column = 80 and max row = 25
COMP6047 - Algorithm and Programming 53
References
• Paul Deitel & Harvey Deitel. (2016). C how to program : with an
introduction to C++. 08. Pearson Education. Hoboken. ISBN:
9780133976892. Chapter 1 ,2, 9
• Writing Your First C Program: http://aelinik.free.fr/c/ch02.htm
• Data Types and Names in C: http://aelinik.free.fr/c/ch04.htm
• Reading from and Writing to Standard I/O:
http://aelinik.free.fr/c/ch05.htm
• Intro to File Input/Output in C:
http://www.cs.bu.edu/teaching/c/file-io/intro/
COMP6047 - Algorithm and Programming 54
END
T0016 - Algorithm and Programming 55