You are on page 1of 61

Pengantar Bahasa C

printf() function
printf() function is used to print the character,
string, float, integer, octal and hexadecimal values
onto the output screen
We use printf() function with %d format specifier to
display the value of an integer variable.
Similarly %c is used to display character, %f for
float variable, %s for string variable, %lf for double
and %x for hexadecimal variable.
To generate a newline,we use \n in C printf()
statement.
case sensitive
2

%d for value of an integer variable


%c for value of a character variable
%f for value of a float variable (flt),
%lf for value of a double variable (dbl),
%s for value of a string variable (str),
%o for a octal value corresponding to integer
variable
%x for a hexadecimal value corresponding to
integer variable
\n for a newline.

int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
4

Output :
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

scanf() function
scanf() function is used to read character, string,
numeric data from keyboard
Consider below example program where user
enters a character. This value is assigned to the
variable ch and then displayed.
Then, user enters a string and this value is
assigned to the variable str and then
displayed.
6

int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

The char Data Type


The char data type holds a single character.
char ch;
Example assignments:
char grade, symbol;
grade = B;
symbol = $;
The char is held as a one-byte integer in memory. The
ASCII code is what is actually stored, so we can use them
as characters or integers, depending on our need.

The char Data Type


Use
scanf (%c, &ch) ;
to read a single character into the variable ch. (Note that
the variable does not have to be called ch.)
Use
printf(%c, ch) ;
to display the value of a character variable.

