Chapter 5 - C PROGRAMMING LANGUAGE USS
Chapter 5 - C PROGRAMMING LANGUAGE USS
Learning objectives : after studying this lesson , the students should be able : give the
structure of C program ; translate a program written in pseudo code into C language.
5.1. Introduction
C is one of the most widely used languages in the world, it was developed in 1972 by Denis
Ritchie at the Bell Telephone Laboratories for use with Unix and LINUX operating systems.
Since its creation in 1972, it's been used for a wide variety of programs including firmware for
micro -controllers, operating systems, applications, and graphics programming.
Page | 1
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
A. Documentation section:
To enhance the readability of the program, programmers can provide comments about the
program in this section. Comments can be used anywhere in the program. It indicates the
purpose of a program or a portion of code. The comments can be inserted with a single
statement or more.
Examples
// This is a single line comment
/*This is a multiple lines comments*/
From above example: line 1
B. Header file section / preprocessor command
C program depends upon some header files for function definition that are used in program. A
header file contains the information required by the compiler when calls to the library functions
used in the program occur during compilation. Each header file by default is extended with“.h”
The file should be included using #include directive.
Example: line 2
#include<stdio.h> or #include “stdio.h”
In this example <stdio.h> file is included i.e. all the definitions and prototypes of
functions defined in this file are available in the current program. This file is compiled
with original program.
C math functions : examples- Sqrt( ) returns the square root of an integer ; pow( ) returns the
value of x to the power of y (yx) are included in the library function file “math.h”
Page | 2
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
Some examples of correct variable names are: Temp, CostPrice, Selling_Price, HEIGHT.
Note: character may be a letter of the alphabet (A-Z), a symbol( #,%,$). a digit.
Initialization of variable
Constants
Constants A constant is a value that doesn’t change during the execution of a program. These
are generally declared before main function. Type of constant include:
Integer constant: Numeric value without decimal part is called integer constant.
Real constant: Numeric value with decimal part is called. Example: 5.0, - 98.76…
Character constant: A single character enclosed in single quotes.
Declaration of a constant
Syntax: const data type constant_name= value;
Example: const float PI=3.14159;
String constant: A single character or a group of characters enclosed in double quotes is called
string constant. Example: “5” , “temperature”
C Keywords are also known as reserved words. These keywords are only to be used for
their intended purpose and as identifiers. All the Keywords are written in lowercase.
Some of the keywords are summarized in the table below.
Char Double String Break Return Scanf char
Getchar Int Pow Long Goto Printf Getchar
Page | 4
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
5.3. Operators
Operators are C tokens which can join together individual constants, variables, array elements
and functions references.
C operators are classified into following categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
A. Arithmetic Operators
Here We consider the value of A is 10 and B is 7.
D. Logical operators
Page | 6
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
G. Bitwise operators
Bitwise operators are similar to that of logical operators except that they work on binary numbers
(bits). When bitwise operators are used with variables, they are internally converted to
binary numbers and then bitwise operators are applied on individual bits. These operators
work with char and int data types. They cannot be used with floating point numbers.
Example: if a=4, b=6; The equivalent binary value of a is 0000 0100 The equivalent binary
value of b is 0000 0110: ( see table below)
Bitwise operators Actions Examples
& Bitwise AND The value of a&b = 0 0 0 0 0 1 0 0
| Bitwise OR The value of a|b = 0 0 0 0 0 1 1 0
^ Bitwise exclusive OR The value of a^b = 0 0 0 0 0 1 0 1
<< Shift left a<<2. It left shifts the binary bits twice.
Therefore a= 0 0 0 1 0 0 0 0.
>> Shift right
~( unary) Ones complement
Page | 7
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
This selection control statement is used when two Options are available;
The syntax :
if (condition )
{
statement 1 ;
statement 2;
}
else
{
Statement n ;
}
If the condition is true (1 ), the first block of statement is executed. If it is false (0), the second block of
statement is executed( after the else).
For example : the C program below takes a number as input and tells whether a number is
positive, negative . Braces are not required if you have only one statement per block.
IF ( Num > 0)
Printf( “ The Number Entered is Positive ”);
ELSE
Printf( “ The Number Entered is a Negative ”);
C. Else-if ladder Statement
The else-if ladder is used when multipath decisions are involved. FLOWCHART
Syntax: if (condition-1)
Statement-1 ;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
………………
else
Statement-x ;
Page | 10
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
Example:
#include<stdio.h>
void main( )
int avg;
{
if(avg>=70)
printf(“ distinction”);
else if(avg>=60)
printf(“ first class”);
else if(avg>=50)
printf(“second class”);
else if(avg>=40)
printf(“third class”);
else
printf(“fail”);
}
D. Case control statement( switch-case)
At times, the if condition may increases the complexity of the program when one of many alternatives
is to be selected. C The switch statement requires only one argument variable or expression.
It tests the value of a given variable against a list of case values and when a match is found, a block of
statements associated with that case is executed, if not such match, then default statement is
executed.
The default is an optional case when present. It will be executed if the value of the
expression doesn’t match with any of the case values.
The expression is an integer expression or character. Value-1, value-2 are either integer constants or
character constants. These values should be unique with in a switch statement. Case labels end
with colon ( : ).
Syntax:
switch(variable or expression)
{
case value-1: block-1
break;
case value-2: block-2
break;
..
..
default: default-block
}
next statement.
Page | 11
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
The break statement signals the end of a particular case and causes an exit from the
switch statement, transferring the control to the next statement following the switch.
EXAMPLE:
switch(op)
{
case ‘+’: c=a+b;
break;
case ‘-’: c=a-b;
break;
case ‘*’: c=a*b;
break;
case ‘/’: c=a/b;
break;
default: printf(“wrong option”);
}
5.4.4. Loop Control statements
The loop statement is used when the program needs to perform repetitive tasks.
Steps in loops:
1. Loop variable: It is a variable used in loop to evaluate.
2. Initialization: It is the step in which starting value or final values are assigned to the loop variable.
3. Test-condition: It is to check the condition to terminate the loop. It is any relational expression with
the help of logical operators.
4. Update statement: It is the numerical value added or subtracted to the loop variable in each round of
the loop.
C language supports three types of loop control statements. While, do-while and For
a. While statement ( pre – test loop)
It allows a program to repeat a section of code any number of times , until some condition occurs.
This is the simplest looping structure in C. the while is an entry-controlled loop statement.
Syntax:
initial statement ;
while(test condition)
{
Statement(s) ;
Update statement;
}
The program will repeatedly execute the statements inside the while loop until the condition becomes false (0).
Page | 12
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
main( )
{
int i,sum;
i = 1; // initial staement
sum=0;
while (i<=10)
{
sum = sum + i ;
i + +; // update statement
}
printf(“sum=%d”,sum);
}
Here the value, sum of first ten numbers is stored into the variable sum; i is the loop
variable.
The loop is repeated for ten times to do that process, each time by incrementing the value of i by one.
Once the value of i becomes 11 then the test condition becomes false and the control is out of the loop.
b. Do while statement
On some occasions it might be necessary to execute the body of the loop before the test
condition is performed. Such situations can be handled by the do -while statement. Do
while id exit controlled loop statement.
Syntax:
do
{
Statement(s) ;
Update statement ;
while(test condition);
}
next statement
(Post-test Loop)
The body of the loop is executed first, and then at the end of the loop the test
condition is evaluated, if it is true then the statements are executed once again. The process of
execution continues until the test condition finally becomes true.
Page | 13
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
Example:
main()
{
int i, sum;
i =1; // initial statement
sum=0;
do
{
sum = sum + i;
i + +; // update statement(incrementation)
} while( i<=10);
printf(“Sum=%d”, sum); //
}
c. For loop statement
Trace Table
The for statement allows the programmer to execute a block of code for a
Count Even Output
specified number of times. 1 2 2
The syntax : 2 4 4
for ( initialization; test condition; incrementation / decrementation) 3 6 6
4 8 8
{ statement(s);
} 5 10 10
6 12 12
Example : this portion of C code Prints the first 10 even numbers. 7 14 14
for( count=1; count<=10; count++) 8 16 16
{ even = 2*count; 9 18 18
d. Nesting Loops
The way if statement can be nested, similarly whiles and for can also be nested.
Example:
for(i=1;i<=3;i++) //outer for loop
{
for(j=1;j<=2;j++) // inner for loop
{
Printf(“\t %d %d”, i, j);
}
Printf(“\n”);
}
Here in this example nested for loop is used, and the total process is executed for 6( 3 * 2) times.
Page | 14
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
The way for loops have been nested here, similarly while and do-while can also be nested. Not
only this, a for loop can occur within a while loop, or a while within a for.
Page | 15
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]
Exercise1: The C program below finds the average of two numbers entered by a user.
1. This program contains 4 syntax errors ; underline the errors.
1. #include <stdio.h>
2. int main()
3. {
4. int num1, num2;
5. float avg
6. printf("Enter first number: ");
7. scanf("%d",&num1);
8. printf("Enter second number: ");
9. scantf("%d",&num2);
10. avg =(Num1+num2)/2;
11. printf("Average of %d and %d is: %.2f",num1,num2,avg);
12. return 0,
13. }
Exercise2: .the Pseudo code below determines the double of a number entered as input.
BEGIN
WRITE “ Please Enter an integer number”
READ n
Double1 = num*2
PRINT double1
END
1. State the data types of the variables used in this pseudo code.
Variable name Data type
n ________________
double1 ________________
2. Translate the pseudo code above into a C Program.
Exercise 3: Write a C Program to find the area of a circle, This C program gets radius as user
inputs and computes the area of a circle.
The area of a circle is given by the formula: Area of a Circle = pi * radius*radius
Exercise4: consider the pseudo code below, for the Profit and Loss of items bought.
1. Complete the C program on the left
2. Underline the instruction line which declare variables. Name the variables used with the data type.
Page | 16
Mr HOYOKSOU GOLSIA BLAISE ROUL