Fundamentals of Programming Programming Concepts and Constructs (C Language)
UNIT
4.3
Programming Concepts and Constructs (C
Language)
Fundamentals of C Language
OBJECTIVES
This unit describes the structure of a C program. This unit also explains the
various data types and operators available in C language.
At the end of this unit, you will be able to
Describe the structure of a C program
Compile and execute simple C programs
Identify the basic elements of a C program
List the various data types in C language
Perform input-output operations
List the various operators available in C language
Benchmark Standard
Write simple programs using Mathematical operator
Write expressions using relational and logical operators
Display the output in a specified format
Fundamentals of C Language 4.3-1
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Let us Revise!
1. Define algorithm.
2. Why is algorithm important in programming?
3. Why is flowchart important in programming?
Introduction
C is a programming language developed at AT&T Bell laboratories by Dennis
Ritchie. This programming language was named C as it followed an earlier
programming language named B. C is a middle-level language. It has the
feature of both high-level and low-level languages. It allows low-level access
to information and commands. At the same time, it retains the syntax of high-
level languages and their advantage of being machine independent. C is
referred to as a structured language as it enforces logical structure in the
program. C follows modularity. Therefore, it is suitable for writing large and
complex programs.
C is portable, powerful and flexible. Because of these features, C is used for
both system and application level programming. C is reliable, simple and easy
to use. It is easier to learn newer languages once you are familiar with C
language. In this unit, you will learn the fundamentals of the C language.
4.3.1 Structure of C Programs
Languages like English have words, symbols and grammar rules. Similarly,
programming languages too have words, symbols and rules. In a
programming language, the rules are known as the syntax. If these rules are
not followed, a program will not work. Each programming language has its
own set of syntax and structures to be followed. A typical C program will
appear as shown in Table 4.3.1.
Structure Sample Program
< Comment entry > /* First C program */
< Preprocessor directives > #include <stdio.h>
main() main()
{ {
< Declarations >; int a;
< C statements >; printf("Welcome to C ");
} }
Table 4.3.1: Structure of a C Program 4.3-2
Fundamentals of C Language
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Consider the code given in the program.
1. The /* */ symbol denotes that the text that is enclosed within it is a
comment entry. Comments are used to describe the entire program or
specific lines of code in the program. The compiler will ignore the
comment entries during compilation. Comments can be written
anywhere in a program.
2. #include <stdio.h> is a preprocessor directive statement. This
statement directs the preprocessor to include the standard input and
output header file.
The symbol hash (#) will invoke the preprocessor directives.
Preprocessor directives are the instructions given to the compiler. The
keyword include will direct the preprocessor to include the specified
header file into the program. A header file contains definition for all the
functions that could be shared by several other programs.
Syntax
#include <filename>
Example
#include <stdio.h>
stdio.h will include all standard input-output functions.
3. main() is the function where the program is written.
Any C program will have one or more functions and the most important
function, which must be present in all the programs, is the main()
function. Programs will always start executing from this function. Other
function definitions can be written above or below the main function. A
program can have only one main() function.
4. int a; is an example for variable declaration. All the variables that are
used in a program must be declared.
5. printf("Welcome to C "); is a C statement that displays the specified
string on the screen. Statement is an instruction written in high-level
language.
Cross-Reference
You will learn about functions in detail in Unit 4.8.
Fundamentals of C Language 4.3-3
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Points to remember when writing a C program:
A C program must have the main() function.
It is important to include the necessary header files.
C is case sensitive. main() is not same as Main().
Any number of statements can be written in the same line.
Each C statement must be terminated with a semicolon (;).
Best Programming Practise
Always include comment entries in program.
Indent the statements within the main function.
4.3.2 Compilation and Execution
Definition: Compilation is the process of conversion of high-level language
into machine language.
Definition: Execution is the process of running the program to get the desired
output.
4.3.2 (A) Compilation
Computers cannot understand programs written in high-level language. These
programs, therefore, must be converted into machine language. For this
purpose, a compiler is used. Compilers are programs, which convert a high-
level language program into machine level language program. The process of
conversion is called compilation.
During compilation, the entire program is compiled and all errors in the
program are displayed. Once the errors are corrected, the program is
compiled successfully. The source code gets converted into object code.
Note
Each programming language has its own compiler.
4.3.2 (B) Execution
Compiler converts source code into object code. Using another program
called linker, the object code is converted into executable code. Before a
program is executed, it has to be loaded into the memory. A special program
called the loader will take the executable code from the disk and place it in the
Fundamentals of C Language 4.3-4
Fundamentals of Programming Programming Concepts and Constructs (C Language)
memory. This process is called loading. These executable programs are
executed to get the output. This process is called as execution.
Note
Source code: Programs written by humans using programming languages.
Object code: Machine code generated by a compiler.
Executable code: Machine code that is ready for execution.
The following are the steps involved in writing, compiling and executing a C
program:
1. Open the editor and type the program.
2. Save the file with the extension as .C.
3. Compile the program.
4. Execute/run the program.
Note
An editor allows you to type the program code, edit the code and store it. You can also perform
other operations, such as compilation and execution, by using the editor.
Note
You can also execute a program directly without compiling it. In such cases, the editor will
automatically compile the program and then execute it.
Activity 4.3.1 (a)
Step 1: Open the data file A3_1.C. The following C statements will be
displayed on the screen.
1. /* Displays the given string on the screen */ Comment entry.
2. Preprocessor
3. #include <stdio.h> directives.
4. #include <conio.h>
5. main() This statement will
6. { clear the screen
7. clrscr(); content.
8. printf(" MALAYSIA "); This statement will
9. } display the text
MALAYSIA on the
screen.
Fundamentals of C Language 4.3-5
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Step 2: Run the program and observe the output.
Step 3: Edit the code line 8 as printf(" I am in Malaysia ");.
Step 4: Save the program.
Step 5: Run and observe the output.
Activity 4.3.1 (b)
Step 1: Open the data file A3_2.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3. main()
4. {
5. clrscr();
6. printf(" WELCOME ")
7. }
Step 2: Run the program and observe the output.
Step 3: Edit the code line 6 as printf(" WELCOME ");.
Step 4: Save the program.
Step 5: Run and observe the output.
Activity 4.3.1 (c)
Step 1: Open the data file A3_3.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3. main();
4. {
5. clrscr();
6. printf(" HELLO ");
7. }
Step 2: Run the program and observe the output.
Step 3: Edit the code line 3 as main().
Fundamentals of C Language 4.3-6
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Step 4: Save the program.
Step 5: Run and observe the output.
Activity 4.3.1 (d)
Step 1: Open the data file A3_4.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3. main()
4. {
5. clrscr();
6. printf(" BEAUTY ")
7. }
Step 2: Identify the error in code line 6 and rectify the mistake.
Step 3: Save the program.
Step 4: Run and observe the output.
Lab Exercise
Lab Exercise 1: Write a program to display the following text on the screen.
World Is Beautiful
Self-Check Exercise 4.3.1
1. Why do you need to put comment entry in a program?
2. What is the need for compiler?
4.3.3 Variables, Constants and Data Types
Before you start writing programs, it is very important to understand the basic
elements that are used in constructing simple C statements. These are C
character set, variables, constants, data types and keywords as shown in
Figure 4.3.1.
Fundamentals of C Language 4.3-7
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Figure 4.3.1: C Basic Elements
4.3.3 (A) C Character Set
Definition: A character or set of characters is used to represent any
information.
C uses alphabets, numbers and certain special characters for this purpose.
Table 4.3.2 represents the alphabets, numbers and special characters that
are valid in C.
Type Character Set
Alphabets A, B, C … X, Y, Z
Digits a, b, c … x, y, z
Special
characters 0, 1, 2 … 9
+-*/%=&#<>():{}_;?“
| ‘ . , ~ \ ! ^ (blank space)
Table 4.3.2: C Character Set
Fundamentals of C Language 4.3-8
Fundamentals of Programming Programming Concepts and Constructs (C Language)
4.3.3 (B) Data Types
Definition: Data type will define the type of the value to be stored in the
memory.
Assume that you have to store information of student's English test results
such as the student’s name, age and marks. Student's name will have
characters, age will be integer and marks will be decimal. Humans can easily
identify these types. Computers cannot differentiate between these types. A
computer therefore uses special internal codes, called data type, for this
purpose.
Programming languages require the programmer to declare the data type of
every data object used in the program. The available data types may be
different from one programming language to another.
C supports several different types of data. The following are the basic data
types available in C:
Integer: A whole number, a number that has no fractional part.
Character: A single character or a group of characters (string).
Floating-point: A number with a decimal point.
Activity 4.3.2
Identify the data types for the following:
1. Assume that you have to store the information about a book; such as
book name and price.
2. Assume that you have to store information on employee’s details such
as employee name, employee id, designation and salary.
3. Assume that you have to store your account information such as bank
name, account number and balance.
4.3.3 (C) Variables
Definition: Variable is the name given to the memory location where the data
is stored. This value keeps changing during the program execution.
Computer stores data in the computer memory in a specific location. To use
the data, you must know the address of the memory location, where the data
is stored. The name given to this memory location is called a variable. The
data of a variable changes during the execution of the program.
Fundamentals of C Language 4.3-9
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Figure 4.3.2: Representation of Variable in Memory
When you want to reach a destination, you must know the address of that
destination. Similarly, to use the data stored in the memory, you need to refer
to the address of the memory location (variable), where the data is stored as
shown in Figure 4.3.2. Identifiers are the names given to the variables.
Rules for Naming Identifiers
The naming convention of the identifiers follows the following rules:
1. Can be a combination of alphabets and numbers but must start with
an alphabet.
2. Comprise maximum of 40 characters.
3. No commas or blank space is allowed.
4. No special characters can be used except underscore (_).
Best Programming Practise
When you name a variable, choose a relevant identifier. For example, name the variable to
accept the mark of students as mark, age as age, and so on
Table 4.3.3 gives a list of valid and invalid identifiers.
Fundamentals of C Language 4.3-10
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Identifiers Valid/Invalid Reason
Grade Valid Identifier should start with an alphabet.
2 Invalid Identifier starts with a number, which is
item1 Valid not allowed.
1name Invalid
Identifier can have combination of
alphabets and numbers.
Identifier starts with a number.
Amount 1 Invalid No blank space is allowed within a
code_1 Valid identifier.
area* Invalid
Special symbol underscore (_) can be
used in identifier.
Special character asterix (*) cannot be
used in a identifier.
Table 4.3.3: List of Examples for Valid Identifiers
Activity 4.3.3
Identify which of the following are valid identifiers. If invalid, explain why.
1. sal
2. INCOME
3. mark 1
4. bill_no
5. length-1
6. 123acc_no
7. mark1&mark2
8. 123
9. record4_1
10. $name
4.3.3 (D) Keywords
Definition: Keywords are reserved words for which the meaning is already
defined to the compiler.
C has special reserved words that cannot be used as identifiers. These are
keywords. There are 32 keywords in C language. They are listed in Table
4.3.4.
Fundamentals of C Language 4.3-11
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Types Keywords
Data types, modifiers void, int, char, float, double, signed,
and storage class unsigned, long, short, auto, const,
specifiers extern, static, volatile, register and
typedef
User defined data types
and type related struct, union, enum and sizeof
Conditional
Flow control if, else, switch, case and default
for, while, do, break, continue, goto
and return
Table 4.3.4: Keywords in C Language
Activity 4.3.4
Identify which of the following are valid identifiers. If invalid, explain why.
1. address
2. void
3. return1
4. case_do
5. goto
6. FOR
7. long_1
8. shotr
9. for*
10. char
4.3.3 (E) Constants
Definition: Constant is a location in the memory that stores data that never
changes during the execution of the program.
A constant can either be:
A numbers, like 15 or 10.5
A single character, like 'x' or '#'
A group of characters (string), like “Beautiful Malaysia”
Fundamentals of C Language 4.3-12
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Activity 4.3.5
Identify the type of constant in the following:
1. 3
2. 'A'
3. 12.5
4. 6
5. "ALL"
Table 4.3.5 represents the difference between variables and constants.
Variables Constants
Variable is the name given to the Constant is a location in the memory
memory location where the data is that stores data that never changes
stored. This value keeps changing during the execution of the program.
during the program execution.
Example: Example:
a, grade and mark 10, 'A' and 78.90
Table: 4.3.5: Difference between variables and constants
4.3.3 (F) Declarations in C
Any variable used in a program must be declared in the beginning. This is to
specify the variable data type to the compiler. Table 4.3.6 lists some of the
declarations used in C language.
Keywords Used Description
for Data type
Integer number: A whole number without fractional part.
int Floating-point number (with fractional part).
Character: A single character or string.
float
char
Table 4.3.6: Keywords for Declaration of Variables
Example 1
Data type is character.
char student_grade;
student_grade is a
variable.
Fundamentals of C Language 4.3-13
Fundamentals of Programming Programming Concepts and Constructs (C Language)
student_grade is a variable, which can take character value.
When you write char name, it is called variable declaration.
Variable declaration means specifying the type of the variable.
Example 2 Data type is integer.
int age; age is a variable.
age is a variable, which can take integer value.
Example 3
Data type is float.
float english_mark;
english_mark is a
variable.
mark is a variable, which can take integer value.
Hands-On!
Code Sample 4.3.1 illustrates the variable declarations.
/* Variable declarations */
#include <stdio.h>
void main()
{
int age;
char student_grade;
float english_mark;
}
Code Sample 4.3.1
Activity 4.3.6 (a)
Write the appropriate declarations for the following:
1. Integer variables: number and mark.
2. Floating-point variables: total and average.
3. Character variables: gender and grade.
Fundamentals of C Language 4.3-14
Fundamentals of Programming Programming Concepts and Constructs (C Language)
4. Integer variables: index and record.
5. Floating-point variables: salary and interest.
6. Character variables: city_pin.
Activity 4.3.6 (b)
Identify the data types for the following and make the appropriate
declarations:
1. For billing: item_number, price and total.
2. Mark list: index_number, mark1, mark2, total and average.
3. Customer detail: cus_id and cus_grade.
4. Video library: cd_rack_number and cd_number.
5. Food item: item_id and price.
4.3.4 Input/Output Statements
Definition: Input statements are used for accepting data from the user.
Definition: Output statements are used for displaying the processed data on
the screen.
Input statements are used to make the program more interactive.
4.3.4 (A) scanf( )
Definition: scanf()is a function, used as a statement, to get the value from
the user.
Format specifier
Example
scanf("%d",&age);
Identifier
The scanf()function has two parameters: the format specifier and the
variable. These parameters have to be separated by the delimiter comma (,).
In the example, scanf statement will request the user to enter the age. The
variable age is of an integer data type.
Note
The symbol ampersand (&) refers to the address of a variable in the memory. The input data
has to be stored in the memory addressed by that variable.
Syntax
scanf("<format specifier>",&<variable>);
Fundamentals of C Language 4.3-15
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Format Specifiers
Definition: Format specifier defines the data type of the variable to the
compiler.
To accept a value, you must specify the type of data expected. Consider the
example given for scanf(). As the variable age is integer type, the format
specifier, %d, is used. It indicates that the variable age is of integer type.
Some of the commonly used format specifiers are listed in Table 4.3.7.
Format Specifier Data Type
%d Int
%f Float
%c Char
Table 4.3.7: Format Specifiers
4.3.4 (B) printf( )
Definition: printf()is a function, used as a statement, to display the data on
the screen.
Example 1
printf("Welcome");
Output
Welcome
In example 1, the string Welcome will be displayed on the screen.
Example 2 String to be displayed on
the screen.
printf("My age is %d",age);
Variable whose value will
be displayed.
Output
My age is 16 Format specifier.
In example 2, age is a variable of integer data type. Assume that the user
enters the value 16 for the variable age. To display the value of a variable on
the screen, the relevant format specifier must be specified within double
quotes.
Fundamentals of C Language 4.3-16
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Syntax
printf("<string> <format specifier>",<variable>);
Hands-On!
Program to accept an integer value from the user and display the value on the
screen.
/* Example program for I/O statements */
#include <stdio.h>
void main()
{
int age;
printf("\n Enter the age : ");
scanf("%d",&age); \n is used to display
the text in a new line.
printf("\n\n Age : %d",age);
}
Code Sample 4.3.2
Output
Enter the age : 18
Age : 18
Activity 4.3.7 (a)
Step 1: Open the data file A3_5.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3.
4. void main()
5. {
6. int index=1;
Fundamentals of C Language 4.3-17
Fundamentals of Programming Programming Concepts and Constructs (C Language)
7. float mark=55.5;
8. char grade='A';
9. clrscr();
10.
11. printf("\n Index = %d ",index);
12. printf("\n Mark = %f ",mark);
13. printf("\n Grade = %c ",grade);
14. }
Step 2: Run the program and observe the output.
Step 3: Identify the format specifiers used.
Activity 4.3.7 (b)
Step 1: Open the data file A3_6.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3.
4. void main()
5. {
6. int item_id=501;
7. float price=125.5;
8. char grade='A';
9. clrscr();
10.
11. printf("\n Item_id = __ ",item_id);
12. printf("\n Price = __ ",price);
13. printf("\n Grade = __ ",grade);
14. }
Step 2: Run the program and observe the output.
Step 3: Edit code line 11 as printf("\n Item_id = %d ",item_id);.
Step 4: Edit code line 12 as printf("\n Price = %f ",price);.
Step 5: Edit code line 13 as printf("\n Grade = %c ",grade);.
Step 6: Save the program.
Fundamentals of C Language 4.3-18
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Step 7: Run and observe the output.
Lab Exercise
Lab Exercise 2: Write a program to accept the customer id from the user and display the same
on the screen.
Lab Exercise 3: Write a program to accept the price of an item and display the same on the
screen.
Lab Exercise 4: Write a program to accept the grade of a student and display the same on the
screen.
Self-Check Exercise 4.3.2
1. Choose the correct statement. z is a character data type.
a. printf(z); b. printf("z");
c. printf("%d",z); d. printf("%c",z);
2. Choose the correct statement. y and z are floating-point data type.
a. scanf("%f %f",&y,&z); b. scanf("%d%d",&y,&z);
c. scanf("%f",&y,&z); d. Scanf("%f",&x, "%f",&z);
Escape Sequences
Definition: Escape sequences are nonprinting characters that are used for
formatting the output.
C provides various escape sequences to display the outputs on screen in the
specified formats. For example, the escape sequence \n will display the text
in a new line and \t will include horizontal tab spacing. Some commonly used
escape sequences are listed in Table 4.3.8.
Escape Sequence Description
\n Newline
\t Horizontal tab
\’ Apostrophe (‘)
\” Quotation (“)
%% Percentage (%)
Table 4.3.8: Escape Sequence
Fundamentals of C Language 4.3-19
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Hands-On!
Program to illustrate the use of the escape sequences.
/*Program to illustrate the use of the escape sequences*/
#include <stdio.h>
void main()
{
printf("Before using escape sequence");
printf("First line"); Without using escape
sequences.
printf("Second line");
printf("\n\nAfter using escape sequence ");
printf("\n\n\tFirst line"); Using escape
printf("\n\n\tSecond line"); sequences.
}
Code Sample 4.3.3
Output
Before using escape sequenceFirst lineSecond line
After using escape sequence
First line
Second line
Hands-On!
Program to illustrate the use of the escape sequences.
/*Program to illustrate the use of the escape sequences*/
#include <stdio.h>
void main()
{
printf(" Without using escape sequence");
printf(" Item Quantity Unit_price");
printf(" Basket ball 12 Rm24");
printf(" Tennis ball 12 Rm5");
Fundamentals of C Language 4.3-20
Fundamentals of Programming Programming Concepts and Constructs (C Language)
printf("\n\n\n Using escape sequence");
printf("\n\n Item\t\tQuantity\tUnit_price");
printf("\n\n Basket ball\t12\t\tRm24");
printf("\n Tennis ball\t12\t\tRm5");
}
Code Sample 4.3.4
Output
Without using escape sequence Item Quantity Unit_price
Basket ball 12 Rm24 Tennis ball 12 Rm5
Using escape sequence
Item Quantity Unit_price
Rm24
Basket ball 12 Rm5
Tennis ball 12
Activity 4.3.8 (a)
Step 1: Open the data file A3_7.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. clrscr();
6. printf("Welcome");
7. printf(" to ");
8. printf(" C Programming ");
9. }
Step 2: Run the program and observe the output.
Fundamentals of C Language 4.3-21
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Activity 4.3.8 (b)
Step 1: Open the data file A3_8.C. The following C statements will be
displayed on the screen.
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. clrscr();
6. printf(" Name ID");
7. printf(" Rahque Farim ");
8. }
Step 2: Run the program and observe the output.
Step 3: Edit code line 6 as printf("Name\tID");.
Step 4: Edit code line 7 as printf("\nRahque\tFarim ");.
Step 5: Save the program.
Step 6: Run and observe the output.
Self-Check Exercise 4.3.3
1. Choose the correct statement to display the string House in a new line
a. printf("%s", House); b. printf("/n House");
c. printf("\n House"); d. printf("House \n");
2. Choose the correct statement to display the string Trees in a new line within inverted
commas
a. printf("%s", Tree) b. printf("/n Tree ");
c. printf("\n " Tree ""); d. printf("\n \" Tree \"");
Lab Exercise
Lab Exercise 5: Write a program to display the following output on the screen.
I am in "Malaysia"
Lab Exercise 6: Write a program to display the following output on the screen.
Arvee's pen
Fundamentals of C Language 4.3-22
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Lab Exercise 7: Write a program to display the following output on the screen.
50% Discount Sale
4.3.5 Operators and Expressions
In some of the programs, you might need to perform some mathematical
calculations. Various operations such as adding two numbers, comparing two
numbers and so on need to be performed. Various operators and expressions
are used for this purpose.
4.3.5 (A) Expressions
Definition: An expression is any combination of operators and operands that
evaluates to a value.
Most statements that you write in a program will contain expressions. A
simple example of an expression is 2 + 3. An expression can be broken down
into operators and operands. C expressions can either be simple or complex.
(a) Simple Expressions
The simplest C expressions consist of a single item: a simple variable, a
constant. Table 4.3.9 gives example for simple expressions.
Expressions Descriptions
-35 a constant
quantity a variable
Table 4.3.9: Examples for Simple Expressions
(b) Complex Expressions
Complex expressions consist of simpler expressions connected by operators.
Example
4+12
In the example, the expression consist of sub-expression 4 and 12 and the
addition operator. The expression 4 + 12 evaluates to 16.
Fundamentals of C Language 4.3-23
Fundamentals of Programming Programming Concepts and Constructs (C Language)
4.3.5 (B) Operators
Definition: An operator is a symbol that instructs C to perform some
operation, or action.
In a program, for adding two numbers you need to use the addition (+)
operator. Similarly, for comparing two numbers you need to use a comparison
operator. It is therefore necessary to use the appropriate operators to perform
these calculations. For example, + is an operator that represents addition.
Example
c=a+b
In this code line, + is an operator and a, b and c are called operands.
Operands are the variables/constants on which the operators operate.
In C, all operands are expressions. C operators can be classified as:
Assignment operators
Mathematical operators
Relational Operators
Logical Operators
Assignment Operator
Definition: Assignment operator (=) is used to assign a value to a variable.
Example1
a = 10; Æ Value 10 is assigned to the variable a.
In example1, the value 10 is assigned to a.
In a C statement, the right side of the operator can be any expression, and the
left side must be a variable name. Thus, the form is as follows:
Variable = expression;
When executed, expression is evaluated, and the resulting value is assigned
to variable
Example2
x = y + z;
In example2, the sum of y and z is calculated and the result is stored in x.
Fundamentals of C Language 4.3-24
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Mathematical Operators
Definition: Mathematical operators are used for performing simple
mathematical calculations such as addition, subtraction, multiplication and
division.
The various Mathematical operators available in C are listed in Table 4.3.10.
Operator Operation Description Example
+ Addition Adds two operands. c=a+b
- c=a-b
Subtraction Subtracts an operand
* from another. c=a*b
Multiplication
/ Multiplies an operand c=a/b
Division with the other.
% c=a%b
Modulo Divides an operand by
another.
Calculates the
remainder when an
operand is divided by
another.
Table 4.3.10: Mathematical Operators
You must know how to convert a general mathematical notation to equivalent
C statement. Table 4.3.11 lists some of the examples of C expressions as
shown:
Mathematical Notation C Expression
xy x*y
a+b (a+b)/(a-b)
a-b
(pq)-(rt) (p*q)-(r*t)
Table 4.3.11: Mathematical Notations and Their Equivalent in C
Fundamentals of C Language 4.3-25
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Hands-On!
The following code illustrates the use of mathematical operator:
/* Program to add two numbers */
#include <stdio.h>
void main()
{
int x,y,sum;
x=10;
y=3;
sum=x+y;
printf("\n %d + %d = %d ",x,y,sum);
}
Code Sample 4.3.5
Output
10 + 3 = 13
Hands-On!
The following code illustrates the use of mathematical operators:
/* Program to calculate the average of three numbers */
#include <stdio.h>
void main()
{
int x,y,z,sum,avg;
x=1;
y=2;
z=3;
sum=x+y+z;
avg=sum/3;
printf("\n Average is : %d ",avg);
}
Code Sample 4.3.6
Output
Average is : 2
Fundamentals of C Language 4.3-26
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Activity 4.3.9
Write the equivalent C expressions for the given mathematical notations:
Mathematical Notation C Expression
(a+b)(a-b)
2x+3y
5x2+4x-1
a+b+c
3
m+n
m-n
x+y
yx
p+q * q
p-r
a*c+b
ba
2 + 3x + 4z
y
2 *y
(3 + x)
Lab Exercise
Lab Exercise 8: Write a program to accept the radius of a circle and find its diameter.
Hint: Diameter=2*radius.
Lab Exercise 9: Write a program to accept the length and width of a rectangle and find the
area.
Hint: Area=length* width.
Lab Exercise 10: Write a program to accept the length of a square and find the perimeter.
Hint: Perimeter=4*length.
Fundamentals of C Language 4.3-27
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Relational Operators
Definition: Relational operators are used to compare two operands.
The output of the expression will be a Boolean value, which is either 0 (false)
or 1 (true). The various relational operators are listed in Table 4.3.12.
Symbol Description Example
a>b
> Greater than
< Lesser than a<b
>= Greater than or equal a>=b
to a<=b
<= Less than or equal to a!=b
!= Not equal to a==b
== Equal to
Table 4.3.12: Relational Operators
Activity 4.3.10
Write the equivalent C expression for the following:
Description C Expression
x is greater than y
m is less than n
p is less than or equal to 50
q is greater than or equal to 80
(x+y) is greater than or equal to
z
a is not equal to 5
(a+b) is greater than (c+d)
Is q equal to 10
c is not equal to (a+b)
i is less than 100
Fundamentals of C Language 4.3-28
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Logical Operators
Definition: Logical operators are used to combine two simple statements into
a compound statement.
Using logical operators, you can simulate Boolean algebra in C. The various
logical operators are listed in Table 4.3.13.
Symbol Operation Description
&& AND Logical AND
|| OR Logical OR
! NOT Logical NOT
Table 4.3.13: Logical Operators
The AND (&&) operator will evaluate to true only if all the conditions in the
expression returns a true value.
Example
You will pass the exam only when you get more than 50 in subject 1,
subject 2 and subject3.
The OR (||) operator will evaluate to true even if one of the conditions is true.
Example
To get a medal, you should either be 1st or 2nd in the race.
The NOT (!) operator will evaluate to true if the condition fails and vice versa.
Example
If the month is April, the number of days is not equal to 31.
Fundamentals of C Language 4.3-29
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Activity 4.3.11
Write the equivalent C expression for the following:
Description C Expression
a is less than b and a is less than c
x is less than y or x is greater than
z
p is less than 40 and q is greater
than 70
Is m equal to 90 or n is greater
than 10
i is greater than or equal to 10 and
is j equal to 20
a is greater than b and a is greater
than c
i divided by 2 is not equal to 0
m is greater than 0 or m is less
than 100
Is x equal to y and x is less than z
a is less than b or a is less than c
4.3.5 (C) Operator Precedence
Definition: Precedence refers to the priority given to each operator.
The expression is evaluated in the order of priority given to the operators in it.
Thus an operator that has the highest priority is evaluated first.
Table 4.3.14 lists the order of precedence of the operators:
Fundamentals of C Language 4.3-30
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Table 4.3.14: Operator Precedence
The following example will help you to understand this concept:
Example 1
Fundamentals of C Language 4.3-31
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Example 2
The examples clearly explain the step-by-step evaluation of the expression
following the order of precedence.
Fundamentals of C Language 4.3-32
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Activity 4.3.12
Evaluate the following expressions when x=1, y=2 and z=3:
C Expression Output
x+y+z
z-y-x
z-y+x
2*x+y
y*z/x
z/x-y
(y+z)/x
(x+z)/(y+x)
(x+y+z)/z
((x+y)*(y+z))/(y+z)
Best Programming Practise
When you have long expressions in a program, it is better to use brackets for evaluating the
expression easily.
Technical Terminologies
Assignment operator – Operator that is used to assign a value to a
variable.
Comments – Describe the entire program or specific lines of
code in the program.
Compilation – The process of conversion of high-level language
into machine language.
Compilers – Programs, which convert a high-level language
program into machine level language program.
Constant – Location in the memory that stores data that never
changes during the execution of the program.
Data type – Defines the type of the value to be stored in the
memory.
Fundamentals of C Language 4.3-33
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Escape sequences – Nonprinting characters that are used for formatting
the output.
Execution – The process of running the program to get the
desired output.
Expression – Any combination of operators and operands that
evaluates to a value.
Format specifier – Defines the data type of the variable to the
compiler.
Identifiers – The names given to the variables.
Keywords – Reserved words for which the meaning is already
defined to the compiler.
Logical operators – Combines two simple statements into a compound
statement.
Mathematical
operators – Operator used for performing simple mathematical
calculations such as addition, subtraction,
multiplication and division.
Operands – The variables on which the operators operate.
Operator – A symbol that instructs C to perform some
operation, or action.
Precedence – Priority given to each operator.
Preprocessor
directives – The instructions given to the compiler.
Relational operators – Operators that are used to compare two operands.
Statement – An instruction written in high-level language.
Syntax – The rules to be following when writing a program.
Variable – The name given to the memory location where the
data is stored, that keeps changing during the
program execution.
Summary
In this unit, you learnt the following:
Dennis Ritchie, at AT & T Bell Laboratories in New Jersey,
developed the C language.
Comments are for describing the entire program or specific lines of
code in the program.
Preprocessor directives are the instructions given to the compiler.
A header file contains definition for all the functions that could be
shared by several other programs.
Fundamentals of C Language 4.3-34
Fundamentals of Programming Programming Concepts and Constructs (C Language)
The main function is the most important function, which must be
present in a program.
Compilers are programs, which convert a program written in high-
level language into machine level language program. This process
is called as compilation.
Execution is the process of running the program to get the desired
output.
The basic elements that are used in constructing simple C
statements are C Character set, Variables, Constants, Data types
and Keywords.
A character or set of characters is used to represent any
information.
Data type will define the type of the value to be stored in the
memory.
Variable is the name given to the memory location where the data is
stored, that keeps changing during the program execution.
Keywords are reserved words for which the meaning is already
defined to the compiler.
Constant is a location in the memory that stores data that never
changes during the execution of the program.
scanf() is the basic input function used to accept value from the
user.
printf() is the basic output function used to display data on the
screen.
Format specifier defines the data type of the variable to the
compiler.
Escape sequences are non-printing characters that are used for
formatting the output.
An expression is any combination of operators and operands that
evaluates to a value.
An operator is a symbol that instructs C to perform some operation,
or action.
Operands are the variables/constants on which the operators
operate.
Types of operators in C are:
o Assignment operator.
o Mathematical operators.
o Relational operator.
o Logical operator.
Mathematical operators are used for performing simple
mathematical calculations such as addition, subtraction,
multiplication and division.
Fundamentals of C Language 4.3-35
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Relational operators are used to compare two operands.
Logical operators are used to combine two simple statements into a
compound statement.
Precedence refers to the order of priority given to each operator.
This is to control the order in which the expression is evaluated.
Assignments
1. Describe the structure of a C program with an example.
2. Write a program to accept two numbers and calculate their product.
Display the result.
3. Write a program to accept the height and base of a right-angled
triangle. Calculate the area of the triangle. (Tip: area =
(½)*base*height).
4. Write a program to display the following text on the screen:
My name is "<name>"
5. Write short notes on various operators in C.
Fundamentals of C Language 4.3-36
Fundamentals of Programming Programming Concepts and Constructs (C Language)
Criterion Referenced Test
Instruction: Students must evaluate themselves to attain the list of
competencies to be achieved
Name:
Subject: Fundamentals of Programming
Unit : Fundamentals of C Language
Please tick [ ] the appropriate box when you have achieved the respective
competency
Date Fundamentals of C Language
C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11
Comment
Competency codes:
C1 = Identify the 5 or exact number components in the structure of a C
programs.
C2 = Compile and execute C programs.
C3 = Write simple C programs using data types and variables.
C4 = Identify the 5 basic elements in C language.
C5 = Construct valid identifiers.
C6 = List the data types available in C language.
C7 = Identify the keywords in C language.
C8 = Identify the basic input and output statements.
C9 = Write programs to accept data and display the data in the specified
format (using any 3 escape sequences).
C10=Write mathematical expressions, relational and logical expressions for
the given description.
C11 = Evaluate expression by applying operator precedence.
Fundamentals of C Language 4.3-37