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

{
char str [50];
printf ("Enter string: ");
gets(str);
displayString(str); // Passing string c to function.
return 0;

}
void displayString (char str [])
{

printf ("String Output: ");
puts(str);
}
 Here, string c is passed from main () function to user-defined function displayString (). In
function declaration, str [] is the formal argument.

Boolean

bool is a data type in C. It sends for Boolean variable, i.e. the variable which can has
only 0 or 1 value. In this case the value is True or False.

If you decide to define them yourself, the choice between #defines and enumeration
constants for the true/false values is arbitrary and not terribly interesting. Use any of

#define TRUE 1 #define YES 1
#define FALSE 0 #define NO 0

enum bool {false, true}; enum bool {no, yes};

or use raw 1 and 0, as long as you are consistent within one program or project. (An
enumeration may be preferable if your debugger shows the names of enumeration
constants when examining variables.)

You may also want to use a typedef:

typedef int bool;
or
typedef char bool;
or
typedef enum {false, true} bool;

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

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

Some people prefer variants like

#define TRUE (1==1)
#define FALSE (! TRUE)

Numeric constants: There are two types of numeric constants,

1. Integer constants
2. Real or floating-point constants

Integer constants

 Any whole number value is an integer.

 An integer constant refers to a sequence of digits without a decimal point.

 An integer preceded by a unary minus may be considered to represent a negative constant

 Example: 0 -33 32767

Decimal Integer constant (base 10)

 It consists of any combinations of digits taken from the set 0 through 9, preceded by an
optional – or + sign.

 The first digit must be other than 0.
 Embedded spaces, commas, and non-digit characters are not permitted between digits.

Valid: 0 32767 -9999 -23
Invalid:
12,245 - Illegal character (,)

10 20 30 - Illegal character (blank space)

Unsigned integer constant

An unsigned integer constant specifies only positive integer value. It is used only to count things. This
constant can be identified by appending the letter u or U to the end of the constant.

Valid: 0u 1U 65535u 0x233AU
Invalid: -123 - Only positive value

Long integer constant

A long integer constant will automatically be generated simply by specifying a constant that exceeds the

normal maximum value. It is used only to count things. This constant can be identified by appending the

letter l or L to the end of the constant.

Valid: 0l23456L 0x123456L -123456l

Invalid: 0x1.2L - Illegal character (.)

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

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

Short integer constant

A short integer constant specifies small integer value. This constant can be identified by appending the
letter s or S to the end of the constant.

Valid: 123s -456 32767S
Invalid:
12,245 - Illegal character (,)

10 20 30 - Illegal character (blank space)

Note: - A sign qualifier can be appended at the end of the constant. Usually suffixes (s or S, u or U, l or L)
are not needed. The compiler automatically considers small integer constants to be of type short and
large integer constants to be of type long.

Rules for constructing Integer constants

i. An integer constant must have at least one digit.
ii. It must not have a decimal point.
iii. It can be either positive or negative.
iv. If no sign precedes an integer constant, it is assumed to be positive.
v. Commas or blanks are not allowed within an integer constant.

Real or Floating-point constant

Constants in C are fixed value that does not change during the execution of a program. A real constant is
combination of a whole number followed by a decimal point and the fractional part. Example:
0.0083 -0.75 .95 215.

Use of Real or Floating-point constants

Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices and so on. These quantities are represented by numbers
containing fractional part. Such numbers are called real or floating-point constants.

The Real or Floating-point constants can be written in two forms:

1. Fractional or Normal form
2. Exponential or Scientific form

Express a Real constant in fractional form

A real constant consists for a series of digits representing the whole part of the number, followed by a
decimal point, followed by a series of representing the fractional part. The whole part or the fractional
part can be omitted, but both cannot be omitted. The decimal cannot be omitted. That is, it is possible
that the number may not have digits before the decimal point or after the decimal point.

Valid Real constants (Fractional): 0.0 -0.1 +123.456 .2 2.

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

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

Invalid Real constant: - 1- a decimal point is missing
1, 2.3 - Illegal character (.)

Rules for Constructing Real Constants in Fractional Form

1. A real constant must have at least one digit.
2. It must have a decimal point.
3. It could be either positive or negative.
4. Default sign is positive.
5. Commas or blanks are not allowed within a real constant.

String Constant

A character string, a string constant consists of a sequence of characters enclosed in double
quotes.
A string constant may consist of any combination of digits, letters, escaped sequences and
spaces. Note that a character constant ‫ۥ‬A‫ ۥ‬and the corresponding single character string

constant "A" are not equivalent.

‫ۥ‬A‫ ۥ‬- Character constant - ‫ۥ‬A‫ۥ‬
"A" - String Constant - ‫ۥ‬A‫ ۥ‬and ‫\ ۥ‬0‫( ۥ‬NULL)

The string constant "A" consists of character A and \0. However, a single character string
constant does not have an equivalent integer value. It occupies two bytes, one for the ASCII
code of A and another for the NULL character with a value 0, which is used to terminate all
strings.