char Example
#include <stdio.h>
int main ( )
{
char ch ;
printf (Enter a character: ) ;
scanf (%c, &ch) ;
printf (The value of %c is %d.\n, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.

The getchar ( ) Function


The getchar( ) function is found in the stdio library.
The getchar( ) function reads one character from stdin
(the standard input buffer) and returns that characters
ASCII value.
The value can be stored in either a character variable or
an integer variable.

getchar ( ) Example
#include <stdio.h>
int main ( )
{
char ch ; /* int ch would also work! */
printf (Enter a character: ) ;
ch = getchar( ) ;
printf (The value of %c is %d.\n, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.

Problems with Reading


Characters
When getting characters, whether using scanf( ) or
getchar( ), realize that you are reading only one character.
What will the user actually type? The character he/she
wants to enter, followed by pressing ENTER.
So, the user is actually entering two characters, his/her
response and the newline character.
Unless you handle this, the newline character will remain in
the stdin stream causing problems the next time you want to
read a character. Another call to scanf() or getchar( ) will
remove it.

Improved getchar( ) Example


#include <stdio.h>
int main ( )
{
char ch, newline ;
printf (Enter a character: ) ;
ch = getchar( ) ;
newline = getchar( ) ; /* could also use scanf(%c, &newline) ;
printf (The value of %c is %d.\n, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.

*/

LOOPING

16

Flow Diagram of Loop Choice Process

e.g., read the content in a file

e.g., calculate the value of n!

Comparison of Loop Choices (1/2)


Kind
Counting loop

When to Use
We know how many loop
repetitions will be needed
in advance.

C Structure
while, for

SentinelInput of a list of data ended while, for


controlled loop by a special value
EndfileInput of a list of data from
controlled loop a data file

while, for

Comparison of Loop Choices (2/2)


Kind
When to Use
C Structure
Input validation Repeated interactive input do-while
loop
of a value until a desired
value is entered.
General
conditional
loop

Repeated processing of
data until a desired
condition is met.

while, for

FOR

20

Display numbers from 0 to 4:

#include <stdio.h>
int main()
{
const int max = 5;
int i;
for(i = 0; i < max; i++)
printf("%d ",i);
return 0;
}
21

while Loop
Statement is
executed while
condition is true
Note that the
condition must
first be true in
order for the
statement to be
executed even
once

condition

FALSE

TRUE

statement

Repetition Structure
t=0

Often need to repeat an


action or calculation
Ex. Find and print the
distance traveled by an
object dropped from a
height at t = 0 sec each
second over the next 10
seconds

Repetition structures are


often called loops

t=10
A dynamics problem (ME 101)

F ma

1 2
d gt v0t d 0
2

mg
Equation of
motion

Distance Dropped Program Development


Define the problem
Calculate and print the distance traveled each second by
an object dropped from a height in a standard
gravitational field beginning at t = 0 sec over the next
10 seconds
Simplify
1 2
d gt
Assume v0 and d0 are both zero
2

Inputs are there any?


Outputs
time
distance

Solution Algorithm
Start
Pseudocode
1. Start
2. Declare variables: ____
d (distance traveled)
t (time)
(Are these good names?)

3.
4.

Initialize variables
While time is less than or
equal to 10 s
calculate d
print time
print distance
increment time

5.

Stop

while
loop

Flowchart

Declare variables

Initialize variables

t <= 10? T
F

1 2
gt
2

print t, d
t = t +1

Stop

Solution Code

Nested Loops
Nested loops consist of an outer loop with one
or more inner loops.
loops
e.g.,
Outer loop
for (i=1;i<=100;i++){
for(j=1;j<=50;j++){

Inner loop
}
}
The above loop will run for 100*50 iterations.
5-27

Nested loops (loop in loop)


int a,b;
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
printf (*);
}
return 0;
}

*************
*************
*************
*************

28

Nested loops (4)


int a,b;

*************
a ************
***********
**********

for (int i = 0; i < a; i++)


{
for (int j=0; j<b; j++)
{
Printf (*);
}
return 0;
}

29

Nested loops
b

*
**
***
****

int a,b;
for (int i = 0; i < a; i++)
{
for (int j=0; j<b && j <= i; j++)
{
printf (*);
}
return 0;
}
30

Nested loops
int a,i,j;
for (i = 0; i < a; i++) {
for (j=0; j<a; j++) {
if (j < a-i)
printf(" );
else
printf("*);
}
return 0;
}

*
**
***
****
*****
31

Nested loops

*
***
*****
*******
*********
***********

32

#include <stdlib.h>
int main()
{
int i, k, levels, space;
printf("Enter the number of levels in pyramid:");
scanf("%d",&levels);
space = levels;
for ( i = 1 ; i <= levels ; i++ )
{
for ( k = 1 ; k < space ; k++ )
printf(" ");
space--;
for ( k = 1 ; k <= 2*i - 1 ; k++ )
printf("*");
printf("\n");
}
return 0;
}

33

display a pyramid with 10 levels


*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

34

WHILE

35

the number guessing game


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ALLOWED_TIMES 4
int main()
{
int secret, input = 0;
int times = 1;
/* get a random number between 0 and 10 */
srand((unsigned int)time(NULL));
secret = rand() % 10 + 1;
}
36

/* start the game */


printf("--- Demonstrate C while loop statement --- \n\n");
printf("--- Number Guessing Game --- \n");
while(input != secret && times <= ALLOWED_TIMES )
{
printf("Please enter a number (0 - 10):\n");
scanf("%d",&input);
if(input == secret)
printf("Bingo! you got it.\n");
else if(input > secret)
printf("No, it is smaller.\n");
else
printf("No, it is bigger.\n");
times++;
}

37

if(times == ALLOWED_TIMES)
{
printf("You lose! The secret number is %d",secret);
}
return 0;
}

38

selection

39

Selection
if ( age >= 17 )

if ( age >= 17 )

{
printf(Vote!\n) ;

printf(Vote!\n) ;
}

}
else
{
printf(Maybe next time!\n) ;
}

Selection

41

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
printf("Please enter a number:");
scanf ("%d",&x);
if(x > 0){
printf("\nThe number %d is greater than 0",x);
}
return 0;
}

42

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
printf("Please enter a number:");
scanf ("%d",&x);
if(x > 0)
{
printf("\nThe number %d is greater than 0",x);
}
else
{
printf("\nThe number %d is less than or equal zero",x);
}
return 0;
}

43

Nested Selection

44

Compares the input number with zero (0) and displays corresponding message
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
printf("Please enter a number:");
scanf ("%d",&x);
if(x > 0)
{
printf("%d > 0",x);
}
else
if(x < 0)
{
printf("%d < 0",x);
}
else
{
printf("zero");
}
return 0;
}

45

a simple currency conversion program


#include <stdio.h>
/* predefined exchange rates */
#define usd_to_euro 0.77
#define usd_to_aus 0.96
#define usd_to_yen 95.90
#define usd_to_yuan 6.21
#define usd_to_rupee 54.32
int main()
{
float usd_amount; /* USD amount*/
float fc_amount; /* Foreign currency amount*/
float rate;
int currency
46

/* Enter amount in USD */


printf("Please enter USD amount:\n",&usd_amount);
scanf("%f",&usd_amount);
printf("Please choose the currency:\n");
printf("1 - Euro.(%f)\n",usd_to_euro);
printf("2 - Australia Dollar.(%f)\n",usd_to_aus);
printf("3 - Japanese Yen.(%f)\n",usd_to_yen);
printf("4 - Chinese Yuan.(%f)\n",usd_to_yuan);
printf("5 - Indian Rupee.(%f)\n",usd_to_rupee);
printf("6 - Other\n");
scanf("%d",&currency);

47

/* determine the rate */


if(currency == 1)
rate = usd_to_euro;
else if(currency == 2)
rate = usd_to_aus;
else if(currency == 3)
rate = usd_to_yen;
else if(currency == 4)
else if(currency == 5)
rate = usd_to_rupee;
else{
printf("Enter the exchange rate USD -> Foreign Currency\n");
scanf("%f",&rate);
}

48

/* Convert currency */
if(rate > 0){
fc_amount = usd_amount * rate;
}
printf("Result: %.2f",fc_amount);
return 0;
}

