The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

Note and Tutorial C Programming BI v3

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by sekolah-142, 2021-04-09 07:59:47

Module C Programming BI v3

Note and Tutorial C Programming BI v3

Keywords: Module C Programming

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.2.1 “if”, “else” and “nested if” Decision Control Statements in C:

In decision control statements (if-else and nested if), group of statements are executed when condition
is true. If condition is false, then else part statements are executed.

There are 3 types of decision-making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements

Syntax for each C decision control statements are given in below table with description.

Decision control statements Syntax/Description

if Syntax:
if (condition)

{ Statements;}

Description:
In these types of statements, if condition is true, then
respective block of code is executed.

if…else Syntax:
if (condition)

{ Statement1; Statement2;}
else

{ Statement3; Statement4;}

Description:
In these type of statements, group of statements are
executed when condition is true. If condition is false, then
else part statements are executed.

nested if Syntax:
if (condition1)

{Statement1;}
else

if(condition2)
{ Statement2;}

else
Statement 3;

Description:
If condition 1 is false, then condition 2 is checked and
statements are executed if it is true. If condition 2 also gets
failure, then else part is executed.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.2.1.1 Example Program for “if” Statement in C:

In “if” control statement, respective block of code is executed when condition is true.

1 int main ()
2{
3 int m=40, n=40;
4 if (m == n)
5{
6 printf ("m and n are equal");
7}
8}

Output:
m and n are equal

4.2.1.2 Example Program for “if else” Statement in C:

In C if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.

1 #include <stdio.h>
2 int main ()
3{
4 int m=40, n=20;
5 if (m == n)
6{
7 printf ("m and n are equal");
8}
9 else
10 {
11 printf ("m and n are not equal");
12 }
13
14 }

Output:

m and n are not equal

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.2.1.3 Example Program for Nested if Statement in C:

In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
If condition 2 also gets failure, then else part is executed.

1
2 #include <stdio.h>
3 int main ()
4{
5 int m=40, n=20;
6 if (m>n)
7 printf ("m is greater than n");
8 else if(m<n)
9 printf ("m is less than n");
10 else
11 printf ("m is equal to n");
12 }

Output:
m is greater than n

4.2.2 Switch Statement

A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows −

switch(expression)
{

case constant-expression: statement(s);
break; /* optional */

case constant-expression: statement(s);
break; /* optional */

/* you can have any number of case statements */

Default : /* Optional */

statement(s);

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

}
The following rules apply to a switch statement: -
1. The expression used in a switch statement must have an integral or enumerated type, or be of a

class type in which the class has a single conversion function to an integral or enumerated type.
2. You can have any number of case statements within a switch. Each case is followed by the value

to be compared to and a colon.
3. The constant-expression for a case must be the same data type as the variable in the switch, and

it must be a constant or a literal.
4. When the variable being switched on is equal to a case, the statements following that case will

execute until a break statement is reached.
5. When a break statement is reached, the switch terminates, and the flow of control jumps to the

next line following the switch statement.
6. Not every case needs to contain a break. If no break appears, the flow of control will fall through

to subsequent cases until a break is reached.

7. A switch statement can have an optional default case, which must appear at the end of the

switch. The default case can be used for performing a task when none of the cases is true. No

break is needed in the default case.

Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Example
#include <stdio.h>