Valid String Constants: - "W" "100" "24, Kaja Street"

Invalid String Constants: - "W the closing double quotes missing
Raja" the beginning double quotes missing

Rules for Constructing String constants

1) A string constant may consist of any combination of digits, letters, escaped sequences
and spaces enclosed in double quotes.
2) Every string constant ends up with a NULL character which is automatically assigned
(before the closing double quotation mark) by the compiler.

Difference between single character constant and string constant

Character Constant String Constant
A character constant is enclosed within single
inverted commas. A sequence of characters enclosed in double
The maximum length of a character constant quotes.
can be one character. A string constant can be any length.

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

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

A single character string constant has an A single character string constant does not
equivalent integer value. have an equivalent integer value.
The string constant "A" consists of
The character constant ‘A’ consists of only character A and \0.
character A. A single string constant occupies two bytes.

A single character constant occupies one Every string constant ends up with a NULL
byte. character which is automatically assigned
Every character constant does not end up (before the closing double quotation mark) by
with a NULL character. the compiler.

How to Use Constants in A C Program?

C Constants are also like normal variables. But only difference is, their values cannot be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax: const data_type variable_name;

We can define constants in a C program in the following ways.

1. By “const” keyword
2. By “#define” preprocessor directive

Please note that when you try to change constant values after defining in C program, it will through
error.

1. Example program using const keyword in c:

1 #include <stdio.h>
2 void main ()
3{
4 const int height = 100; /*int constant*/
5 const float number = 3.14; /*Real constant*/
6 const char letter = 'A'; /*char constant*/
7 const char letter_sequence [10] = "ABC"; /*string constant*/
8 const char backslash_char = '\?'; /*special char cnst*/
9 printf ("value of height: %d \n", height);
10 printf ("value of number: %f \n", number);
11 printf ("value of letter: %c \n", letter);
12 printf ("value of letter_sequence: %s \n", letter_sequence);
13 printf ("value of backslash_char: %c \n", backslash_char);
14 }

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

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

Output:

value of height: 100
value of number: 3.140000
value of letter: A
value of letter_sequence: ABC
value of backslash_char:?

2. Example program using #define preprocessor directive in c:

1 #include <stdio.h>
2 #define height 100
3 #define number 3.14
4 #define letter 'A'
5 #define letter_sequence "ABC"
6 #define backslash_char '\?'
7 void main ()
8{
9 printf ("value of height: %d \n", height);
10 printf ("value of number: %f \n", number);
11 printf ("value of letter: %c \n", letter);
12 printf ("value of letter_sequence: %s \n”, letter_sequence);
13 printf ("value of backslash_char: %c \n”, backslash_char);
14 }

Output:

value of height: 100
value of number: 3.140000
value of letter: A
value of letter_sequence: ABC
value of backslash_char:?

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

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

C – Variable

C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.

Rules for Naming C Variable:
1. Variable name must begin with letter or underscore.
2. Variables are case sensitive.
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name

Declaring & Initializing C Variable:
 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on variable

definition.
 Variable initialization means assigning a value to the variable.

Type Syntax

Variable declaration data_type variable_name;

Example: int x, y, z; char flat, ch;

Variable data_type variable_name = value;
initialization Example: int x = 50, y = 30; char flag = ‘x’, ch=’l’;

There Are Three Types of Variables in C Program They Are,
a) Local variable
b) Global variable
c) Environment variable

1. Example Program for Local Variable In C:
 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed outside the function.
 In the below example, m and n variables are having scope within the main function only. These

are not visible to test function.
 Likewise, a and b variables are having scope within the test function only. These are not visible to

main function.

1 #include<stdio.h>
2 void test ();
3
4 int main ()
5{
6 int m = 22, n = 44;
7 // m, n are local variables of main function

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

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

8 /*m and n variables are having scope
9 within this main function only.
10 These are not visible to test funtion. */
11 /* If you try to access a and b in this function,
12 you will get 'a' undeclared and 'b' undeclared error */
13 printf ("\nvalues: m = %d and n = %d", m, n);
14 test ();
15 }
16
17 void test ()
18 {
19 int a = 50, b = 80;
20 // a, b are local variables of test function
21 /*a and b variables are having scope
22 within this test function only.
23 These are not visible to main function. */
24 /* If you try to access m and n in this function,
25 you will get 'm' undeclared and 'n' undeclared
26 error */
27 printf ("\n values: a = %d and b = %d", a, b);
28 }

Output:

values: m = 22 and n = 44
values: a = 50 and b = 80

2. Example Program for Global Variable in C:

 The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.

 This variable is defined outside the main function. So that, this variable is visible to main function
and all other sub functions.

