0% found this document useful (0 votes)
7 views16 pages

Chapter 5 - C PROGRAMMING LANGUAGE USS

Uploaded by

golsiaraoul9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Chapter 5 - C PROGRAMMING LANGUAGE USS

Uploaded by

golsiaraoul9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

LESSON 5: C PROGRAMMING LANGUAGE( part1)

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.

5.2. Structure of a C program


Every C program contains a number of several building blocks known as functions. Each
function of it performs task independently. A function is subroutine that may consists one or
more statements.
Example of a Simple C program.
/* This is a comment */
1. #include <stdio.h>
2. Int main(void)
3. {
4. print f(“ Welcome to C programming. “);
5. Return 0;
6. }
The output is : welcome to C programming.

The structure of a C program is shown below:

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]

C. Global declaration section:


This section declares some variables that are used in more than one function. These variables
are known as global variables. These must be declared outside of all the functions.
D. Main function
Every program written in C language must contain main( ) function. The function main (
) is starting point of every ‘C’ program. The execution of the program always begins
with the function main( ). With int main( ), the main function return an integer (0) at the end
of the function.
E. Declaration part
Informally, a variable (also called an object) is a place where you can store a value. C allows us
to store values in variables and each variable is identified by a its name. The initialization of
variables is also done here. The initialization means providing the initial value to the variable.
Example of declaration and initialization of a variable int a = 10;
F. User defined Functions
The function defined by the user is called user defined function. These functions are generally
defined after the main( ) function. They can also be defined before main() function. This
portion in not compulsory.
5.1. Variables and constants
Before you can use a variable in C, it must be defined in a declaration statement .
A declaration of a variable tells the compiler the name and type of a variable you'll be using in
your Program.
Rules & conventions for naming the variables:
There are just a couple of rules to follow when naming your variables:
 Variable name can contain letters, numbers, and the underscore
 Variable name cannot contain space.
 Variable name cannot start with a number, but can contains a number.
 Variable name cannot be a keyword /reserved word( e.g INT, PRINTF, etc…)
 Variable should always be declared at the beginning of a function.
 Case matters – for instance, temp, Temp and TEMP are three different variables.
The following are not correct variable names:
 3rd_entry /* Begins with a number */
 all$done /* Contains a "$" */
 the end /* Contains a space */
 int /* Reserved word */
Page | 3
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

Some examples of correct variable names are: Temp, CostPrice, Selling_Price, HEIGHT.

The syntax of a variable declaration is:


Type variable name; The type of a variable determines what kinds of values it may take.

Example data type Description


int age ; Integer Age contains a whole number eg 15, 20 etc.
float height; Real number Height contains a number with a decimal point e.g 5.7
char sex; Character sex contains a single character eg.“F” , “M”
char name[5] String Name contains a set of 5 characters maximum e.g “ PAUL”

