SlideShare a Scribd company logo
STRUCTURED PROGRAMMING (USING C
PROGRAMMING)
Mr. Stephen Njuguna
DEFINITION OF TERMS
DEFINATION TERMS
• HEADER FILE - A header file is a file with extension .h which contains C
function declarations to be shared between several source files. A
header file is used in a program by including it with the use of the
preprocessing directive #include, which comes along with the compiler.
#include<stdio.h>
• PREPROCESSOR DIRECTIVES are lines included in a program that begin
with the character #, which make them different from a typical source
code text. They are invoked by the compiler to process some programs
before compilation. Preprocessor directives change the text of the
source code and the result is a new source code without these
directives.
DEFINATION TERMS
• EXPRESSION – These are statements that return a value. Expressions
combine variables and constants to create new values or logical
conditions which are either true or false e.g.x + y, x <= y etc
• KEYWORD - A keyword is a reserved word in C. Reserved words may
not be used as constants or variables or any other identifier names.
Examples include auto, else, Long, switch, typedef, break etc
• IDENTIFIER - A C identifier is a name used to identify a
variable, function, or any other user defined item. An identifier
starts with a letter A to Z or a to z or an underscore _ followed by
zero or more letters, underscores, and digits (0 to 9). C does not
allow punctuation characters such as @, $, and % within
identifiers.
DEFINATION TERMS
• IDENTIFIER - A C identifier is a name used to identify a
variable, function, or any other user defined item. An identifier
starts with a letter A to Z or a to z or an underscore _ followed by
zero or more letters, underscores, and digits (0 to 9). C does not
allow punctuation characters such as @, $, and % within
identifiers.
• COMMENT - These are non-executable program statements
meant to enhance program readability and maintenance- they
document the program.
• FUNCTION - A function is a group of statements, enclosed
within curly braces, which together perform a task.
DEFINATION TERMS
• STATEMENT - Statements are expressions, assignments, function
calls, or control flow statements which make up C programs.
Statements are terminated using a semicolon.
• SOURCE CODE – Program instructions in their original form. C
source code files have an extension .c
• OBJECT CODE – Code produced by a compiler from source code
and exists in machine readable language.
• EXECUTABLE FILE – Refers to a file in a format that a
computer can directly execute and is created by a compiler.
DEFINATION TERMS
• STANDARD LIBRARY – Refers to a collection of precompiled
functions/routines that a program can use. The routines are stored
in object format and contain descriptions of functions to perform
I/O, string manipulations, mathematics etc.
• SIGNED INTEGER – This is an integer that can hold either
positive or negative numbers.
• COMPILER – This is a program that translates source code into
object code.
• PREPROCESSOR COMMAND - The C preprocessor modifies
a source file before handing it over to the compiler for instance by
including header files with #include as I #include <stdio.h>
DEFINATION TERMS
• LINKER/Binder/Link Editor – This is a program that combines
object modules to form an executable program. The linker
combines the object code, the start up code and the code for library
routines used in the program (all in machine language) into a
single file- the executable file.
• OPERATOR - A symbol that represents a specific action. For
example, a plus sign (+) is an operator that represents addition.
The basic mathematic operators are + addition, - subtraction,*
multiplication, / division.
DEFINATION TERMS
• OPERAND - Operands are the objects that are manipulated by
operators in expressions. For example, in the expression 5 + x, x
and 5 are operands and + is an operator. All expressions have at
least one operand.
• EXPRESSION – This is a statement that returns a value. For
example, when you add two numbers together or test to see
whether one value is equal to another.
• VARIABLE - A variable is a memory location whose value can
change during program execution. Variable declaration must have
a type, which defines what values that variable can hold.
DEFINATION TERMS
• VARIABLE - A variable is a memory location whose value can
change during program execution. Variable declaration must
have a type, which defines what values that variable can hold.
VARIABLE RULES
• A variable can have alphabets, digits, and underscore.
• A variable name can start with the alphabet, and underscore
only. It can't start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword,
e.g. int, goto , etc.
• A Variable must have a type, which defines what values that variable
can hold.
DEFINATION TERMS
• DATA TYPE – The data type of a variable etc determines the
size and layout of the variable’s memory; the range of values
that can be stored within that memory; and the set of
operations that can be applied to the variable.
• CONSTANT - a constant is a value that never changes
during program execution.
DEFINATION TERMS
• WHITESPACE
• A line containing only whitespace, possibly with a comment, is
known as a blank line, and a C compiler totally ignores it.
• Whitespace is the term used in C to describe blanks, tabs, newline
characters and comments.
• Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement,
such as int, ends and the next element begins.
• Therefore, in the following statement: int age; There must be at
least one whitespace character (usually a space) between int and
age for the compiler to be able to distinguish them.
• On the other hand, in the following statement.
STRUCTURE OF A C PROGRAM
•The C programming language was designed by
Dennis Ritchie as a systems programming language
for Unix.
•A C program basically has the following structure:
• Preprocessor Commands
• Functions
• Variable declarations
• Statements & Expressions
• Comments
STRUCTURE OF A C PROGRAM
1.Example:
2.#include <stdio.h>
3.int main()
4.{
5.//SINGLE LINE COMMENT
6./* My first program*/
7.printf("Hello, World! n");
8.return 0;
9.}
Exercise 1
Sample 1
Program to allow the User to enter his or her name:
#include<stdio.h>
int main()
{
char name[20];
printf("Enter Your Name : ");
scanf("%s",&name);
printf("Your name is : %s", name);
getch();
return 0;
}
Sample 2
Program to allow the User to enter his or her name:
• #include<stdio.h>
• int main()
• {
• char name[25];
• printf("Enter Your Full Names: ");
• gets(name);
• printf("nWelcome %s to C programmingn",name);
• return 0;
• }
Exercise 1
Sample 3
Program to allow the User to enter his or her name:
• #include<stdio.h>
• #include<stdlib.h>
• int main()
• {
• char name[25];
• printf("Enter Your Full Names: ");
• gets(name);
• system("cls");
• printf("nHere is your full namesn");
• puts(name);
• return 0;
Exercise 2
Program to request user for radius and the calculate both Area and Circumference of a circle:
Sample 1
• #include<stdio.h>
• int main()
• {
• float r, area,circ;
• printf("Enter the radius of a circle=> ");
• scanf("%f",&r);
• area=3.14*r*r;
• circ=2*3.14*r;
• printf("Area: %fnnCircumfrence: %fnn",area,circ);
• return 0;
• }
Exercise 2
Program to request user for radius and the calculate both Area and Circumference of a circle:
Sample 2
• #include<stdio.h>
• int main()
• {
• float r, area,circ,pie=3.14;
• printf("Enter the radius of a circle=> ");
• scanf("%f",&r);
• area=pie*r*r;
• circ=2*pie*r;
• printf("Area: %fnnCircumfrence: %fnn",area,circ);
• return 0;
• }
Exercise 2
Program to request user for radius and the calculate both Area and Circumference of a circle:
Sample 3
• #include<stdio.h>
• #define PIE 3.14 //Constant defined
• int main()
• {
• float r, area,circ; //variable declaration
• printf("Enter the radius of a circle=> ");
• scanf("%f",&r);//reading a float value to be radius
• area=PIE*r*r;
• circ=2*PIE*r;
• printf("Area: %fnn Circumfrence: %fnn",area,circ);
• return 0;
• }
Exercise 2
• Program to request user for radius and the calculate both Area and Circumference of a circle:
Sample 4
• #include<stdio.h>
• #include<math.h>
• #define PIE 3.14 //Constant defined
• int main()
• {
• float r, area,circ; //variable declaration
• printf("Enter the radius of a circle=> ");
• scanf("%f",&r);//reading a float value to be radius
• area=PIE*pow(r,2);
• circ=2*PIE*r;
• printf("Area: %fnn Circumfrence: %fnn",area,circ);
• return 0;
• }
Preprocessor Commands
• These commands tell the compiler to do preprocessing before doing actual compilation. Like
#include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file
before going to actual compilation. The standard input and output header file (stdio.h) allows the
program to interact with the screen, keyboard and file system of the computer.
• NB/ Preprocessor directives are not actually part of the C language, but rather instructions from
you to the compiler.
Functions
• These are main building blocks of any C Program. Every C Program will
have one or more functions and there is one mandatory function which is
called main() function. When this function is prefixed with keyword int, it
means this function returns an integer value when it exits. This integer value
is retuned using return statement.
• The C Programming language provides a set of built-in functions. In the
above example printf() is a C built-in function which is used to print anything
on the screen.
• A function is a group of statements that together perform a task. A C
program can be divide up into separate functions but logically the division
usually is so each function performs a specific task.
Functions
• A function declaration tells the compiler about a function's name, return
type, and parameters.
• A function definition provides the actual body of the function.
• The general form of a function definition in C programming language is as
follows:
Functions
• return_type function_name( parameter list )
• {
• body of the function/Function definition
• }
Function Example1:
• #include<stdio.h>
• int addition(int x,int y);//Function Declaration
• int addition(int x,int y)
• {
• int sum;
• sum=x+y;
• return sum;
• }
• int main()
• {
• int a,b;
• printf("Enter number 1: ");
• scanf("%d",&a);
• printf("Enter number 2: ");
• scanf("%d",&b);
• printf("The Sum of the two Numbers is: %dn",addition(a,b));
• }
Function Defination
VARIABLES
• A variable is a memory location whose value can change during
program execution. In C a variable must be declared before it can be
used.
• Variable Declaration
• Declaring a variable tells the compiler to reserve space in memory for
that particular variable. A variable definition specifies a data type and
the variable name and contains a list of one or more variables of that
type .Variables can be declared at the start of any block of code. A
declaration begins with the type, followed by the name of one or more
variables. For example, Int high, low;
• int i, j, k;
• char c, ch;
• float f, salary;
Variable Declarations
• Variables can be initialized when they are declared. This is done by
adding an equals sign and the required value after the declaration.
• Int high = 250; /*Maximum Temperature*/
• Int low = -40; /*Minimum Temperature*/
• Int results[20]; /* series of temperature readings*/
• In C, all variables must be declared before they are used. Thus, C is a strongly
typed programming language. Variable declaration ensures that appropriate
memory space is reserved for the variables.
• Variables are used to hold numbers, strings and complex data for manipulation
e.g.
• Int x;
• Int num; int z;
TYPES OF VARIABLES
•The Programming language C has two main
variable types
• Local Variables
•Global Variables
Local Variables
• A local variable is a variable that is declared inside a function.
• Local variables scope is confined within the block or function where
it is defined. Local variables must always be defined at the top of a
block.
• When execution of the block starts the variable is available, and
when the block ends the variable 'dies’.
Global Variables
• Global variable is defined at the top of the program file and it can be
visible and modified by any function that may reference it. Global
variables are declared outside all functions.
Sample Program.
• #include <stdio.h>
• int area; //global variable
• int main ()
• {
• int a, b; //local variable
• /* actual initialization */
• a = 10;
• b = 20;
• printf("t Side a is %d cm and side b is %d cm longn",a,b);
• area = a*b;
• printf("t The area of your rectangle is : %d n", area);
• return 0;
• }
Inputing Numbers From The Keyboard Using Scanf()
• Variables can also be initialized during program execution (run time). The scanf() function is used to read
values from the keyboard. For example, to read an integer value use the following general form:
• scanf(“%d”, &var_name)
• As in
• scanf(“%d”, &num)
• The %d is a format specifier which tells the compiler that the second argument will be receiving an
integer value.
• The & preceding the variable name means “address of”. The function allows the function to place a value
into one of its arguments. The table below shows format specifiers or codes used in the scanf() function
and their meaning.
TYPE CASTING
• When used in a printf() function, a type specifier informs the function that a different type
item is being displayed.
• Type casting is a way to convert a variable from one data type to another. For example, if
you want to store a long value into a simple integer then you can type cast long to int. You
can convert values from one type to another explicitly using the cast operator as follows:
• (type_name) expression
• Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation:
• #include <stdio.h>
• main()
• {
• int sum = 17, count = 5;
• double mean;
• mean = (double) sum / count;
• printf("Value of mean is %d n", mean );
• }
C PROGRAMMING OPERATORS
• Operator is the symbol which operates on a value or a variable
(operand). For example: + is an operator to perform addition.
• 1. Arithmetic Operators
• 2. Increment and Decrement Operators
• 3. Assignment Operators
• 4. Relational Operators
• 5. Logical Operators
• 6. Conditional Operators
• 7. Bitwise Operators
• 8. Special Operators
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
SAMPLE PROGRAM
• #include <stdio.h>
• int main(){
• int c=2;
• printf("%dn",c++); /*this statement displays 2 then,
• only c incremented by 1 to 3.*/
• printf("%dn",++c); /*this statement increments 1 to
• c then, only c is displayed.*/
• return 0;
• }
ASSIGNMENT OPERATORS – Binary Operators
• The most common assignment operator is =. This operator assigns the value in the right side to the left side.
For example:
• var=5 //5 is assigned to var
• a=c; //value of c is assigned to a
• 5=c; // Error! 5 is a constant.
RELATIONAL OPERATORS - Binary Operators
• Relational operators check relationship between two operands. If
the relation is true, it returns value 1 and if the relation is false, it
returns value 0. For example: a>b
• Here, > is a relational operator. If a is greater than b, a>b returns 1
if not then, it returns 0. Relational operators are used in decision
making and loops in C programming.
Operator Meaning of Operator Example
== Equal to 5= =3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)
LOGICAL OPERATORS - Binary Operators
• Logical operators are used to combine expressions containing relational operators. In C, there are 3
logical operators:
• The following table shows the result of operator && evaluating the expression a&&b:
• The operator || corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results of a ||
b:
Explanation
• For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be
true but, (d>5) is false in the given example. So, the expression is false. For
expression ((c==5) || (d>5)) to be true, either the expression should
be true. Since, (c==5) is true. So, the expression is true. Since, expression
(c==5) is true, !(c==5) is false.
CONDITIONAL OPERATOR – Ternary Operators
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be
-10.
BITWISE OPERATORS
• Bitwise operators work on bits and performs bit-by-bit operation.
PRECEDENCE OF OPERATORS
• This refers to redefined rule of priority of operators. 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.
ASSOCIATIVITY OF OPERATORS
• Associativity indicates in which order two operators of same precedence (priority)
executes. Let us suppose an expression:
• a= =b!=c
• Here, operators == and != have the same precedence. The associativity of both == and !
= is left to right, i.e., the expression in left is executed first and execution take pale
towards right. Thus, a==b!=c equivalent to :
• (a= =b)!=c
• Operators may be left-associative (meaning the operations are grouped from the left),
right associative (meaning the operations are grouped from the right)
&&
Right
CONTROL STRUCTURES
• Control structures represent the forms by which statements in a
program are executed. Flow of control refers to the order in which
the individual statements, instructions or function calls of a program
are executed or evaluated.
• sequential structure - Executing the statements one by one until the
defined end. The functionality of this type of program is limited
since it flows in a single direction.
• Control structures change the flow of program execution. They
enable decision making and repetition as well as giving the power
to do far more complex processing and provide flexibility with
logic.
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
SELECTION STRUCTURES
• (a) THE IF SELECTION STRUCTURE - Used to choose among alternative courses of action i.e. the if
statement provides a junction at which the program has to select which path to follow. The if selection
performs an action only if the condition is true,
• General form:
• If (expression)
• Statement
• For Block of statements:
• if (expression)
• {
• Block of statements
• }
• (b) THE IF/ELSE - While if only performs an action if the condition is true, if/else specifies an action to
be performed both when the condition is true and when it is false. E
• (c) THE IF...ELSE IF...ELSE STATEMENT
• – Test for multiple cases/conditions.
• – Once a condition is met, the other statements are skipped
• – Deep indentation usually not used in practice
#include <stdio.h>
int main()
{
int marks;
printf("Please enter your MARKS:");
scanf("%d", &marks);
if (marks>=90 && marks <=100)
printf("Your grade is An");
else if (marks>=80 && marks <=89)
printf("Your grade is Bn");
else if (marks>=70 && marks <=79)
printf("Your grade is Cn");
else if (marks>=60 && marks <=69)
printf("Your grade is Dn");
else if (marks >100)
printf("Marks out of rangen");
else
printf("Your grade is Fn");
return 0;
(d) NESTED IF STATEMENTS
One if or else if statement can be used inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows:
if (boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
NB: You can nest else if...else in the similar way as you have nested if
statement.
• #include <stdio.h>
• int main ()
• {
• /* local variable definition */
• int a = 100;
• int b = 200;
• /* check the boolean condition */
• if( a == 100 )
• {
• /* if condition is true then check the following */
• if( b == 200 )
• {
• /* if condition is true then print the following */
• printf("Value of a is 100 and b is 200n" );
• }
• }
• return 0; }
(e) SWITCH STATEMENT
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each switch case.
• Syntax
• The syntax for a switch statement in C programming language is as follows:
• switch(expression)
• {
• case constant-expression:
• statement(s);
• break;
• case constant-expression :
• statement(s);
• break;
• /* you can have any number of case statements */
• default :
• statement(s);
• }
The following rules apply to a switch statement:
• You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the
flow of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is
reached.
• A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
• #include<stdio.h>
• int main()
• {
• char grade;
• printf("Enter your grade:");
• scanf("%c", &grade);
• switch (grade)
• {
• case 'A':
• printf("Excellent!n");
• break;
case 'B':
printf("Very Good!n");
break;
case 'C':
printf("Good!n");
break;
case 'D':
printf("Work harder!n");
break;
default:
printf("Fail!n");
}
return 0;
}
REPETITION/ITERATIVE/LOOP STRUCTURES
• A loop statement allows the execution of a statement or a group of
statements multiple times until a condition either tests true or false.
There are two types of loops: Pre-test and post-test loops.
• In a pretest loop, a logical condition is checked before each
repetition to determine if the loop should terminate. These loops
include:
i. while loop
ii. for loop
• Post-test loops check a logical condition after each repetition for
termination. The do-while loop is a posttest loop.
(a) WHILE LOOP IN C
• A while loop statement repeatedly executes a target statement as
long as a given condition is true.
• The syntax of a while loop in C programming language is:
• while(condition)
• {
• statement(s);
• update expression
• }
• The statement(s) may be a single statement or a block of
statements. The loop iterates while the condition is true.
• When the condition becomes false, program control passes to the
line immediately following the loop.
Example
• #include <stdio.h>
• int main ()
• {
• /* local variable definition */
• int a = 10; //loop index
• /* while loop execution */
• while( a < 20 )
• {
• printf("value of a: %dn", a);
• a++;
• }
• return 0;
• }
(b) FOR LOOP IN C
• A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute
• a specific number of times.
Syntax
• The syntax of a for loop in C programming language is:
• for ( initial expression; test
expression/logical codition; update
• expression )
• {
• statement(s);
• }
Here is the flow of control in a for loop:
• This step initializes any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow
of control jumps to the next statement just after the for loop.
• After the body of the for loop executes, the flow of control jumps back
up to the update expression. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself. After the condition becomes false, the
for loop terminates.
(c) DO...WHILE LOOP IN C
• Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming language checks its condition at the
bottom of the loop.
• A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time. The structure, therefore loops until a
condition tests false i.e. loop until. Syntax
• do
• {
• statement(s);
• }while( condition );
• If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false.
(d) NESTED LOOPS IN C
• C programming language allows the use of
one loop inside another loop. The following
section shows afew examples to illustrate the
concept.
• Syntax
• The syntax for a nested for loop statement in
C is as follows:
• for ( init; condition; increment )
• {
• for ( init; condition; increment )
• {
• statement(s);
• }
• statement(s);
• }
The syntax for a nested while loop statement
in C programming language is as follows:
• while(condition)
• {
• while(condition)
• {
• statement(s);
• }
• statement(s);
• }
• The syntax for a nested do...while
loop statement in C programming
language is as follows:
• do
• {
• statement(s);
• do
• {
• statement(s);
• }while( condition );
• }while( condition );
you can put any type of loop inside of any other type of loop. For example, a for loop can be
inside a while loop or vice versa.
• Example
• #include <stdio.h>
• int main()
• {
• int n, c, k;
• printf("Enter number of rows:");
• scanf("%d",&n);
• for ( c = 1 ; c <= n ; c++ )
• {
• for( k = 1 ; k <= c ; k++ )
• {
• printf("%d",k);
• }
Statements & Expressions
• Expressions combine variables and constants to create new values e.g.
• x + y;
• Statements in C are expressions, assignments, function calls,
or control flow statements which make up C programs.
• An assignment statement uses the assignment operator “=” to
give a variable on the operator’s left side the value to the
operator’s right or the result of an expression on the right.
• z = x + y;
Comments
• These are non-executable program statements meant to enhance program readability and
allow easier program maintenance- they document the program. They are ignored by the
compiler.
• These are used to give additional useful information inside a C Program. All the comments will
be put inside /*...*/ or // for single line comments as given in the example above. A comment can
span through multiple lines.
• /* Author: Mzee Moja */
or
• /*
• * Author: Mzee Moja
• * Purpose: To show a comment that spans multiple lines.
• * Language: C
• */
or
• Fruit = apples + oranges; // get the total fruit
Escape Sequences
• Escape sequences (also called back slash codes) are character combinations that
begin with a backslash symbol used to format output and represent difficult-to-
type characters. They include:
• a Alert/bell
• b Backspace
• n New line
• v Vertical tab
• t Horizontal tab
•  Back slash
• ’ Single quote
• 19
• ” Double quote
• 0 Null
Note the following
• C is a case sensitive programming language. It means in C printf and Printf
will have different meanings.
• End of each C statement must be marked with a semicolon.
• Multiple statements can be on the same line.
• Any combination of spaces, tabs or newlines is called a white space. C is a
free-form language as the C compiler chooses to ignore whitespaces.
Whitespaces are allowed in any format to improve readability of the code.
Whitespace is the term used in C to describe blanks, tabs, newline
characters and comments.
Note the following
• Statements can continue over multiple lines.
• A C identifier is a name used to identify a variable, function, or any other
user-defined item. An identifier starts with a letter A to Z or a to z, Can
start with an underscore _ followed by zero or more letters, underscores,
and digits (0 to 9). C does not allow punctuation characters such as @, $,
and % within identifiers.
• · A keyword is a reserved word in C. Reserved words may not be used as
constants or variables or any other identifier names
SAMPLE PROGRAM
• //First program to display an integer
• #include<stdio.h>
• main()
• {
• int num; // Declaration
• num =1; // Assignment statement
• printf(" My favorite number is %d because", num);
• printf(" it is first.n");
• return 0;
• }
• The program will output (print on screen) the statement “My favorite number is 1
because it is first”. The %d instructs the computer where and in what form to print
the value. %d is a type specifier used to specify the output format for integer
numbers.
Reserved Words/Keywords in C
• The following list shows the reserved words in C. These reserved words may not
be used as constants or variables or any other identifier names.
SOURCE CODE FILES
• When you write a program in C language, your instructions form the source code/file. C files
have
• an extension .c. The part of the name before the period is called the extension.
Object Code, Executable Code and Libraries
• An executable file is a file containing ready to run machine code. C accomplishes this in two
• steps.
• Compiling –The compiler converts the source code to produce the intermediate object code.
• The linker combines the intermediate code with other code to produce the executable file.
• You can compile individual modules and then combine modules later.
• Linking is the process where the object code, the start up code and the code for library routines
• used in the program (all in machine language) are combined into a single file- the executable file.
• NB/ An interpreter unlike a compiler is a computer program that directly
executes, i.e. performs, instructions written in a programming, without
previously compiling them into a machine language program.
• If the compiled program can run on a computer whose CPU or operating
system is different from the one on which the compiler runs, the compiler is
known as a crosscompiler.
• A program that translates from a low level language to a higher level one is a
decompiler.
• A program that translates between high-level languages is usually called a
sourceto- source compiler or transpiler.
C DATA TYPES
• In the C programming language, data types refer to a system used for declaring variables or
functions of different types. A data type is, therefore, a data storage format that can contain a
specific type or range of values. The type of a variable determines how much space it occupies
in storage and how the bit pattern stored is interpreted. The basic data types in C are as follows:
Type Description
• Char Character data and is used to hold a single character. A character can be a letter, number,
space, punctuation mark, or symbol - 1 byte long
• Int A signed whole number in the range -32,768 to 32,767 - 2 bytes long
• Float A real number (that is, a number that can contain a fractional part) – 4 bytes
• Double A double-precision floating point value. Has more digits to the right of the decimal point
than a float – 8 bytes
• Void Represents the absence of type. i.e. represents “no data”
• USING

More Related Content

Similar to STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx (20)

PPTX
Unit-1 (introduction to c language).pptx
saivasu4
 
PDF
C intro
SHIKHA GAUTAM
 
PPTX
C structure
ankush9927
 
PPT
424769021-1-First-C-Program-1-ppt (1).ppt
advRajatSharma
 
PDF
The New Yorker cartoon premium membership of the
shubhamgupta7133
 
DOCX
Module 1 PCD.docx
VijayKumar886687
 
PPTX
C Programming - Basics of c -history of c
DHIVYAB17
 
PPTX
Basics of C Lecture 2[16097].pptx
CoolGamer16
 
PPTX
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
 
PPT
490450755-Chapter-2.ppt
ManiMala75
 
PPT
490450755-Chapter-2.ppt
ManiMala75
 
PDF
EC2311-Data Structures and C Programming
Padma Priya
 
PPTX
c programming session 1.pptx
RSathyaPriyaCSEKIOT
 
PPT
lec 1 for ITC Introduction to computing and AI
FatimaAijaz6
 
PPTX
C programming
KarthicaMarasamy
 
PPTX
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
PPTX
C Programming UNIT 1.pptx
Mugilvannan11
 
PPTX
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
 
PPTX
unit2.pptx
sscprep9
 
PPTX
Introduction to C Programming language Chapter02.pptx
foxel54542
 
Unit-1 (introduction to c language).pptx
saivasu4
 
C intro
SHIKHA GAUTAM
 
C structure
ankush9927
 
424769021-1-First-C-Program-1-ppt (1).ppt
advRajatSharma
 
The New Yorker cartoon premium membership of the
shubhamgupta7133
 
Module 1 PCD.docx
VijayKumar886687
 
C Programming - Basics of c -history of c
DHIVYAB17
 
Basics of C Lecture 2[16097].pptx
CoolGamer16
 
Unit No 2.pptx Basic s of C Programming
Vaibhav Parjane
 
490450755-Chapter-2.ppt
ManiMala75
 
490450755-Chapter-2.ppt
ManiMala75
 
EC2311-Data Structures and C Programming
Padma Priya
 
c programming session 1.pptx
RSathyaPriyaCSEKIOT
 
lec 1 for ITC Introduction to computing and AI
FatimaAijaz6
 
C programming
KarthicaMarasamy
 
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
C Programming UNIT 1.pptx
Mugilvannan11
 
C programming language:- Introduction to C Programming - Overview and Importa...
SebastianFrancis13
 
unit2.pptx
sscprep9
 
Introduction to C Programming language Chapter02.pptx
foxel54542
 

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Ad

STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx

  • 1. STRUCTURED PROGRAMMING (USING C PROGRAMMING) Mr. Stephen Njuguna DEFINITION OF TERMS
  • 2. DEFINATION TERMS • HEADER FILE - A header file is a file with extension .h which contains C function declarations to be shared between several source files. A header file is used in a program by including it with the use of the preprocessing directive #include, which comes along with the compiler. #include<stdio.h> • PREPROCESSOR DIRECTIVES are lines included in a program that begin with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation. Preprocessor directives change the text of the source code and the result is a new source code without these directives.
  • 3. DEFINATION TERMS • EXPRESSION – These are statements that return a value. Expressions combine variables and constants to create new values or logical conditions which are either true or false e.g.x + y, x <= y etc • KEYWORD - A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names. Examples include auto, else, Long, switch, typedef, break etc • IDENTIFIER - A C identifier is a name used to identify a variable, function, or any other user defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers.
  • 4. DEFINATION TERMS • IDENTIFIER - A C identifier is a name used to identify a variable, function, or any other user defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. • COMMENT - These are non-executable program statements meant to enhance program readability and maintenance- they document the program. • FUNCTION - A function is a group of statements, enclosed within curly braces, which together perform a task.
  • 5. DEFINATION TERMS • STATEMENT - Statements are expressions, assignments, function calls, or control flow statements which make up C programs. Statements are terminated using a semicolon. • SOURCE CODE – Program instructions in their original form. C source code files have an extension .c • OBJECT CODE – Code produced by a compiler from source code and exists in machine readable language. • EXECUTABLE FILE – Refers to a file in a format that a computer can directly execute and is created by a compiler.
  • 6. DEFINATION TERMS • STANDARD LIBRARY – Refers to a collection of precompiled functions/routines that a program can use. The routines are stored in object format and contain descriptions of functions to perform I/O, string manipulations, mathematics etc. • SIGNED INTEGER – This is an integer that can hold either positive or negative numbers. • COMPILER – This is a program that translates source code into object code. • PREPROCESSOR COMMAND - The C preprocessor modifies a source file before handing it over to the compiler for instance by including header files with #include as I #include <stdio.h>
  • 7. DEFINATION TERMS • LINKER/Binder/Link Editor – This is a program that combines object modules to form an executable program. The linker combines the object code, the start up code and the code for library routines used in the program (all in machine language) into a single file- the executable file. • OPERATOR - A symbol that represents a specific action. For example, a plus sign (+) is an operator that represents addition. The basic mathematic operators are + addition, - subtraction,* multiplication, / division.
  • 8. DEFINATION TERMS • OPERAND - Operands are the objects that are manipulated by operators in expressions. For example, in the expression 5 + x, x and 5 are operands and + is an operator. All expressions have at least one operand. • EXPRESSION – This is a statement that returns a value. For example, when you add two numbers together or test to see whether one value is equal to another. • VARIABLE - A variable is a memory location whose value can change during program execution. Variable declaration must have a type, which defines what values that variable can hold.
  • 9. DEFINATION TERMS • VARIABLE - A variable is a memory location whose value can change during program execution. Variable declaration must have a type, which defines what values that variable can hold. VARIABLE RULES • A variable can have alphabets, digits, and underscore. • A variable name can start with the alphabet, and underscore only. It can't start with a digit. • No whitespace is allowed within the variable name. • A variable name must not be any reserved word or keyword, e.g. int, goto , etc. • A Variable must have a type, which defines what values that variable can hold.
  • 10. DEFINATION TERMS • DATA TYPE – The data type of a variable etc determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. • CONSTANT - a constant is a value that never changes during program execution.
  • 11. DEFINATION TERMS • WHITESPACE • A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. • Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. • Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. • Therefore, in the following statement: int age; There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. • On the other hand, in the following statement.
  • 12. STRUCTURE OF A C PROGRAM •The C programming language was designed by Dennis Ritchie as a systems programming language for Unix. •A C program basically has the following structure: • Preprocessor Commands • Functions • Variable declarations • Statements & Expressions • Comments
  • 13. STRUCTURE OF A C PROGRAM 1.Example: 2.#include <stdio.h> 3.int main() 4.{ 5.//SINGLE LINE COMMENT 6./* My first program*/ 7.printf("Hello, World! n"); 8.return 0; 9.}
  • 14. Exercise 1 Sample 1 Program to allow the User to enter his or her name: #include<stdio.h> int main() { char name[20]; printf("Enter Your Name : "); scanf("%s",&name); printf("Your name is : %s", name); getch(); return 0; }
  • 15. Sample 2 Program to allow the User to enter his or her name: • #include<stdio.h> • int main() • { • char name[25]; • printf("Enter Your Full Names: "); • gets(name); • printf("nWelcome %s to C programmingn",name); • return 0; • }
  • 16. Exercise 1 Sample 3 Program to allow the User to enter his or her name: • #include<stdio.h> • #include<stdlib.h> • int main() • { • char name[25]; • printf("Enter Your Full Names: "); • gets(name); • system("cls"); • printf("nHere is your full namesn"); • puts(name); • return 0;
  • 17. Exercise 2 Program to request user for radius and the calculate both Area and Circumference of a circle: Sample 1 • #include<stdio.h> • int main() • { • float r, area,circ; • printf("Enter the radius of a circle=> "); • scanf("%f",&r); • area=3.14*r*r; • circ=2*3.14*r; • printf("Area: %fnnCircumfrence: %fnn",area,circ); • return 0; • }
  • 18. Exercise 2 Program to request user for radius and the calculate both Area and Circumference of a circle: Sample 2 • #include<stdio.h> • int main() • { • float r, area,circ,pie=3.14; • printf("Enter the radius of a circle=> "); • scanf("%f",&r); • area=pie*r*r; • circ=2*pie*r; • printf("Area: %fnnCircumfrence: %fnn",area,circ); • return 0; • }
  • 19. Exercise 2 Program to request user for radius and the calculate both Area and Circumference of a circle: Sample 3 • #include<stdio.h> • #define PIE 3.14 //Constant defined • int main() • { • float r, area,circ; //variable declaration • printf("Enter the radius of a circle=> "); • scanf("%f",&r);//reading a float value to be radius • area=PIE*r*r; • circ=2*PIE*r; • printf("Area: %fnn Circumfrence: %fnn",area,circ); • return 0; • }
  • 20. Exercise 2 • Program to request user for radius and the calculate both Area and Circumference of a circle: Sample 4 • #include<stdio.h> • #include<math.h> • #define PIE 3.14 //Constant defined • int main() • { • float r, area,circ; //variable declaration • printf("Enter the radius of a circle=> "); • scanf("%f",&r);//reading a float value to be radius • area=PIE*pow(r,2); • circ=2*PIE*r; • printf("Area: %fnn Circumfrence: %fnn",area,circ); • return 0; • }
  • 21. Preprocessor Commands • These commands tell the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. The standard input and output header file (stdio.h) allows the program to interact with the screen, keyboard and file system of the computer. • NB/ Preprocessor directives are not actually part of the C language, but rather instructions from you to the compiler.
  • 22. Functions • These are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. When this function is prefixed with keyword int, it means this function returns an integer value when it exits. This integer value is retuned using return statement. • The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. • A function is a group of statements that together perform a task. A C program can be divide up into separate functions but logically the division usually is so each function performs a specific task.
  • 23. Functions • A function declaration tells the compiler about a function's name, return type, and parameters. • A function definition provides the actual body of the function. • The general form of a function definition in C programming language is as follows:
  • 24. Functions • return_type function_name( parameter list ) • { • body of the function/Function definition • }
  • 25. Function Example1: • #include<stdio.h> • int addition(int x,int y);//Function Declaration • int addition(int x,int y) • { • int sum; • sum=x+y; • return sum; • } • int main() • { • int a,b; • printf("Enter number 1: "); • scanf("%d",&a); • printf("Enter number 2: "); • scanf("%d",&b); • printf("The Sum of the two Numbers is: %dn",addition(a,b)); • } Function Defination
  • 26. VARIABLES • A variable is a memory location whose value can change during program execution. In C a variable must be declared before it can be used. • Variable Declaration • Declaring a variable tells the compiler to reserve space in memory for that particular variable. A variable definition specifies a data type and the variable name and contains a list of one or more variables of that type .Variables can be declared at the start of any block of code. A declaration begins with the type, followed by the name of one or more variables. For example, Int high, low; • int i, j, k; • char c, ch; • float f, salary;
  • 27. Variable Declarations • Variables can be initialized when they are declared. This is done by adding an equals sign and the required value after the declaration. • Int high = 250; /*Maximum Temperature*/ • Int low = -40; /*Minimum Temperature*/ • Int results[20]; /* series of temperature readings*/ • In C, all variables must be declared before they are used. Thus, C is a strongly typed programming language. Variable declaration ensures that appropriate memory space is reserved for the variables. • Variables are used to hold numbers, strings and complex data for manipulation e.g. • Int x; • Int num; int z;
  • 28. TYPES OF VARIABLES •The Programming language C has two main variable types • Local Variables •Global Variables
  • 29. Local Variables • A local variable is a variable that is declared inside a function. • Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. • When execution of the block starts the variable is available, and when the block ends the variable 'dies’. Global Variables • Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are declared outside all functions.
  • 30. Sample Program. • #include <stdio.h> • int area; //global variable • int main () • { • int a, b; //local variable • /* actual initialization */ • a = 10; • b = 20; • printf("t Side a is %d cm and side b is %d cm longn",a,b); • area = a*b; • printf("t The area of your rectangle is : %d n", area); • return 0; • }
  • 31. Inputing Numbers From The Keyboard Using Scanf() • Variables can also be initialized during program execution (run time). The scanf() function is used to read values from the keyboard. For example, to read an integer value use the following general form: • scanf(“%d”, &var_name) • As in • scanf(“%d”, &num) • The %d is a format specifier which tells the compiler that the second argument will be receiving an integer value. • The & preceding the variable name means “address of”. The function allows the function to place a value into one of its arguments. The table below shows format specifiers or codes used in the scanf() function and their meaning.
  • 32. TYPE CASTING • When used in a printf() function, a type specifier informs the function that a different type item is being displayed. • Type casting is a way to convert a variable from one data type to another. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows: • (type_name) expression • Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation: • #include <stdio.h> • main() • { • int sum = 17, count = 5; • double mean; • mean = (double) sum / count; • printf("Value of mean is %d n", mean ); • }
  • 33. C PROGRAMMING OPERATORS • Operator is the symbol which operates on a value or a variable (operand). For example: + is an operator to perform addition. • 1. Arithmetic Operators • 2. Increment and Decrement Operators • 3. Assignment Operators • 4. Relational Operators • 5. Logical Operators • 6. Conditional Operators • 7. Bitwise Operators • 8. Special Operators
  • 36. SAMPLE PROGRAM • #include <stdio.h> • int main(){ • int c=2; • printf("%dn",c++); /*this statement displays 2 then, • only c incremented by 1 to 3.*/ • printf("%dn",++c); /*this statement increments 1 to • c then, only c is displayed.*/ • return 0; • }
  • 37. ASSIGNMENT OPERATORS – Binary Operators • The most common assignment operator is =. This operator assigns the value in the right side to the left side. For example: • var=5 //5 is assigned to var • a=c; //value of c is assigned to a • 5=c; // Error! 5 is a constant.
  • 38. RELATIONAL OPERATORS - Binary Operators • Relational operators check relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example: a>b • Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0. Relational operators are used in decision making and loops in C programming. Operator Meaning of Operator Example == Equal to 5= =3 returns false (0) > Greater than 5>3 returns true (1) < Less than 5<3 returns false (0) != Not equal to 5!=3 returns true(1) >= Greater than or equal to 5>=3 returns true (1) <= Less than or equal to 5<=3 return false (0)
  • 39. LOGICAL OPERATORS - Binary Operators • Logical operators are used to combine expressions containing relational operators. In C, there are 3 logical operators:
  • 40. • The following table shows the result of operator && evaluating the expression a&&b: • The operator || corresponds to the Boolean logical operation OR, which yields true if either of its operands is true, thus being false only when both operands are false. Here are the possible results of a || b:
  • 41. Explanation • For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false. CONDITIONAL OPERATOR – Ternary Operators Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example: c=(c>0)?10:-10; If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
  • 42. BITWISE OPERATORS • Bitwise operators work on bits and performs bit-by-bit operation.
  • 43. PRECEDENCE OF OPERATORS • This refers to redefined rule of priority of operators. 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.
  • 44. ASSOCIATIVITY OF OPERATORS • Associativity indicates in which order two operators of same precedence (priority) executes. Let us suppose an expression: • a= =b!=c • Here, operators == and != have the same precedence. The associativity of both == and ! = is left to right, i.e., the expression in left is executed first and execution take pale towards right. Thus, a==b!=c equivalent to : • (a= =b)!=c • Operators may be left-associative (meaning the operations are grouped from the left), right associative (meaning the operations are grouped from the right)
  • 46. CONTROL STRUCTURES • Control structures represent the forms by which statements in a program are executed. Flow of control refers to the order in which the individual statements, instructions or function calls of a program are executed or evaluated. • sequential structure - Executing the statements one by one until the defined end. The functionality of this type of program is limited since it flows in a single direction. • Control structures change the flow of program execution. They enable decision making and repetition as well as giving the power to do far more complex processing and provide flexibility with logic.
  • 48. SELECTION STRUCTURES • (a) THE IF SELECTION STRUCTURE - Used to choose among alternative courses of action i.e. the if statement provides a junction at which the program has to select which path to follow. The if selection performs an action only if the condition is true, • General form: • If (expression) • Statement • For Block of statements: • if (expression) • { • Block of statements • } • (b) THE IF/ELSE - While if only performs an action if the condition is true, if/else specifies an action to be performed both when the condition is true and when it is false. E • (c) THE IF...ELSE IF...ELSE STATEMENT • – Test for multiple cases/conditions. • – Once a condition is met, the other statements are skipped • – Deep indentation usually not used in practice
  • 49. #include <stdio.h> int main() { int marks; printf("Please enter your MARKS:"); scanf("%d", &marks); if (marks>=90 && marks <=100) printf("Your grade is An"); else if (marks>=80 && marks <=89) printf("Your grade is Bn"); else if (marks>=70 && marks <=79) printf("Your grade is Cn"); else if (marks>=60 && marks <=69) printf("Your grade is Dn"); else if (marks >100) printf("Marks out of rangen"); else printf("Your grade is Fn"); return 0;
  • 50. (d) NESTED IF STATEMENTS One if or else if statement can be used inside another if or else if statement(s). Syntax The syntax for a nested if statement is as follows: if (boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } } NB: You can nest else if...else in the similar way as you have nested if statement.
  • 51. • #include <stdio.h> • int main () • { • /* local variable definition */ • int a = 100; • int b = 200; • /* check the boolean condition */ • if( a == 100 ) • { • /* if condition is true then check the following */ • if( b == 200 ) • { • /* if condition is true then print the following */ • printf("Value of a is 100 and b is 200n" ); • } • } • return 0; }
  • 52. (e) SWITCH STATEMENT A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. • Syntax • The syntax for a switch statement in C programming language is as follows: • switch(expression) • { • case constant-expression: • statement(s); • break; • case constant-expression : • statement(s); • break; • /* you can have any number of case statements */ • default : • statement(s); • }
  • 53. The following rules apply to a switch statement: • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. • The constant-expression for a case must be the same data type as the variable in the switch • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
  • 54. • #include<stdio.h> • int main() • { • char grade; • printf("Enter your grade:"); • scanf("%c", &grade); • switch (grade) • { • case 'A': • printf("Excellent!n"); • break; case 'B': printf("Very Good!n"); break; case 'C': printf("Good!n"); break; case 'D': printf("Work harder!n"); break; default: printf("Fail!n"); } return 0; }
  • 55. REPETITION/ITERATIVE/LOOP STRUCTURES • A loop statement allows the execution of a statement or a group of statements multiple times until a condition either tests true or false. There are two types of loops: Pre-test and post-test loops. • In a pretest loop, a logical condition is checked before each repetition to determine if the loop should terminate. These loops include: i. while loop ii. for loop • Post-test loops check a logical condition after each repetition for termination. The do-while loop is a posttest loop.
  • 56. (a) WHILE LOOP IN C • A while loop statement repeatedly executes a target statement as long as a given condition is true. • The syntax of a while loop in C programming language is: • while(condition) • { • statement(s); • update expression • } • The statement(s) may be a single statement or a block of statements. The loop iterates while the condition is true. • When the condition becomes false, program control passes to the line immediately following the loop.
  • 57. Example • #include <stdio.h> • int main () • { • /* local variable definition */ • int a = 10; //loop index • /* while loop execution */ • while( a < 20 ) • { • printf("value of a: %dn", a); • a++; • } • return 0; • }
  • 58. (b) FOR LOOP IN C • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute • a specific number of times. Syntax • The syntax of a for loop in C programming language is: • for ( initial expression; test expression/logical codition; update • expression ) • { • statement(s); • }
  • 59. Here is the flow of control in a for loop: • This step initializes any loop control variables. You are not required to put a statement here, as long as a semicolon appears. • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. • After the body of the for loop executes, the flow of control jumps back up to the update expression. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself. After the condition becomes false, the for loop terminates.
  • 60. (c) DO...WHILE LOOP IN C • Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming language checks its condition at the bottom of the loop. • A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. The structure, therefore loops until a condition tests false i.e. loop until. Syntax • do • { • statement(s); • }while( condition ); • If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
  • 61. (d) NESTED LOOPS IN C • C programming language allows the use of one loop inside another loop. The following section shows afew examples to illustrate the concept. • Syntax • The syntax for a nested for loop statement in C is as follows: • for ( init; condition; increment ) • { • for ( init; condition; increment ) • { • statement(s); • } • statement(s); • } The syntax for a nested while loop statement in C programming language is as follows: • while(condition) • { • while(condition) • { • statement(s); • } • statement(s); • }
  • 62. • The syntax for a nested do...while loop statement in C programming language is as follows: • do • { • statement(s); • do • { • statement(s); • }while( condition ); • }while( condition ); you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.
  • 63. • Example • #include <stdio.h> • int main() • { • int n, c, k; • printf("Enter number of rows:"); • scanf("%d",&n); • for ( c = 1 ; c <= n ; c++ ) • { • for( k = 1 ; k <= c ; k++ ) • { • printf("%d",k); • }
  • 64. Statements & Expressions • Expressions combine variables and constants to create new values e.g. • x + y; • Statements in C are expressions, assignments, function calls, or control flow statements which make up C programs. • An assignment statement uses the assignment operator “=” to give a variable on the operator’s left side the value to the operator’s right or the result of an expression on the right. • z = x + y;
  • 65. Comments • These are non-executable program statements meant to enhance program readability and allow easier program maintenance- they document the program. They are ignored by the compiler. • These are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ or // for single line comments as given in the example above. A comment can span through multiple lines. • /* Author: Mzee Moja */ or • /* • * Author: Mzee Moja • * Purpose: To show a comment that spans multiple lines. • * Language: C • */ or • Fruit = apples + oranges; // get the total fruit
  • 66. Escape Sequences • Escape sequences (also called back slash codes) are character combinations that begin with a backslash symbol used to format output and represent difficult-to- type characters. They include: • a Alert/bell • b Backspace • n New line • v Vertical tab • t Horizontal tab • Back slash • ’ Single quote • 19 • ” Double quote • 0 Null
  • 67. Note the following • C is a case sensitive programming language. It means in C printf and Printf will have different meanings. • End of each C statement must be marked with a semicolon. • Multiple statements can be on the same line. • Any combination of spaces, tabs or newlines is called a white space. C is a free-form language as the C compiler chooses to ignore whitespaces. Whitespaces are allowed in any format to improve readability of the code. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
  • 68. Note the following • Statements can continue over multiple lines. • A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z, Can start with an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. • · A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names
  • 69. SAMPLE PROGRAM • //First program to display an integer • #include<stdio.h> • main() • { • int num; // Declaration • num =1; // Assignment statement • printf(" My favorite number is %d because", num); • printf(" it is first.n"); • return 0; • } • The program will output (print on screen) the statement “My favorite number is 1 because it is first”. The %d instructs the computer where and in what form to print the value. %d is a type specifier used to specify the output format for integer numbers.
  • 70. Reserved Words/Keywords in C • The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
  • 71. SOURCE CODE FILES • When you write a program in C language, your instructions form the source code/file. C files have • an extension .c. The part of the name before the period is called the extension. Object Code, Executable Code and Libraries • An executable file is a file containing ready to run machine code. C accomplishes this in two • steps. • Compiling –The compiler converts the source code to produce the intermediate object code. • The linker combines the intermediate code with other code to produce the executable file. • You can compile individual modules and then combine modules later. • Linking is the process where the object code, the start up code and the code for library routines • used in the program (all in machine language) are combined into a single file- the executable file.
  • 72. • NB/ An interpreter unlike a compiler is a computer program that directly executes, i.e. performs, instructions written in a programming, without previously compiling them into a machine language program. • If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a crosscompiler. • A program that translates from a low level language to a higher level one is a decompiler. • A program that translates between high-level languages is usually called a sourceto- source compiler or transpiler.
  • 73. C DATA TYPES • In the C programming language, data types refer to a system used for declaring variables or functions of different types. A data type is, therefore, a data storage format that can contain a specific type or range of values. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The basic data types in C are as follows: Type Description • Char Character data and is used to hold a single character. A character can be a letter, number, space, punctuation mark, or symbol - 1 byte long • Int A signed whole number in the range -32,768 to 32,767 - 2 bytes long • Float A real number (that is, a number that can contain a fractional part) – 4 bytes • Double A double-precision floating point value. Has more digits to the right of the decimal point than a float – 8 bytes • Void Represents the absence of type. i.e. represents “no data” • USING