1 #include<stdio.h>
2 void test (); int m = 22, n = 44;
3 int a = 50, b = 80;
4
5 int main ()
6{
7 printf ("All variables are accessed from main function");
8 printf ("\nvalues: m=%d: n=%d: a=%d: b=%d", m, n, a, b);
9 test ();
10 }
11
12 void test ()
13 {
14 printf ("\n\nAll variables are accessed from" \

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

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

15 " test function");
16 printf ("\nvalues: m=%d: n=%d: a=%d: b=%d", m, n, a, b);
17 }

Output:

All variables are accessed from main function
values: m = 22: n = 44: a = 50: b = 80
All variables are accessed from test function
values: m = 22: n = 44: a = 50: b = 80

Array

C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.

Array might be belonging to any of the data types
Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.

Example for C Arrays:

int a [10]; // integer array
char b [10]; // character array i.e. string

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

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

Struct

C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.

If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be
allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign
any values to structure members.
Example member / attribute Student and Employee as a below:

Example of Struct
1.

2.

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

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

Difference between C Variable, C Array and C Structure:

A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types and Data types can be int, char, float,
double and long double etc.

C Structure:

Syntax struct student
Example {
int a;
char b [10];
}

a = 10;

b = “Hello”;

C Variable:

int Syntax: int a;
char Example: a = 20;

Syntax: char b;
Example: b=’Z’;

C Array:

int Syntax: int a [3];
Example:
a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = ‘\0’;

char Syntax: char b [10];

Example: b=” Hello”;

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

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

Below table explains following concepts in c structure.

1. How to declare a C structure?
2. How to initialize a C structure?
3. How to access the members of a C structure?

Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int mark;
char name [10];
float average;
};
Declaring structure using normal variable:
struct student report;
Initializing structure using normal variable:
struct student report = {100, “Mani”, 99.5};
Accessing structure members using normal variable:
report. mark;
report.name;
report. average;

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

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

2.2.2 Tutorial 2

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

1. Exercise Introduction

/*This is a basic structure C program*/

#include <stdio.h>

void main ()
{

int form = 6;

printf ("\n I study at SMK Tinggi, Setapak.");
printf ("\n My class name is form %d Science 2", form);
}

2. Exercise Decimal 1

#include<stdio.h>

void main ()
{

printf ("%d, %d, %d\n",456, 456, 456);
printf ("%5d, %5d, %5d\n",456, 456, 456);
printf ("%7d, %7d, %7d\n",456, 456, 456);
}

3. Exercise Decimal 2

#include<stdio.h>

void main ()
{

printf ("%d, %d, %d\n",456, 456, 456);
printf ("%-5d, %-5d, %-5d\n",456, 456, 456);
printf ("%-7d, %-7d, %-7d\n",456, 456, 456);
}

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

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

4. Exercise Decimal 3

#include<stdio.h>