Note: character may be a letter of the alphabet (A-Z), a symbol( #,%,$). a digit.
Initialization of variable

Syntax: data type variable_name(s) = value;


Example: int x=5;
Here x is a variable which holds a value=5;

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.2. Assignment statements


An Assignment statement is used to give a variable a value. The syntax :
Variable_name = expression or Value;
For example: answer = (1 + 2) * 4;
The variable answer on the left side of the equals operator (= ) is assigned the value of the
expression (1 + 2) * 4 . So the variable answer gets the value 12. as illustrated in Figure 4 -1B
The semi-colon (;) ends the statement.

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.

Operator Meaning Example Meaning of example and results


* Multiply 10*2; 20
/ Divide 10/5; 2
+ Add A+2; 12
- Subtract A-B; 3
^ Exponent 5^3; 5*5*5 = 25
% Modulo division ( remainder of a A%B ; 10% 7 it gives 3 ( remainder of 10
division of two integers) divided by 7)
Page | 5
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

B. Incrementation and decrementation Operators

++ Incrementation by 1 A++ ; A=A+1; it gives 11


-- Decrementation by 1 B-- ; B= B-1; it gives 6

C. Relational Operators or (comparison operators)

Relational operators Meaning Examples


< Less than 38<4 = 0 false
<= Less than or equal to 38>4 =1 true
> Greater than If (mark >=10 )
Printf (“ you have passed”);
>= Greater than or equal to
Else
== Equal to
Printf (“ you have failed”);
!= Not equal to

D. Logical operators

Relational Examples Description


Meaning
operators
Example1: if a=10, b=5, c=15 The result of the logical AND
i=(a>b)&&(b<c); The value of i expression will be true only when the
&& Logical AND
in this expression will be 1. both relational expressions are true.

Example1: if a=10, b=5, c=15


The result of logical OR expression
i=(a<b)|| (b>c); The value of i
|| Logical OR
in this expression will be 0.
will be true only when either
expression( operand ) is true.
Example: x=20
i = !(x==20) The value of i will the result of the expression will be
! Logical NOT be 0. This is because x==20 is true, if the expression is false and
true(value 1). vice versa.

 Logical expression combines two or more relational expressions.


 Logical operators are used to test more than one condition and make decision.

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

5.4. Input and output Statements.


Let us study the C program below

Pseudo code C program 2


/* this program calculates the cube of a number*/
#include<stdio.h>
BEGIN int main(void)
Variables num, cube : integer {
Coding int num, cube; // Declaration of variables num & cube
PRINT “ enter number ” printf("Enter a Number:");
READ Num scanf("%d",&num);
cube = num * num*num cube =num*num*num;
PRINT cube printf("the cube of %d is %d \n:",num,cube);
.................................... return 0;
END }
……………………………………………..PR
INT “ The double of Num is, Double”

Page | 7
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

5.4.1. Input statements ( function Scanf )


The Scanf statement reads an input value and stores it in the specified variable.
The general form of the scanf( ) statement
scanf (“format specifier,&variable name);
format specifier are used to identify the data type to read or written into variables.
Example : scanf(“%d”, &width); means that The value entered by the user is read and stores in
the variable width. if scanf( ) has to read multiple values from keyboard then all format
specifiers are grouped to form format string as show below
example: scanf("%d%%d%d",&v1,&v2,&v3);
The above example reads three integers one by one from keyboard into variable v1,v2,v3
respectively
Format specifier Meaning
%d Input value is an integer
%ld Long integer
%f Input value is a floating point number ( real number)
%c Value is a single character
%s the input is a string of character. Such as a word.

The Pseudo code statement “ READ num ” is translated in C statement as Scanf(“%d”,&num);


List of commonly used symbols in C language:
Symbol { } # ; ( ) , $ & %
Name Curly braces Hash Semi colon Brackets Comma Dollar And Modulo

5.4.2. Output statement: printf ( )


The printf( ) function is used to print a message or the result of an operation on the screen.
Example : Printf( “ Enter a Number:”); this instruction prints Enter a Number on the
screen.
1. The printf ( ) statement for printing message is:
Syntax:
Printf(“ text to be printed on the screen”) ;
any text between the double quote “ ” Will appear on the screen as it is typed.
2. The printf ( ) statement for for printing results of an operation:
printf( “text printed format specifier1 format2 format n ” , variable1 , variable 2,variable n);
Page | 8
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

Example: consider the statement from the C program above,


Printf(“the cube of %d is %d, num, cube ); if the user enters 10 for the value of Num then
the ouput is:
The cube of 10 is 1000
Explanation:
Printf(“the cube of %d I is %d , Num, cube );

Format section expression section


The values of the Variables Num and cube will be printed in place of %d. %d.
%.2f the number is printed with two digits after the decimal point. For float data types.
Backslash Character constants: C supports some special backslash character constants that are
used in output functions. These are also known as escape sequences.
“\n ” new line – it moves the cursor to the beginning of the next line.
“\t ” tabulation – it moves the cursor to more than one space forward
“\a” audible alert
“ \b” backspace.
5.4.3. Selection statements
This programming construct is used when an action should be executed based on a condition
that is true or false.
A. The IF statement
The syntax :
if (condition )
{
Statement1;
Statement n;
}
If the condition is true (nonzero), the statements will be executed. If the condition is false (0), the
statements will not be executed. For example , suppose we are Writing a program to Award
Honour Rolls to the students with an Average score of 12 and Above. It will award only those
students and ignored the rest. In C, this program is written:
if ( Average >= 12)
{ Printf( “Honour Roll Awarded”);
}
Page | 9
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

Comparison and logical operators.


These operators are used for making a condition in decision and loop statements ; to compare different
values.( see page 6 )
B. IF……………ELSE Statement

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

printf(" % d\n", even);


}

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.

Appendix. Summary on data type.

Page | 15
Mr HOYOKSOU GOLSIA BLAISE ROUL
TOPIC: ALGORITHM AND PROGRAMMING [C PROGRAMMING LANGUAGE]

END OF CHAPTER QUESTIONS

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. }

2. Fill in the table below


statement line number Syntax errors Correction

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

You might also like