49

Multiple Selection
Sometimes it is necessary to branch in more than two
directions.
We do this via multiple selection.

Multiple Selection with if


if (day == 0 ) {
printf (Sunday) ;
}
if (day == 1 ) {
printf (Monday) ;
}
if (day == 2) {
printf (Tuesday) ;
}
if (day == 3) {
printf (Wednesday) ;
}

(continued)
if (day == 4) {
printf (Thursday) ;
}
if (day == 5) {
printf (Friday) ;
}
if (day == 6) {
printf (Saturday) ;
}
if ((day < 0) || (day > 6)) {
printf(Error - invalid day.\n) ;
}

Multiple Selection with if-else


if (day == 0 ) {
printf (Sunday) ;
} else if (day == 1 ) {
printf (Monday) ;
} else if (day == 2) {
printf (Tuesday) ;
} else if (day == 3) {
printf (Wednesday) ;
} else if (day == 4) {
printf (Thursday) ;
} else if (day == 5) {
printf (Friday) ;
} else if (day = 6) {
printf (Saturday) ;
} else {
printf (Error - invalid day.\n) ;
}

This if-else structure is more


efficient than the corresponding if
structure. Why?

Multiple Alternative if Statements


if (score >= 90)
grade = A;
else
if (score >= 80)
grade = B;
else
if (score >= 70)
grade = C;
else
if (score >= 60)
grade = D;
else
grade = F;

if (score >= 90)


grade = A;
else if (score >= 80)
grade = B;
else if (score >= 70)
grade = C;
else if (score >= 60)
grade = D;
else
grade = F;

The switch Multiple-Selection


Structure
switch ( integer expression )
{
case constant1 :
statement(s)
break ;
case constant2 :
statement(s)
break ;

...
default:
statement(s)
break ;
}

switch Statement Details


The last statement of each case in the switch should
almost always be a break.
The break causes program control to jump to the
closing brace of the switch structure.
Without the break, the code flows into the next case.
This is almost never what you want.
A switch statement will compile without a default case,
but always consider using one.

Switch flowchart
entry
Expression?

value1

Statement(s)

value2

Statement(s)

value3

Statement(s)

value4

Statement(s)

Value n

Statement(s)

switch case statement

57

switch ( day )
{
case 0: printf (Sunday\n) ;
break ;
case 1: printf (Monday\n) ;
break ;
case 2: printf (Tuesday\n) ;
break ;
case 3: printf (Wednesday\n) ;
break ;
case 4: printf (Thursday\n) ;
break ;
case 5: printf (Friday\n) ;
break ;
case 6: printf (Saturday\n) ;
break ;
default: printf (Error -- invalid day.\n)
;
break ;
}

switch Example
Is this structure more
efficient than the equivalent
nested if-else structure?

Why Use a switch Statement?


A nested if-else structure is just as efficient as a
switch statement.
However, a switch statement may be easier to
read.
Also, it is easier to add new cases to a switch
statement than to a nested if-else structure.

#include <stdio.h>
int main() {
int color = 1;
printf("Please choose a color(1: red,2: green,3: blue):\n");
scanf("%d", &color);
switch (color) {
case 1:
printf("you chose red color\n");
break;
case 2:
printf("you chose green color\n");
break;
case 3:
printf("you chose blue color\n");
break;
default:
printf("you did not choose any color\n");
}
return 0;
}
60

break and continue Statements


break immediately exits from a continue skips remaining
statements in the body of a
loop
Recall its use in the switch
repetition structure
selection structure
int x;
for(x=1; x<=10; x++)
{
if(x == 5)
break;
printf("%d ", x);
}
printf("Broke out at x
== %d\n",x);
1 2 3 4 Broke out at x == 5

int x, y;
for(x=1; x<=10; x++)
{
if(x == 5)
{
y = x;
continue;
}
printf("%d ", x);
}
printf("Skipped x ==
%d\n",y);

1 2 3 4 6 7 8 9 10 Skipped x
== 5

You might also like