void main ()
{

int day, month, year;

printf ("Please enter a date:\n");
scanf ("%d %d %d”, &day, &month, &year);

printf ("Day: %d\t Month: %d\t Year: %d", day, month, year);
}

5. Exercise Character 1

#include<stdio.h>

void main ()
{

char my_alphabet;

printf ("Enter an alphabet from a to z: ");
scanf ("%c", &my_alphabet);

printf ("\nYou typed an alphabet %c", my_alphabet);
}

6. Exercise Character 2

#include<stdio.h>

void main ()
{

char gender;

printf ("Type f if you are female or m if you are male: ");
scanf ("%c", &gender);

printf ("\nYour are %c", gender);
}

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

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

7. Exercise Float 1 //price input
//item input
#include<stdio.h>
void main ()
{

int item;
float price, sum;

printf ("Price: RM ");
scanf ("%f”, &price);
printf ("Number of items: ");
scanf ("%d”, &item);

sum = price * item;
printf ("\nYou have to pay RM %.2f\n”, sum);
//%.2f = The output is rounded to 2 decimal places
}

8. Exercise Float 2

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

printf("%6.2f\n",123.4567);
printf("%7.1f\n",123.4567);
printf("%7.2f\n",123.4567);
printf("%7.3f\n",123.4567);
}

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

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

2.3 Input and Output

Input and output function can used when you include a header file “stdio.h”
#include<stdio.h>

The printf have several format specifications:-
%d -> print integer
%u -> print unsigned integer
%ld -> print long integer
%f -> print a float
%lf -> print long float(double)
%e -> print a floating in scientific notation
%c -> print a character
%s -> print a string

Any occurences of the ‘ \ ’ character inside string is called an escape sequence. Some common
escape sequence :-

\’ - Output a single quote( ‘ ) charecter
\” - Output a double quote ( “ ) character
\? - output a question mark ( ? ) character
\\ - output a backslash( \ ) character
\a - cause an audible (bell) or visual alert
\b - move the cursor back one position on the current line
\f - move the cursor to the next logical page
\n - move the cursor to the beginning of the next line
\r - move the cursor to the beginning of the current line
\t - move the cursor to the next horizontal tab position
\v - move the cursor to the next vertical tab position

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

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

Format specification: %s
You can specify a field with by placing a decimal number between the % and s, if the number is
larger than the data requires. It is padded with space on the left.
Example 1:

printf ( “Computer\n”); Output:

printf (“%s\n”, “Computer”); Computer

printf(“%4s\n”, “Computer”); Computer

printf(“%13s\n”, “Computer”); Computer
Example 2:

#include<stdio.h> ~~~~~Computer
void main()

{

char color[ ] = “Yellow”;

printf(“%s”, color);

}

Example 3:

#include<stdio.h>
main()
{

printf(“[%30s]\n”, “SMK. Tinggi Setapak”);
printf(“[%-30s]\n”, “SMK. Tinggi Setapak”);
printf(“[%15.6s]\n”, “SMK. Tinggi Setapak”);
printf(“[%-15.6s\n”, “SMK. Tinggi Setapak”);
return 0;
}

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

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

Format : %c
Same as printing a string, you can specify a filed width by placing a decimal number between the
% and c.

Example:
printf(“%c%c%c%c”,’J’,’U’,’N’,’E’);
Output:
JUNE

printf(“%c%3c%7c”, ‘A’,’B’,’C’);
Output: A~~B~~~~~~C

char let1, let2, let3, let4;
let1 = ‘J’;
let2 = ‘U’;
let3 = ‘N’;
let4 = ‘E’;
printf(“%c%c%c%c”, let1, let2, let3, let4);

Output:
JUNE

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

2nd Semester: Programming (C Language) – 3rd Edition 2021
2.3.3 Printing Integers and Floating Point Numbers

Format: %d - integers
%f - float

Coding: printf(“%5d\n”, 66);
printf(“%-5d%4d”,66,777);

Output: ~~~66
66~~~~777

Coding 1:

int num1;
float num2;
num1 = 5;
num2 = 33.77;
printf(“The first number is = %d \n”, num1);
printf(“The second number is = %f \n”, num2);

Output:
The first number is = 5
The second number is = 33.7700

Coding: printf(“%d\n”, 1234); Coding: printf(“%5d\n”, 1234);
printf(“%2d\n”, 1234); printf(“%6d\n”, 1234);
printf(“%3d\n”, 1234); printf(“%7d\n”, 1234);
printf(“%4d\n”, 1234); printf(“%8d\n”, 1234);

Output: 1234 Output: ~1234
1234 ~~1234
1234 ~~~1234
1234 ~~~~1234

Meanwhile, a format for floating point number is: %m.nf
 m=field width(the maximum number of total characters to print)
 n=number of decimal places (how many digits after the decimal point to print)

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

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

Coding 1: Output:
printf(“%6.1f\n”, 12.12345); ~~12.1
printf(“%6.2f\n”, 12.12345); ~12.12
printf(“%6.3f\n”, 12.12345); 12.123

Coding 2: Output: The output is
printf(“% .1f\n”, 12.345678); 12.3 rounded to 2
printf(“% .2f\n”, 12.345678); 12.35 decimal places
printf(“% .3f\n”, 12.345678); 12.346

Coding 3: Output:
printf(“%4.2f\n”, 7.88); 7.88
printf(“%4.2f\n”, 7.888); 7.89
printf(“%4.2f\n”, 7.8); 7.80
printf(“%4.2f\n”, 777.888); 777.89

2.3.4 Displaying Several Values at Once

You may use a single printf() to display several values
Coding:
printf(“%8.2f%3c%8d”, 7.2, ‘R’, 250);

The single prinOtfu() tstpatuemt:ent is equivalent to the three statement:

printf(“%8.2f”, 7.2);

printf~(“%~3c~”,~‘R’7);.20~~R~~~~~250

printf”%8d”, 250);

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

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

Coding:
int year = 19;
float height = 1.72;
printf(“Weng Yee is %d years old and %.2f m height”, year, height);

Otuput:
Weng Yee is 19 years old and 1.72 m height

2.3.5 The scanf( ) Function

%d - read an integer
%f - read a float
%lf - read a long float(double)
%c - read a character
%s - read a string

Coding 1: Output:

int day, month, year; Please enter a date:
printf(“Please enter a date:\n”);
scanf(“%d %d %d”, &day, &month, &year); 24 6 2008

Day: 24 Month: 6 Year: 2008

printf(“ Day:%d\t Month:%d\t Year:%d”, day, month, year);

Coding 2 : Output:
Enter a string:Earth
char x, y[9]; The input was:
printf(“Enter a string:”); The character “E” and the string “arth”
scanf(“%c%s”, &x, y);
printf(“The input was:\n”);
printf(“The character \”%c\””, x);
printf(“ and the string \”%s\””,y);

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

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

2.3.6 Other Functions for Input/Output Purposes

1. getc( ) and putc( )
2. getchar( ) and putchar( )
3. getch( ) and putch( )
4. gets( ) and puts( )

1. The getc( ) and putc( )

 function can be accessed from the standard header file<stdio.h>.
 The getc( ) reads a single character from standard input device.
 The putc( ) function prints one single character on the strandard output device:
 Format:-

variable = getc(stdin);
putc(variable, stdout);

2. The getchar( ) and putchar( ) function

 same as the getc( ) and putc( ) except you do not need to put the standard input/output

device in parenthesis.

 Format:-

variable = getc(stdin); putc(variable, stdout);

variable = getchar( ); putchar(variable);

Example:

#include<stdio.h>
main( )
{

int my_character;
printf(“Enter a character please:”);
my_character = getchar();
printf(“\n You typed a
character>>>”);
putchar(my_character);
return 0;
}

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

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

3. For getch( ) and putch( ) functions,

 you do not need to put the input/output standard device in the parenthasis.
 The format:

variable = getch( );
putch(variable);
 but this functions are eccessed from the standard header file<conio.h>.
 The other different is the input character from the keyboard will not be displayed on the
screen whereas for the other function before, the input can be seen on the screen.

Example:

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

main( )
{

char letter;
printf(“Enter a character\n”);
letter = getch();
printf(“the character you have typed is:”);
putch(letter);
return 0;
}

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

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

3. The gets( ) and puts) can be accessed from the standard header file<stdio.h>.

 The gets( ) function reads a string entered from the keyboard.
 It will end the string with a null(\0) character.
 The puts( ) function prints a string on the screen.
 It will end the string with a new line( n) character.

Example:

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

void main()

{
char name[30];
printf(“Enter your name>>”);
gets(name); /*reads a string */
printf(“\n How are you ”);
puts(name); /* prints a string */
puts(“\nIt is your lucky day!!!”);
getch();

}

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

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

2.3.7 Excercise 1 : Data Type – Character and String

1. A C program contains the following statements:
#include<stdio.h>
char a, s, y;

a) write appropriate getchar statement that will allow values for a, s and y to be entered into the
computer.

b) b) write appropriate putchar statement that will allow the current values of a, s, and y to be
written out of the computer.