int main ()
{

/* local variable definition */
char grade = 'B';

switch(grade) printf ("Excellent! \n”); break;
{ printf ("Well done\n”); break;
printf ("You passed\n”); break;
case 'A’: printf ("Better try again\n”); break;
case 'B’: case 'C’: printf ("Invalid grade\n”);
case 'D’:
case 'F’:
default:
}

printf ("Your grade is %c\n", grade);

return 0;
}

When the above code is compiled and executed, it produces the following result −

Well done
Your grade is B

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.2.3 Tutorial 4: Control /Conditional Statements
*Save as in C:\Librararies\Documents\Programming C\Tutorial4\

1. if statement

//if statement

#include<stdio.h>
void main ()
{

int num;

printf ("Enter a number from 1-20: ");
scanf ("%d”, &num);

if((num>=1) &&(num<=10))
printf ("%d is less than or equal to 10.\n”, num);

if((num>10) &&(num<=20))
printf ("%d greater than or equal to 20.\n", num);

if(num>20)
printf ("Out of Range.");

}

2. if selection strucutre

//if selection structure

#include<stdio.h>
void main ()
{

float nom1, nom2;

printf ("PLEASE INPUT 2 NUMBER.\n");
printf ("First Number: ");
scanf ("%f", &nom1);

printf ("Second Number: ");
scanf ("%f", &nom2);

if(nom1==nom2)
printf ("\n%.1f is equal to %.1f", nom1, nom2);

if (nom1! =nom2)
printf ("\n%.1f is not equal to %.1f", nom1, nom2);

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

if(nom1<nom2)
printf ("\n%.1f is less than %.1f", nom1, nom2);

if(nom1<=nom2)
printf ("\n%.1f is less than or equal to %.1f", nom1, nom2);

if(nom1>nom2)
printf ("\n%.1f is greater than %.1f", nom1, nom2);

if(nom1>=nom2)
printf ("\n%.1f is greater than or equal to %.1f", nom1, nom2);

}

3. if …. else statement
// if...else statement

#include<stdio.h>
void main ()
{

int num;

printf ("Enter a number from 1-20: ");
scanf ("%d”, &num);

if(num<=10)
printf ("%d less than or equal to 10.\n”, num);

else
printf ("%d greater than or equal to 20.\n", num);

}

4. Nested if statement

#include<stdio.h>

int main ()
{

float fuel;

printf ("Enter fuel");
scanf (“%f", &fuel);

printf (" First with braces");

if (fuel < 0.75)
{

if (fuel < 0.25)

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

printf ("fuel very low. Caution! \n");
}
else

{
printf ("fuel over ¾ don't stop now! \n");

}

printf ("Without braces:\n");

if (fuel < 0.75)
if (fuel < 0.25)
printf ("fuel very low. Caution! \n");

else

printf ("fuel over ¾ don't stop now! \n");

return 0;
}

5. if…. else statement

#include <stdio.h>

void main ()
{
int j;
char i;

printf (“Enter 1 character or number");
scanf ("%c", &i);

if (i== 0)
printf (“1 is true");

else
if((i=='a'||i=='b’) &&(i=='b'||i=='a'))
printf ("a or b");

}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

6. Odd or even numbers

//odd or even numbers

#include<stdio.h>

void main ()
{

int number;
int num;

printf ("please enter a number from 1-10: ");
scanf ("%d”, &number);

num= number %2;

if (num == 1)
printf ("%d, is an odd number.\n”, number);

else
printf ("%d, is an even number.\n”, number);

}

7. This program to recognize odd or even number

/*this program to recognise odd or even number*/

#include <stdio.h>
void main ()
{ int num, number;

printf ("enter a number from 1-10:");
scanf ("%d”, &num);

if (num > 10)
printf ("out of range\n");

else
{

number = num % 2;

if(number==1)
printf ("%d an odd number.\n”, num);

else
printf ("%d an even number.\n”, num);

}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

8. Nested if …else if statments

//nested if...else if statements

#include<stdio.h>

void main ()
{

int num, balance;

printf ("Enter a number from 1-20: ");
scanf ("%d”, &num);

if(num<=10)
{ printf ("%d less than or equal to 10.\n”, num);

balance = num % 2;
{

if(balance==1)
printf ("%d is an odd number", num);

else
printf ("%d is an even number", num);

}
}
else if(num<=20)
{

printf ("%d smaller than or equal to 20.\n", num);
balance = num % 2;
{

if(balance==1)
printf ("%d is an odd number", num);

else
printf ("%d is an even number", num);

}
}
else

printf ("Out of range.");
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

9. switch …case statement

/*swicth...Case Statement */

#include<stdio.h>

void main ()
{

char greeting;

printf ("\nA. Selamat Hari Raya\nB. Happy Deepavali \nC. Kong Xi Fa Choi \n");
printf ("Enter the number of your desired greeting: ");
scanf ("%c", &greeting);

switch (greeting)
{

case 'A': case 'a':
printf ("Selamat Hari Raya\n");
break;

case 'B': case 'b':
printf ("Happy Deepavali\n");
break;

case 'C': case 'c':
printf ("Kong Xi Fa Choi\n");
break;

default: printf ("Error number of greeting");
break;

}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.3 Repetition / Looping

You may encounter situations, when a block of code needs to be executed several number of
times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming languages −

C programming language provides the following types of loops to handle looping requirements.

No Loop Type & Description
while loop

1 Repeats a statement or group of statements while a given condition is true. It tests the

condition before executing the loop body.
for loop

2 Executes a sequence of statements multiple times and abbreviates the code that manages

the loop variable.
do...while loop
3 It is more like a while statement, except that it tests the condition at the end of the loop

body.
4 nested loops

You can use one or more loops inside any other while, for, or do..while loop.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021
3.4.1 while loop

A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in C programming language is –

While (condition)
{

Statement(s);
}

Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any nonzero value.
The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately
following the loop.
Flow Diagram

Here, the key point to note is that a while loop might not execute at all.
When the condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Example

#include<stdio.h>

int main ()
{

/*local variable definition*/
int a= 10;

/*while loop execution*/
While(a<20)
{

printf (“Value of a: %d\n”, a);
a++;
}
return 0;
}

When the above code is compiled and executed, it produces the following result –

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.3.1 for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is –

for (initialize; condition; increment/decrement)
{

Statement(s);
}

Here is the flow of control in a 'for' loop −
The initalize step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just
after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the 'for' loop terminates.
Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Example

#include<stdio.h>

int main ()
{

/*local variable definition*/
int a= 10;

/*for loop execution*/
for (a = 10; a < 20; a ++)
{

printf (“Value of a: %d\n”, a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result –

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021
4.3.2 do...while loop

Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax
The syntax of a do...while loop in C programming language is –

do
{

Statement(s);
} while (condition);

Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop executes again. This process repeats until the given condition becomes false.
Flow Diagram

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Example

#include<stdio.h>

int main ()
{

/*local variable definition*/
int a= 10;

/*for loop execution*/
do
{

printf (“Value of a:%d\n”,a);
a = a + 1;
} while (a < 20)

return 0;
}

When the above code is compiled and executed, it produces the following result −

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.3.3 nested loop

C programming allows using one loop inside another loop. The following section shows a few
examples to illustrate the concept.

4.3.4.1 Nested for loop

The syntax for a nested for loop statement in C is as follows –

for (initialize; condition; increment)
{

for (initialize; condition; increment)
{

Statement(s);
}
Statement(s);
}

C program to print patterns of numbers and stars

These program prints various different patterns of numbers and stars.
These codes illustrate how to create various patterns using c programming.
Most of these c programs involve usage of nested loops and space.
A pattern of numbers, star or characters is a way of arranging these in some logical
manner or they may form a sequence.
Some of these patterns are triangles which have special importance in mathematics.
Some patterns are symmetrical while other is not.
Please see the complete page and look at comments for many different patterns.

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

We have shown five rows above, in the program you will be asked to enter the numbers
of rows you want to print in the pyramid of stars.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

C programming code

#include <stdio.h>

int main ()
{

int row, c, n, temp;

printf ("Enter the number of rows in pyramid of stars you wish to see ");
scanf ("%d”, &n);

temp = n;

for (row = 1; row <= n; row++)
{

for (c = 1; c < temp; c++)
printf (" ");

temp--;

for (c = 1; c <= 2*row - 1; c++)
printf ("*");

printf("\n");
}

return 0;
}

For more patterns or shapes on numbers and characters see comments below and also
see codes on following pages:

Floyd triangle
Pascal triangle

Consider the pattern
*
**
***
****
*****

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

to print above pattern, see the code below:

#include <stdio.h>

int main ()
{

int n, c, k;

printf ("Enter number of rows\n");
scanf ("%d”, &n);

for (c = 1; c <= n; c++)
{

for (k = 1; k <= c; k++)
printf ("*");

printf("\n");
}

return 0;
}

Using these examples, you are in a better position to create your desired pattern for
yourself.
Creating a pattern involves how to use nested loops properly; some pattern may involve
alphabets or other special characters.
Key aspect is knowing how the characters in pattern changes.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

C pattern programs
Pattern:

*
*A*
*A*A*
*A*A*A*

C pattern program of stars and alphabets:

#include<stdio.h>

main ()
{

int n, c, k, space, count = 1;

printf ("Enter number of rows\n");
scanf ("%d”, &n);

space = n;

for (c = 1; c <= n; c++)
{

for (k = 1; k < space; k++)
printf (" ");

for (k = 1; k <= c; k++)
{

printf ("*");

if (c > 1 && count < c)
{

printf("A");
count++;
}
}

printf("\n");
space--;
count = 1;
}
return 0;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

C program: Pattern: © Nar | Nisrin Ahmad Ramly \(^o^)/
1
232

34543
4567654
567898765

#include<stdio.h>
main ()
{

int n, c, d, num = 1, space;

scanf ("%d”, &n);

space = n - 1;

for (d = 1; d <= n; d++)
{

num = d;

for (c = 1; c <= space; c++)
printf(" ");

space--;

for (c = 1; c <= d; c++)
{

printf ("%d", num);
num++;
}
num--;
num--;
for (c = 1; c < d; c++)
{
printf ("%d", num);
num--;
}
printf("\n");

}
return 0;
}

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.3.4.2 Nested while loop

The syntax for a nested while loop statement in C programming language is as follows –

while (condition)
{

While(condition)
{

Statement(s);
}
Statement(s);
}

Flowchart of Nested while loop

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Example of Nested while loop
C program to print the number pattern.

1
12
123
1234
12345

#include <stdio.h>
int main ()
{

int i=1, j;
while (i <= 5)
{

j=1;
while (j <= i)
{

printf ("%d “, j);
j++;
}
printf("\n");
i++;
}
return 0;
}

In this program, nested while loop is used to print the pattern.
The outermost loop runs 5 times and for every loop, the innermost loop runs i times which is 1
at first, meaning only "1" is printed, then on the next loop it's 2 numbers printing "1 2" and so
on till 5 iterations of the loop executes, printing "1 2 3 4 5".
This way, the given number pattern is printed.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.3.4.2 Nested do...while loop

The syntax for a nested do...while loop statement in C programming language is as follows –

do
{

do
{

Statement(s);
} while (condition);

Statement(s);
} while(condition);
Example of Nested do-while loop

C program to print the given star pattern.

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

#include <stdio.h>
int main ()
{

int i=1, j;
do
{

j=1;
do
{

printf ("*");
j++;
} while (j <= i);
i++;
printf("\n");
} while (i <= 5);
return 0;
}

In this program, nested do-while loop is used to print the star pattern.
The outermost loop runs 5 times and for every loop, the innermost loop runs i times which is 1
at first, meaning only one "*" is printed, then on the next loop it's 2 printing two stars and so on
till 5 iterations of the loop executes, printing five stars.
This way, the given star pattern is printed.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a 'for' loop can be inside a 'while' loop or vice versa.

4.3.5 Tutorial 5: Repetition/Loop Statements
*Save as in C:\Librararies\Documents\Programming C\Tutorial5\

1. for loop to sum until input number given

#include <stdio.h>
void main ()
{

int i, x, sum = 0;

printf ("Enter number:");
scanf ("%d”, &x);

for (i=5; i<=x; i=i+5)
{

printf (" i = %d", i);
sum += i;
printf ("**%d “, sum);
}

printf ("Sum of the number: %d “, sum);

}

2. for loop to find out the average of sum number until number given by user

#include <stdio.h>
void main ()
{

int i, x, sum = 0, no = 0;
float average = 0;

printf ("Enter number:");
scanf ("%d”, &x);

for (i=5; i<=x; i=i+5)
{

//printf (" i = %d", i);

sum += i;

// printf ("**%d “, sum);

no++;

}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

//printf ("no = %d”, no);

average = sum / no;

printf ("\n Average: %.2f “, average);

}

3. while loop for find out factorial number input by user

#include <stdio.h>
void main ()
{

int i, x;
long factor;

printf ("Enter number:");
scanf ("%d”, &x);
i=x;
factor =x;
while (i! = 1)
{

i= i - 1;
printf (" i = %d", i);
factor = factor * i;
printf ("**%ld “, factor);

}

printf ("\nfactorial = %ld”, factor);
}

4. for loop to find out factorial that given number

#include <stdio.h>
int main ()
{

int c, n, fact = 1;

printf ("Enter a number to calculate it's factorial\n");
scanf ("%d", &n);

for (c = 1; c <= n; c++)
fact = fact * c;

printf ("Factorial of %d = %d\n", n, fact);

return 0;

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

}

5. for loop to find greater number between four numbers given by user

#include <stdio.h>
void main ()
{

int i, no, greater = 0;

for (i=1; i<=4; i++)
{

printf ("Enter number %d:”, i);
scanf ("%d”, &no);

if (greater < no)
greater = no;

else
continue;

}
printf (" The greater number = %d”, greater);

}

6. for loop to timetable multiplication

// for statement

#include<stdio.h>
void main ()
{

int counter, sum, timetable, multiplication;

printf ("What timetable do you want? ");
scanf ("%d", &timetable);
printf ("Please enter amount multiplication you want? ");
scanf ("%d", &multiplication);

for (counter = 1; counter<=multiplication; counter++)
{

sum = counter * timetable;
printf ("%d x %d = %d\n”, counter, timetable, sum);
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

7. nested for to calculate averages for several different lists of numbers

// nested for
// calculate averages for several different lists of numbers

#include<stdio.h>
void main ()
{

int n, count, loops, loopcount;
float x, average, sum;

//read in the number of lists
printf ("How many lists? ");
scanf ("%d", &loops);

//outer loop (process each list of numbers
for (loopcount = 1; loopcount<=loops; ++loopcount)
{

//initialize and read in a value for n
sum=0;

printf ("\nList number %d\nHow many numbers? ", loopcount);
scanf ("%d", &n);

//read in the numbers
for (count=1; count<=n; ++count)
{

printf ("x = ");
scanf ("%f", &x);
sum += x;
}//end inner loop

//calculate the average and display the answer
average = sum/n;

printf ("\nThe average is %f \n", average);
}//end outer loop

}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

8. nested for #include<stdio.h>
9. while loop void main ()
10. while loop {

int i, j;
for (i=1; i<=4; i++)
{

for (j=1; j<=4; j++)
printf ("%c", '*');

printf("\n");
}

}

// while

#include<stdio.h>
void main ()
{

int x=1;

while(x<5)
{ printf (" %d ", x);

x++;
}
}

// while

#include<stdio.h>
void main ()
{

int counter=1, sum, timetable, multiplication;

printf ("What timetable do you want? ");
scanf ("%d", &timetable);
printf ("Please enter amount multiplication you want? ");
scanf ("%d", &multiplication);

while(counter<=multiplication)
{

sum = counter * timetable;
printf ("%d x %d = %d\n”, counter, timetable, sum);
counter++;
}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.4 Jumping Statement

What are jumping statements?

C language provides us multiple statements through which we can transfer the control
anywhere in the program.
There are basically 3 Jumping statements:

1. break jumping statements.
2. continue jumping statements.
3. goto jumping statements.

1. break jumping statements.

By using this jumping statement, we can terminate the further execution of the program and
transfer the control to the end of any immediate loop.
To do all this we have to specify a break jumping statements whenever we want to terminate
from the loop.
Syntax: break;

NOTE: This jumping statement always used with the control structure like switch case, while, do while,
for loop etc.

NOTE: As break jumping statements ends/terminate loop of one level. so, it is refered to use return or
goto jumping statements, during more deeply nested loops.

Example: Program based upon break jumping statements:
WAP to display the following output:
1 2 3 4 5. . . . .

#include<stdio.h>
#include<conio.h>
void main ()
{

int i=1;
for (i=1; i<=10; i++)
{

printf (“Enter”, i,”no”);
printf (“\t %d”, i);

if(i>5)
break;

}
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

2. continue jumping statements.

By using this jumping statement, we can terminate the further execution of the program and
transfer the control to the begining of any immediate loop.
To do all this we have to specify a continue jumping statements whenever we want to terminate
terminate any particular condition and restart/continue our execution.
Syntax: continue;

NOTE: This jumping statement always used with the control structure like switch case, while, do while,
for loop etc.

Example: Program based upon continue jumping statements:
WAP to display the following output:

1 2 3 4 . 6 7 . 9 10

#include<stdio.h>
#include<conio.h>
void main ()
{

int i=1;
for (i=1; i<=10; i++)
{

printf (“Enter”, i,”no”);
printf (“\t %d”, i);
if (i==5 || i==8)

continue;
}
}

3. goto jumping statements.

By using this jumping statement, we can transfer the control from current location to anywhere
in the program.
To do all this we have to specify a label with goto and the controlwill transfer to the location
where the label is specified.
Syntax: goto <label>;

NOTE:
The control will transfer to those label that are part of particular function, where goto is specified.
All those labels will not be included, that are not the part of a particular function where the goto is
specified.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

NOTE:
It is good programming style to use the break, continue and return instead of goto.
However, the break may execute from single loop and goto executes from more deeper loops.

Example: Program based upon continue jumping statements:

WAP to display the square root of a no, if no. is not positive then re enter the input.

#include<stdio.h>
#include<conio.h>

void main ()
{

int i, n;
float s;

start:

printf (“Enter a no.”);
scanf (“%d”, &n);

s=sqrt(n);

if(n<=0)
goto start;

printf (“%f”, s);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.5 Tutorial 6: Algorithm

*Save as in C:\Librararies\Documents\Programming C\Tutorial6\

4.5.1 Pengenalan

Tutorila ini bertujuan memberikan pengetahuan tentang pembinaan penyelesaian (developing
solution) dan mendokumenkannya dalam bentuk carta alir atau pseudocode.
Dalam tutorial ini, anda diberikan beberapa contoh jawapan sebagai panduan.
Sila fahamkan contoh-contoh tersebut sebelum mencuba soalan-soalan berilkutnya.
Tips: Untuk menyemak sama ada carta alir atau pseudocode yang anda hasilkan adalah betul,
caranya adalah dengan menjejak (trace) carta alir atau pseudocode tersebut.
4.5.2 Objektif

Selepas membuat tutorial ini anda sepatutnya boleh
1. Membina carta alir atau menulis pseudocode bagi sesuatu masalah
2. Menggunakan struktur-struktur kawalan iaitu sequential, selection dan repetition

4.5.3 Bahagian 1: Sequential Structure

Contoh 1
Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah dua nombor.

Jawapan:
Sebelum membuat carta alir / pseudocode, kenalpasti input, ouput dan proses (formula) terlebih
dahulu.

Langkah 1:

Input : Dua nombor, A dan B
Output : Hasil tambah dua nombor tersebut
Proses : Rumus yang digunakan: Hasil Tambah = A + B

Langkah 2:

Pseudocode
1. Start Program
2. Enter two numbers, A, B
3. Add the numbers together
4. Print Sum
5. End Program

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Flowchart

Start

Declare variables A, B and sum
Read A and B

sum = A + B
Display sum

Stop

Soalan
1. Tulis pseudocode dan bina sebuah carta alir untuk mengira isipadu sebuah bongkah. Kemudian, tulis

dalam C.

2. Tulis pseudocode dan bina sebuah carta alir untuk mengira Jumlah Pinjaman dan Ansuran Bulanan
(montly payment) bagi pinjamanan kenderaan. Kadar Bunga (interest rate) adalah 4% setahun.
Kemudian, tulis dalam C.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4.5.4 Bahagian 2: Selection Structure

Contoh 2
Tulis pseudocode dan bina sebuah carta alir untuk menentukan sama ada suatu nobor itu genap atau
ganjil.

Jawapan:

Langkah 1:

Input : Satu nombor, Num
Output : Genap atau Ganjil
Proses : Gunakan modulus (bahagi baki). Pengujian untuk nombor genap: Num modulus 2 = 0.

Langkah 2:

Pseudocode
1. Mula Program
2. Baca Num
3. Pengujian untuk nombor genap: Num modulus 2 = 0
3.1 Jika benar: papar Num adalah nombor genap
3.2 Jika tidak benar: papar Num adalah nombor ganjil
4. Tamat Program

Flowchart

Start

Read Num Yes
Print “it’s an even number”
Is Num modulus 2 = 0
No

Print “it’s an odd number”

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Soalan

3. Tulis pseudocode dan bina carta alir untuk menentukan nombor terbesar daripada dua nombor.

4. Tulis pseudocode dan bina carta alir untuk menentukan sama ada suatu nombor itu merupakan
gandaan 3 atau gandaan 5 atau kedua-duanya.

5. Tulis pseudocode dan bina carta alir untuk mengira Ansuran Bulanan (monthly payment) bagi
pinjaman kenderaan. Jumlah pinjaman dan tahun pinjaman adalah maklumat daripada pengguna.
Kadar pinjaman adalah bergantung kepada bilangan tahun pinjaman, seperti berikut:

Bil Tahun Kadar Bunga
Kurang daripada 5 tahun 2.5% setahun
5 tahun atau lebih 3.0% setahun

6. Sebuah bank menyediakan perkhidmatan pinjaman peribadi (personal loan). Syarat-syarat
permohonan dan pinjaman adalah seperti berikut:

Kadar Bunga Kadar Bunga (%) setahun
Bil Tahun
3.0
1 -2 5.0
3 -5 7.0
6 – 10

Pinjaman Maksimum:
RM 50,000.00

Pinjaman Maksimum:
Gaji Kasar Pemohon mestilah 3 kali ganda lebih besar daripada Ansuran Bulanan
(monthly payment).

Berdasarkan spesifikasi di atas, bina sebuah carta alir untuk membantu pihak bank tersebut bagi
membuat keputusan sama ada meluluskan atau menolak sesuatu permohonan.

4.5.5 Bahagian 3: Repeatition Structure

Contoh 3

Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah semua nombor daripada 1
hingga n. (anggap n >0)

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Jawapan: Yes

Langkah 1:

Input : Nombor n
Output : Hasil tambah nombor-nombor 1 hingga n
Proses : Jumlahkan semua nombor: 1 + 2 + 3 + …. + (n-1) + n

Langkah 2: Flowchart
Pseudocode

1. Mula Program Start
2. Baca n

3. Nilai awalan sum = 0 dan i = 0

4. Mula gelung

4.1 sum tambah dengan nilai i Read n

4.2 tambah nilai i dengan 1

5. Pengujian i sama ada kurang atau sama dengan nilai n

5.1 Jika benar, teruskan gelung Initialize
5.2 Jika tidak, gelung tamat sum = 0
6. Papar hasil tambah nombor 1 hingga n
7. Tamat Program i=0

sum = sum + 1
i++

is i less than or
equal to n?
No
Print sum

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Contoh 4
Tulis pseudocode dan bina sebuah carta alir untuk bilangan nombor ganjil daripada 1 hingga n. (yang
mana, n > 0)

Jawapan:

Langkah 1:

Input : Nombor n
Output : Bilangan nombor ganjil
Proses : Kira bilangannombor ganjil sahaja. Pengujian untuk nombor ganjl: N modulus 2 =1

Langkah 2: Flowchart
Pseudocode

1. Mula Program Start
2. Baca n
3. Mula gelung Read n

3.2 Nilai awalan Oddcount = 0 dan i = 1 Initialize
3.2 Pengujian i sama ada nombor ganjil sum = 0

3.2.1 Jika benar, Oddcount tambah 1 i=0
dan i tambah dengan 1
is modulus 2 =1?
3.2.2 Jika tidak, i tambah dengan 1
4. Pengujian i sama ada kurang atau sama dengan nilai n

4.1 Jika benar, teruskan gelung
4.2 Jika tidak, gelung tamat
5. Papar Oddcount
6. Tamat Program

No Yes

Oddcount = Oddcount + 1 Yes

i++

is i less than or equal to
n?

No
Print

Stop

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

Soalan

7. Tulis pseudocode dan bina carta alir untuk mengira hasil tambah semua nombor gandaan 5 daripada
5 hingga n.

Contoh: 5 + 10 +15 + 20……

8. Tulis pseudocode dan bina carta alir untuk mengira purata nombor-nombor gandaan 5 daripada 5
hingga n.

Contoh:
Katakan n =15,
Purata = (5 + 10 + 15)/3 =10

9. Tulis pseudocode dan bina carta alir untuk mengira factorial bagi suatu nombor n. Rumus factorial
adalah seperti berikut:

n! = n x (n-1) x …………x 2 x 1

Contoh:
Katakan n = 5
5! = 5 x 4 x 3 x 2 x 1 = 120

8. Tulis pseudocode dan bina carta alir yang dapat menentukan nombor terbesar daripada n bilangan
nombor yang dimasukkan oleh penggguna.

Contoh:
Katakan pengguna memasukkan bilangan nombor, n = 4. Selepas itu, pengguna memasukkan 4
nombor tersebut, katakan 10,20,10 dan 40. Jadi nombor terbesar adalah 40.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5. Functions

5.1 Type of Function

A function is a block of code that performs a particular task.
There are times when we need to write a particular block of code for more than once in our
program. This may lead to bugs and irritation for the programmer.
C language provides an approach in which you need to declare and define a group of statements
once and that can be called and used whenever required.
This saves both time and space.
C functions can be classified into two categories,

 Library functions
 User-defined functions

Library functions are those functions which are defined by C library, example printf (), scanf
(), strcat () etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.
User-defined functions are those functions which are defined by the user at the time of
writing program. Functions are made for code reusability and for saving time and space.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5.2 Benefits of Using Functions

1. It provides modularity to the program.
2. Easy code Reusability. You just have to call the function by its name to use it.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier if you

use functions.

5.3 Function declaration / Function Prototypes

General syntax of function declaration is,
return-type function-name (parameter-list);

Like variable and an array, a function must also be declared before it called.
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately. A function declaration consists of 4
parts.

 return-type
 function name
 parameter list
 terminating semicolon

5.4 Function definition Syntax

General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body;
}

The first line return-type function-name(parameter) is known as function header and the statement
within curly braces is called function body.

5.4.1 return-type

return type specifies the type of value (int, float, char, double) that function is expected to return to the
program calling the function.

5.4.2 function-name

function name specifies the name of the function. The function name is any valid C identifier and
therefore must follow the same rule of formation as other variables in C.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5.4.3 parameter-list

The parameter list declares the variables that will receive the data sent by calling program. They often
referred to as formal parameters. These parameters are also used to send values to calling program.

5.4.4 function-body

The function body contains the declarations and the statement(algorithm) necessary for performing the
required task. The body is enclosed within curly braces { } and consists of three parts.

 local variable declaration.
 function statement that performs the tasks of the function.
 a return statement that return the value evaluated by the function.

5.5 Functions and Arguments

Arguments are the values specified during the function call, for which the formal parameters are
declared in the function.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5.5.1 Example: Function that return some value

#include<stdio.h>
#include<conio.h>
int larger (int a, int b); // function declaration

void main ()
{

int i, j, k;
clrscr ();
i=99;
j=112;
k=larger (i, j); // function call
printf ("%d”, k);
getch ();
}

int larger (int a, int b) // function declaration
{

if(a>b)
return a;
else
return b;
}

5.5.2 Nesting of Functions

C language also allows nesting of functions, one function using another function inside its body. We
must be careful while using nested functions, because it may lead to infinte nesting.

function1()
{

function2();
//statements
}
If function2 calls function1 inside it, then in this case it will lead to infinite nesting, they will keep calling
each other. Hence, we must be careful.

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5.5.3 Recursion

Recursion is a special of nesting functions, where a function calls itself inside it. We must have certain
condition to break out of the recursion, otherwise recursion is infinite.

function1()

{

function1();

//statements

}

5.5.3.1 Example: Factorial of a number using Recursion

#include<stdio.h>
#include<conio.h>
int factorial (int x);

void main ()
{

int a, b;
clrscr ();
printf ("Enter no.");
scanf ("%d”, &a);
b=factorial(a);
printf ("%d”, b);
getch ();
}
int factorial (int x)
{
int r=1;
if(x==1) return 1;
else r=x*factorial(x-1);
return r;
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

5.6 Tutorial 7: Function

*Save as in C:\Librararies\Documents\Programming C\Tutorial7\

1. Exercise 1
a) Tulis satu aturcara untuk melakukan pengiraan terhadap 2 nombor menggunakan operasi tolak,

darab dan bahagi dan mencetak hasil bagi setiap operasi tersebut.
b) Kita akan menggunakan pendekatan aturcara bermodul (pecahkan kepada bbrp. modul).

Modul
Utama

Operasi Operasi Operasi
Tolak Darab Bahagi

Modul 1 Modul 2 Modul 3
Fungsi main ()
//Penggunaan fungsi tanpa parameter
#include<stdio.h>

void fungsi_tolak( ); //prototaip fungsi
void fungsi_darab( ); //prototaip fungsi
void fungsi_bahagi( ); // prototaip fungsi

int x, y;

void main( )
{

x=10;
y=20;

fungsi_tolak( );
fungsi_darab( );
fungsi_bahagi( );
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

//takrif fungsi tolak
void fungsi_tolak( )
{ int f1;

f1=y-x;

printf(“\nHasil tolak %d - %d ialah %d”, y,x,f1);
}

//takrif fungsi darab
void fungsi_darab ( )
{ int f2;

f2=y*x;

printf(“\nHasil darab %d x %d ialah %d”, y,x,f2);
}

//takrif fungsi bahagi
void fungsi_bahagi ( )
{ int f3;

f3=y/x;

printf(“\nHasil darab %d / %d ialah %d”, y,x,f3);
}

2. // Aturcara dgn 2 pembolehubah setempat berbeza tetapi mempunyai nama sama.

#include<stdio.h>

void main( )
{

int baca_umur( );
int umur;

printf(“Berapa umur anda ?”);
scanf(“%d”,&umur);

printf(“\nPembolehubah umur dlm FUNGSI MAIN( ) ialah %3d”, umur);
baca_umur( );
printf(“\nPemblehubah umur dlm FUNGSI MAIN( ) masih %3d\n”,umur);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

int baca_umur( )
{

int umur;

printf(“\nTaipkan semula umur anda : “);
scanf(“%d”, &umur);

printf(“\nPembolehubah umur dalam FUNGSI BACA_UMUR( ) ialah %d”, umur);
return 0;
}

3. /* Penggunaan fungsi (dengan parameter)--- fungsi ialah satu bahagian aturcara untuk melakukan
sesuatu tugas tertentu yang ditulis secara berasingan */

#include<stdio.h>
void cari_gred(int);

void main( )
{

int markah;

printf(“Masukkan markah : ” );
scanf(“%d”, &markah);

cari_gred(markah);
}

void cari_gred (int markah)
{

char gred;

if (markah >= 80)
gred = ‘A’;

else
if (markah >=70)
gred=’B’;
else
if (markah >=60)
gred=’C’;
else
if (markah >=50)
gred=’D’;
else
gred=’E’;

printf(“Anda dapat gred %c” , gred);
}

© Nar | Nisrin Ahmad Ramly \(^o^)/

2nd Semester: Programming (C Language) – 3rd Edition 2021

4. // fungsi dengan parameter

#include<stdio.h>

char cari_gred(int); //prototaip fungsi

void main( )
{

int markah;

printf(“Masukkan markah :”);
scanf(“%d”, &markah);

printf(“Anda dapat gred %c”, cari_gred(markah)); //panggilan fungsi
}

char cari_gred(int markah)
{

char gred;

if (markah >= 80)
gred = ‘A’;

else
if (markah >=70)
gred=’B’;
else
if (markah >=60)
gred=’C’;
else
if (markah >=50)
gred=’D’;
else
gred=’E’;

return gred;
}

5. Operation subtraction, multiply and division 2 numbers that give by user
// Functions

#include<stdio.h>

int func_subtraction(int a, int b); //function prototype
int func_multiplication(int a, int b); //function prototype
float func_division(int a, int b); //function prototype

© Nar | Nisrin Ahmad Ramly \(^o^)/


Click to View FlipBook Version