2. A C program contains the following statements:

#include<stdio.h>
char text[55];

Write a scanf function that will allow a string to be read into the computer and assigned to the
caharacter array text. Assume that the string does not contain any whitespace characters.

3. A C program contains the following statements:

#include<stdio.h>
char name[30];

Write a printf function that will allow the contents of name to be displayed in the following ways:
a) Entirely on one line
b) Only the first five characters
c) The first five characters, followed by 7 blanks.
d) The first five characters, preceded by 7 blanks.

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

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

2.4 Expressions and Operators

2.4.1 Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators

Arithmetic Operators
Assignment Operators
Unary Operators
Relational and Equality Operators
Logical Operators

2.4.1.1 Arithmetic Operators

We need operators to construct statements to do an operation and calculations.

Operator is a token that can be aplied to variables or any elements in an expression to
produce some kind of computation or action.

+ Addition operator
- Substraction operator
* Multiplication operator
/ Division operator
% Modulus operator(Remainder fo dividion)

*The fifth operator, % is called the ramainder(or modulus) operator. Its operands must be
integer
quantities.

Example 1: 43%8 = 3

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

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

Example 2:

#include<stdio.h>
main( )
{

int num = 20, val = 30;

printf(“nilai asal num:%d dan dilai asal val:%d\n”, num,val);
num = val +5; /* addition operator: num is now 35 */

printf(“nilai num sekarang ialah:%d\n”,num);

val=num-val; /* substraction operator: val is now 5 */
printf(“nilai val ialah:%d\n”,val);

num=num * 2; /* multiplication operator: num is now 70 */
printf(“nilai num setelah darab dua ialah:%d\n”,num);

val=30/7; /* division operator: val is now 4 */
printf(“nilai baru val :%d\n”,val);
}

1. Assigning Mathematical Operator Combinations

To increase or decrease the value already assigned to a variable:

Example:

int num = 5; Or:
num = num – 6; int num = 5;
num -= 6;

int num = 5;
num -= 3; /* same as num =num -3; num is now 2 */
num *=4; /* same as num = num *4; num is now 8 */

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

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

Compound Assignment

Operator Syntax Meaning

*= price*=2.5; price = price * 2.5;
/= total /=2; total=total/2;
%= month %=2; month = month %2;
+= bonus +=800; bonus = bonus+800;
-= balance -=sum+tax; balance = balance – (sum+tax)

2. Unary Sign Operator

Unary Operator---the unary operator operates on a single variable or constant statement.

Unary operator require only one operand and consist the symbols +,-,++ or --.

Example:

x = -y; p = +x * y;

++count; count--;

3. Binary Operator

Each operand links something from left to right with some action.
Binary operators require two operands and consist the symbol +,-,*,/,or %.
Example: z = y – x; x = y + z;

4. Expression with Multiple Operators

Expression can include both unary and binary operators. For readability, do not use a space
between a unary operator and its operand; do use space before and after binary operators.
Use bracket, if more then one expression, from left to right ( ) Rules for Evaluation of
Arithmetic Expressions.
The operator precedence rule:Operators in the same sub-expression are evaluated in the
following order:

Operators Evaluation Associativity
unary+,unary- First
*, /, % Next

+. - Last

For example:
(a) x * y * z + a / b – c * d can be write as...(b)
(b) (x * y * z ) + (a / b) – (c * d)

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

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

Additional Notes:

Example

int a, b, c, d, e;
a=10, b=20, c=15, d=8, e=40;

consider the arithmetic expression : a*b/(- c * 31 % 13) * d;

The expression will be evaluated to six steps as shown below:

STEP OPERATOR REDUCE EXPRESSION

1 Unary - a*b/(-15 * 31 % 13) * d
2 * a*b/ (-465 % 13) * d
3 % a*b/(-10) * d
4 * 200 / (-10) * d
5 / -20 * d
6 * -160

Increment and Decrement Operator

1. Increment Operator: ++

The increment operator only use Unary / Operator. The purpose is to increment a variable

by 1 ( i = i + 1). for (i =0; i < 4; i++)
Also it is used as counter in loop structure. for (i =0; i< 4; i++)

2. Decrement Operator: --
Only uses Unary – Operator. The operator is used to decrement a variable by 1 ( i = i – 1).

int a = 1, b = 2, c= 3;
c--;
printf (“%d %d %d \n”, --a, b--, c);

The table below shows the Syntax examples for the increment(prefix) and incremet(postfix) operator:

++i(prefix) i++(postfix)
In the letter case, the operator comes just in In the former case, we place the operator after
front of the variable. the variable
Incrementing i value Use i value in expression
Use new i value in expression Incrementing i value (before expresion executes)

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

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

Example:

int a = 0, b = 0, c = 0, d =0;
c++;
printf(“ %d %d ”, 4 – d++, d);
printf (“ %d %d %d %d “, ++a, b++, c, d);

Increased Efficiency

value++; value--;
value+=1; value-=1;
value=value+1; value=value-1;

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

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

2.4.1.2.Assignment Operators

The following table lists the assignment operators supported by the C language

Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will assign the value of

right side operands to left side operand A + B to C

+= Add AND assignment operator. It adds the right C += A is equivalent to C = C + A
operand to the left operand and assign the result
to the left operand.

-= Subtract AND assignment operator. It subtracts C -= A is equivalent to C = C - A
the right operand from the left operand and
assigns the result to the left operand.

*= Multiply AND assignment operator. It multiplies C *= A is equivalent to C = C * A
the right operand with the left operand and
assigns the result to the left operand.

/= Divide AND assignment operator. It divides the left C /= A is equivalent to C = C / A
operand with the right operand and assigns the
result to the left operand.

%= Modulus AND assignment operator. It takes C %= A is equivalent to C = C % A
modulus using two operands and assigns the
result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

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

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

2. 4.1.3 Unary Operators

In the C family of languages, the following operators are unary:

1. Increment: ++x, x++
2. Decrement: −−x, x−−
3. Address: &x
4. Indirection: *x
5. Positive: +x
6. Negative: −x
7. Ones' complement: ~x
8. Logical negation: !x
9. Sizeof: sizeof x, sizeof(type-name)
10. Cast: (type-name) cast-expression

2. 4.1.4 Relational and Equality Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, (A == B) is not true.
then the condition becomes true.

!= Checks if the values of two operands are equal or not. If the (A! = B) is true.
values are not equal, then the condition becomes true.

> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand. If yes, then the condition becomes true.

< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.

>= Checks if the value of left operand is greater than or equal to the (A >= B) is not true.
value of right operand. If yes, then the condition becomes true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand. If yes, then the condition becomes true.

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

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

2. 4.1.5 Logical Operators

Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both the operands are non- (A && B) is false.
zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two operands is (A || B) is true.
non-zero, then the condition becomes true.

Called Logical NOT Operator. It is used to reverse the logical
! state of its operand. If a condition is true, then Logical NOT ! (A && B) is true.

operator will make it false.

Logical operator table in c;
 1 – on / yes / true
 0 – off / no / false

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

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

2.4.2 Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

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

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

2.4.3 Exercise 2: Expression and Operator

1. Write a C statement to accomplish each of the following task.
a) Declare variable sum and x of type int.
b) Initialize variable x to 1.
c) Initialize variable sum to 0.
d) Add variable x to variable sum and assign the result to variable sum.
e) Print “ The sum is.” Followed by the value of variable sum.

2. If a is 4, b is 3.8, and c is 2, what is the value of this expression?

(int)b+a*c

3. Assume that n and d represent positive integers. Write a more concise expression that is equivalent to

n-n/d*d

4. What does the following function do ?

Void nonsense (void)
{

printf(“*****\n”);
printf(“* *\n”);
printf(“*****\n);
}

5. What does the following main function do ?

int main(void)
{

nonsense();
nonsense();
nonsense();
return (0);
}

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

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

2.4.2 Tutorial 3: Expression and Operator

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

1. Exercise Modulus Operator

/*Operator % is called the remainder (or modulus) operator. Its operands must be
integer quantities. It calculates the remainder of the division of its first operand by its
second operand */

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

int num;
int balance;

printf ("Enter digit number: ");
scanf ("%d”, &num);
balance = num % 2;
printf ("%d %% 2 = %d “, num, balance);
}

2. Exercise Unary Prefix Operator

/*Arithmetic Operator – Unary prefix
The unary operator operates on a single variable or constant statement.
Unary operators require only one operand and consist the symbols +, -, ++ or --
*/

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

int a;
a=1;

printf ("%d\n”, ++a);

/* ++a (prefix). In the latter case, the operator comes just in front of the
variable. Incrementing a value. Use new a value in expression
Ex: 1 + 1 = a so a = 2 */

}

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

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

3. Exercise Unary Postfix Operator

/* Arithmetic Operator - Unary a++ (postfix). In the former case, we place the operator
after the variable. Use a value in expression. Incrementing a value (before expression
executes). */

#include<stdio.h>

void main ()
{

int a;
a=1;
printf ("%d\n”, a++);

//use the original value
//original value is 1
}

4. Exercise Relational and Equality Operator

/* Relational and Equality Operator
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
! = Not equal to

The C relational and equality operators give a result of 1 for true and 0 for false */

#include<stdio.h>

void main ()
{

int a=10, b=3;

if(a==b)
printf("true");

else
printf("false");

}

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

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

5. Exercise and Operator 1

/* Logic operator AND - symbol &&
true && true = true
true && false = false
false && true = false
false && false = false

*/

#include<stdio.h>

void main ()
{int a=2, b=3;

if((a<b) && (b>a))
printf("true");

else
printf("false");

}

6. Exercise and Operator 2

/* Logic operator AND - symbol &&
true && true = true
true && false = false
false && true = false
false && false = false

*/

#include<stdio.h>

void main ()
{int i=7;

float f=5.5;
char c='w';

if((i>=6) &&(c=='w'))
printf("true");

else
printf("false");

}

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

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

7. Exercise and Operator 3 © Nar | Nisrin Ahmad Ramly \(^o^)/

/* Logic operator AND - symbol &&
true && true = true
true && false = false
false && true = false
false && false = false

*/

#include<stdio.h>

void main ()
{int i=7;

float f=5.5;
char c='w';

if((f<11) &&(i>100))
printf("true");

else
printf("false");

}

8. Exercise or Operator 1

/*Logic operator OR (||)
true || true = true
true || false = true
false || true = true
false || false = false

*/

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

char sex;

printf ("Enter your sex (L/P): ");
scanf ("%c”, &sex);

switch (sex)
{

case 'L': case 'l':

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

printf ("\nHave a nice day, Sir");
case 'P': case 'p':
printf ("\nHave a nice day, Madam");
default:
printf ("Gender does not exist");
}
}

9. Exercise or Operator 2

/*Logic operator OR (||)
true || false = true
true || false = true
false || true = true
false || false = false

*/

#include<stdio.h>

void main ()
{int i=7;

float f=5.5;
char c='w';

if((i>=6) ||(c==119))
printf("true");

else
printf("false");

}

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

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

10. Exercise or Operator 3

/*Logic operator OR (||)
true || true = true
true || false = true
false || true = true
false || false = false

*/

#include<stdio.h>

void main ()
{int i=7;

float f=5.5;
char c='w';

if ((c! ='p’) ||((i+f) <=10))
printf("true");

else
printf("false");

}

11. Exercise Precedence Rules

/*The precedence rules
1. ()
2. *, /, %
3. +, -
*/

#include<stdio.h>

void main ()
{

printf ("%d\n", 5+2*6-4/2);
printf ("%d\n", 3*4/2+3-1);

printf ("%d\n", 5+2*(6-4)/2);
printf ("%d\n", 3*4/2+(3-1));
}

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

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

3. Problem Solving in Programming

Solving problems is the core of computer science.
Programmers must first understand how a human solves a problem, then understand how to
translate this "algorithm" into something a computer can do, and finally how to "write" the
specific syntax (required by a computer) to get the job done.
It is sometimes the case that a machine will solve a problem in a completely different way than a
human.

3.1 Programming Steps

Problem-Solving Phase

1. Program Analysis and Define What solution
Clarification specification problem must do

2. Program Design General Develop logical Verify (Follow
solution sequence of steps - by
3. Program Code (algorithm) steps to solve hand)
(program) problem
Translate
4. Program Test algorithm to
code
5. Program
Documentation Check
computed
6. Maintenance results
manually

Document 6
programming
steps

Modify to meet
changed
requirements or
to correct errors

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

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

●●●
Five Phases of Programming

1. State the problem clearly.
2. Describe the input and output information.
3. Work the problem by hand (or with a calculator) for a specific set of data.
4. Develop a solution that is general in nature.
5. Test the solution with a variety of data sets.

●●●

3.2 Algorithm

In programming, algorithm is the set of well-defined instruction in sequence to solve a program. An
algorithm should always have a clear stopping point.

Qualities of a good algorithm

1. Inputs and outputs should be defined precisely.
2. Each step-in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in such a

way that, it can be used in similar programming languages.

Method Algorithm

Algorithm

Pseudocode Flowchart

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

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

3.2.1 Defining Pseudocode

Pseudocode is a simple way of writing programming code in English.
Pseudocode is not actual programming language.
It uses short phrases to write code for programs before you actually create it in a specific
language.
Once you know what the program is about and how it will function, then you can use
pseudocode to create statements to achieve the required results for your program.

Understanding Pseudocode

Pseudocode makes creating programs easier.
Programs can be complex and long; preparation is the key.
For years, flowcharts were used to map out programs before writing one line of code in a
language.
However, they were difficult to modify and with the advancement of programming languages, it
was difficult to display all parts of a program with a flowchart.
It is challenging to find a mistake without understanding the complete flow of a program.
That is where pseudocode becomes more appealing.
To use pseudocode, all you do is write what you want your program to say in English.
Pseudocode allows you to translate your statements into any language because there are no
special commands and it is not standardized.
Writing out programs before you code can enable you to better organize and see where you
may have left out needed parts in your programs.
All you have to do is write it out in your own words in short statements. Let's look at some
examples.

Examples of Pseudocode

Let's review an example of pseudocode to create a program to add 2 numbers together and
then display the result.

1. Step 1 - Describe the input, output information and formula

Input: 2 numbers
Output: Result sum of two numbers
Formula: Sum = A + B

2. Step 2 - Develop logical sequence of steps to solve problem

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

Now, let's look at a few more simple examples of pseudocode. Here is a pseudocode
to compute the area of a rectangle:

1. Step 1 - Describe the input, output information and formula

Input: 2 numbers, length and width
Output: Result multiply of length and width
Proses: area = l* w

2. Step 2 - Develop logical sequence of steps to solve problem

1. Start Program
2. Get the length, l, and width, w
3. Compute the area = l*w
4. Display the area
5. End Program

●●●

Remember;

Writing basic pseudocode is not like writing an actual coding language.

It cannot be compiled or run like a regular program.

Pseudocode can be written how you want.

But some companies use specific pseudocode syntax to keep everyone in the
company on the same page.

Syntax is a set of rules on how to use and organize statements in a programming
language.

By adhering to specific syntax, everyone in the company can read and understand
the flow of a program.

This becomes cost effective and there is less time spent finding and correcting
errors.

●●●

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

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

3.2.2 Flowchart in Programming

Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing program
and explaining program to others.

Symbols Used in Flowchart

Different symbols are used for different states in flowchart, for example: Input/Output and decision
making has different symbols. The table below describes all the symbols that are used in making
flowchart

Symbol Purpose Description
Flow line
Used to indicate the flow of logic by connecting
Terminal (Stop/Start) symbols.
Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Processing Used for airthmetic operations and data-
Desicion manipulations.
On-page Connector
Used to represent the operation in which there are
two alternatives, true and false.

Used to join different flowline

Off-page Connector Used to connect flowchart portion on different
page.

Predefined Process/Function Used to represent a group of statements
performing one processing task.

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

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

Examples of flowcharts in programming
Let's review an example of flowchart to create a program to add 2 numbers together and then
display the result.

1. Step 1 - Describe the input, output information and formula

Input: 2 numbers
Output: Result sum of two numbers
Proses: Sum = A + B

2. Step 2 - Develop logical sequence of steps to solve problem

3.3 Exercise 2: Algorithm
Define the pseudocode and flowchart of a program where the user supplies three positive numbers
and the program returns the sum, average and root-mean-square of the values. Write the
corresponding algorithm.

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

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

4. Control Structures

Control Statements

Conditional Statement Looping Statement Jumping Statement

1. if statement 1. for loop 1. break statement
2. if else statement 2. while loop 2. continue statement
3. nested if else 3. do while loop 3. goto statement
4. else if construct
5. switch statement

A statement that is used to control the flow of execution in a program is called control structure.
It combines instruction into logical unit. Logical unit has one entry point and one exit point.

Types of control structures
1. Sequence
2. Selection
3. Repetition

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

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

4.1 Sequence:

Statements are executed in a specified order. No statement is skipped and no statement
is executed more than once.
Flowchart

For Example:
#include<stdio.h>
void main ()
int a;
{
int a=5;
printf (“Square of a = %d”,a);
}

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

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

It selects a statement to execute on the basis of condition.
Statement is executed when the condition is true and ignored when it is false e.g if,
if else, switch structures.
Flowchart

For Example

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

void main ()
{

int y;
clrscr ();

printf ("Enter a year:");
scanf ("%d”, &y);

if (y % 4==0)
printf ("%d is a leap year.”, y);

else
printf ("%d is not a leap year.”. y)

getch ();
}

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


Click to View FlipBook Version