0% found this document useful (0 votes)
3 views

CSC 316 Structured Programming Update

The document outlines the principles and techniques of structured programming, emphasizing the importance of clarity, modularity, and stepwise refinement in programming. It discusses various program types, comparisons between spaghetti code and structured programming, and provides examples of structured code. Additionally, it covers programming languages, data types, and the phases of structured programming, including top-down analysis and modular programming.

Uploaded by

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

CSC 316 Structured Programming Update

The document outlines the principles and techniques of structured programming, emphasizing the importance of clarity, modularity, and stepwise refinement in programming. It discusses various program types, comparisons between spaghetti code and structured programming, and provides examples of structured code. Additionally, it covers programming languages, data types, and the phases of structured programming, including top-down analysis and modular programming.

Uploaded by

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

Structured

Programming
CSC 316

Computer Science Department


PLASU

Heman A.M.
Course Outline
• Structured Programming elements
• structured design principles
• abstraction modularity
• stepwise refinement
• structured design techniques
What is a program
• A set of instructions written in a programming language for a
computer to perform a specific task
• It’s the structuring of a solution to a problem and the refine the
solution step-wise
Program types
• Application: a computer program designed to perform a group of
coordinated functions, tasks, or activities for the benefit of the user
• Utility: small program developed to carryout small task. Its not
maintained
• Service: any program that runs at the background of a computer that
enables the smooth running of the computer. No direct interaction
with the user
• System program: instructions the run a computer hardware or
application programs
Comparison between spaghetti
code and structured
MIP program that finds maximum,
program
minimum and average of numbers C program that finds maximum,
.data minimum and average of numbers
txt1: .asciiz "Enter number of terms : "
#include <stdio.h>
txt2: .asciiz "Please enter an integer : "
txt3: .asciiz "\nThe maximum value is : "
int main()
txt4: .asciiz "\nThe minimum value is : " {
txt5: .asciiz "\nThe average is : " int num[1000],i,n,min,max,sum = 0;
txt6: .asciiz " with remainder : " float avg;
.text printf("Enter number of terms : ");
.globl main #Enables the procedure accessible outside this file
scanf("%d",&n);
main:
printf("Enter the terms one by one: ");
addi $s0, $zero, 0
la $a0, txt1 #load the address ot txt1
for(i=0; i<n; i++)
li $v0, 4 {
syscall printf("\n%d. Enter a number: ", i + 1);
li $v0, 5 #Accept input (integer) value from the console scanf("%d",&num[i]);
syscall }
add $t1, $v0, 0
min=max=num[0];
Comparison between spaghetti code
and structured program Conn’d
loop:
for(i=1; i<n; i++)
la $a0, txt2 #load the address of txt2 to $a0
{
li $v0, 4 #Return the content of text1 to the console
if(min>num[i])
syscall
min=num[i];
beq $t1, $t0, average
if(max<num[i])
li $v0, 5 #Accepts input (integer) value from the console max=num[i];
syscall sum += num[i];
add $s0, $v0, 0 #Saves the value entered to $0 }
add $t0, $t0, 1 #auto increment value in the loop by 1 avg = sum/n;
add $t3, $t3, $s0 #Whatever taken be $s0 is added to the content of $t3 printf("The minimum value = %d",min);
beq $t0, 1, first #The First value should equal min and max printf("\nThe maximum value = %d",max);
blt $s0, $t2, min printf("\nAnd the average = %2f",avg);
bgt $s0, $t4, max return 0;
first: }
add $t2, $s0, 0 #The first value is assigned min
add $t4, $s0, 0 #The first value is assigned max
j loop #jump to pick the next value
min:
add $t2, $s0, 0 #Value less than $s0 is added to $t1
j loop
max:
add $t4, $s0, 0 #Value less greater than $s0 is put on t2
j loop
average:
div $t3, $t0 #divide sum by n
mflo $t7 #store quotient
mfhi $t6 # store reminder
print:
la $a0, txt3
li $v0, 4
syscall
add $a0, $t4, 0
li $v0, 1
syscall
la $a0, txt4
li $v0, 4
syscall
add $a0, $t2, 0
li $v0, 1
syscall
la $a0, txt5
li $v0, 4
syscall
add $a0, $t7, 0
li $v0, 1
syscall
exit:
li $v0, 10
syscall
unstructured
programming (Large
programs)
• Difficult to update/Modify
• More difficult to maintain
• More time consuming to develop
• A program could have more than one entry and exit points
• Tendency to have indefinite loop
• Have more lines of code
Structure
• A structure is a set of data that in someway it has an intermediary
relation
• A pre-state to classes within object oriented programming
Structured
Programming
• A programming paradigm aimed at improving the clarity, quality, and
development time of a computer program by making extensive use
of subroutines, block structures, for and while loops—in contrast to
using simple tests and jumps such as the goto statement which could
lead to "spaghetti code”
• Is base on refinement process – a method of problem decomposition
common to all engineering disciplines and the physical, chemical and
biological sciences
Structured program
example

Your are suppose to create a program that calculates the price of


products to be bought by a customer. The customer specifies the
product and the requested quantity. The program should then give 10%
discount add tax and show customer price
Problem analysis
• Let the customer enters what he/she want from list of available
options
• Calculate quantity selected
• Calculate discount
• Add tax and
• Display price
Commonly Used tool
• Jackson Structured Programming (JSP)
Commonly Used tool
Phases of Structured
Programming
Structured
Programming

TopDown Modular Structured


Analysis Programming code
Topdown Analysis
• The program is broken down into smaller parts for appropriate
solution to be devised for it
• Problems are broken down into tasks

Task

Task 1 Task 2 Task 3

Task 1.1 Task 1.2 Task 3.1 Task 3.2

Task
1.1.1
Advantages of TopDown Analysis
• Reduces the complexity of problem solving
• Not limited to particular type of program
Steps for TopDown Analysis
1. Define complete scope of the problem
• Determination of input: what data to be processed
 What to do on the input data
 What type of processing is needed to be done
• Output: what information is expected
2. Division of problem
3. Divide the scope of each part and divide it into tasks
4. Repeat step 3 until a simple task is reached which can’t be further
divided (best solution is obtained)
Modular Programming
• Program broken into smaller independent units called modules
(functions)
 Each module is developed independent of each other
 Each module accomplish a function and contains all the source codes
 Has entry point to which control is transferred from outside
 Has only one exit point to which a control is return back to the calling function
• It is a solution to a very large program which is difficult to develop
and maintain
• Advantages
 Modules can be assigned to groups of developers
 It leads to reusable codes
 Debugging and finding errors becomes easy
Structured Code
• Goto or Jump statement are replaced with if, if else, switch-
case, loop such as for and while and do-while statements
• Advantage
 It improves the problem solving process
 Better organization of program
 Generalization programming methodology
 Clear description of data and structure
 Programs are made for easy documentation and modifications

Imperical
Bottom Up
• Bottom-up: is the composition (stepwise refinement) of smallest
components of a program that interlink to form a desired program
 Building a language towards a program (low level language e.g. Lips,
Assembly language)
 Larger language with more abstract operators
• Advantage
 It’s the best approach when developing an application from an existing system
• Disadvantages of Bottom Top
 It is risky to design and implement the base elements without having clear idea
of how these would be linked in the final system
 Good vision is necessary to decide the functionality of a module
Disadvantages of
Structured
Programming
• Slower in compilation than assembly language
• Abstraction layer prevents programmers from handling use of hardware resources
directly
• The object code generated by a translator might be inefficient compared to an
equivalent assembly language program
• To update a datatype in a program with large source code can be time consuming
• Data is insecure as it could be accessed by any function
• It makes programmers lazy because it makes completion of program faster
C Language
• It’s a general-purpose, procedural, imperative computer
programming language
 Procedural or imperative: list of instructions to be executed in a specified order
• Advantages
 Easy to learn or at least, less complicated
 Structured language
 It produces efficient program
 It can handle low-level activities
 It comes with built-in headers
 It can be compiled on variety of IDE
Areas of Application
• Operating Systems
• Language compilers
• Assemblers
• Text editors
• Print spoolers
• Network drivers
• Modern programs
• Databases
• Language interpreters
• Utilities
• Malware
Datatype
It is the classification of data which tells the compiler or interpreter how the
programmer wants to use the data

• Primitive:
 Character
 Integer
 Floating point
• Enumerated type: is a user defined type which is used to assign names to
integral constants name which makes the program easier to read and maintain
• Void type: indicates that no value will be returned
• Derived types:
 Pointer
 Array
 Structure
 Union
 Function
Running c on Linux
• Verify that gcc is install from the termimanal: gcc --version
• Create a file: touch <file_name>.c in the directory of your choice or
with any text editor, say gedit in the directory of your choice: gedit
/home/<username>/<dir> file_name
• Write code and save the file
• Compile the program: gcc <file_name>.c -o <binary_name>
• Run the program: /home/<username/<dir>/ ./<binary_name>
Similarly, you could use g++ to compile c++ (.cpp) files
Primitive types
Type Explanation Minimum size (bits) Format specifier

Smallest addressable unit of the machine that can contain basic character
char set. It is an integer type. Actual type can be either signed or unsigned. It 8 %c
contains CHAR_BIT bits.

Of the same size as char, but guaranteed to be signed. Capable of %c (or %hhi for numerical
signed char 8
containing at least the [−127, +127] range. output)

Of the same size as char, but guaranteed to be unsigned. Contains at least %c (or %hhu for numerical
unsigned char 8
the [0, 255] range. output)
Short signed integer type. Capable of containing at least the
signed short int 16 %hi or %hd
[−32,767, +32,767] range.

unsigned short int Short unsigned integer type. Contains at least the [0, 65,535] range. 16 %hu

unsigned int Basic unsigned integer type. Contains at least the [0, 65,535] range. 16 %u

Long signed integer type. Capable of containing at least the


signed long int 32 %li or %ld
[−2,147,483,647, +2,147,483,647] range.
Primitive types
Conn’d
unsigned long Long unsigned integer type. Capable of containing at least the [0, 4,294,967,295]
32 %lu
int range.
Long signed integer type. Capable of containing at least the
signed long
[−9,223,372,036,854,775,807, +9,223,372,036,854,775,807] range. Specified since 64 %lli or %lld
int
the version of the standard.
unsigned long Long long unsigned integer type. Contains at least the [0,
64 %llu
int +18,446,744,073,709,551,615] range. Specified since the version of the standard.
Converting from
text:
Real floating-point type, usually referred to as a single-precision floating-point type. %f %F
float Actual properties unspecified (except minimum limits); however, on most systems, 16 %g %G
this is the IEEE 754 single-precision binary floating-point format (32 bits).
%e %E
%a %A
Primitive Types
Conn’d
Real floating-point type, usually referred to as a double-precision floating- %lf %lF
point type. Actual properties unspecified (except minimum limits); however, %lg %lG
double on most systems, this is the IEEE 754 double-precision binary floating-point 32
format (64 bits). This format is required by the optional Annex F "IEC 60559 %le %lE
floating-point arithmetic". %la %lA

Real floating-point type, usually mapped to an extended precision floating-


%Lf %LF
point number format. Actual properties unspecified. It can be either x86
%Lg %LG
long double extended-precision floating-point format (80 bits, but typically 96 bits or 128 80
%Le %LE
bits in memory with padding bytes), the non-IEEE "double-double" (128
%La %LA
bits),
Datatype Conn’d
• Function returned as void: a function that does not return any value
void add(int a, int b)
• Function argument as void: a function that has void parameter does
not accepts argument
int rand(void)
• Pointers to void: returns pointer to void which can be casted to any
datatype
void *malloc( size_t size );
• Enumerated type: is a user defined type which is used to assign
names to integral constants name which makes the program easier to
read and maintain
Variable and
Identifier
• A variable is a name given to a storage area that the program can
manipulate
• Variables governed by type e.g.
int a, char b, etc
• Variable declarations
int a, b, c[num] etc
• Global variable: accessible any where in a program and usually declared
outside any function
• Local variable: a variable that is accessible within a function
float r= 2.97; Global variable
main{
float circumference;
const float pi = 3.14; Local variable
circumference = pi*r;
}
Variable Pointers
• It is a variable that keeps memory address
int main(int argc, char** argv) {
int var = 100;
int* ptr = 0; initializing a pointer (nullptr in c++)
ptr = &var;
*ptr = 200; reference operator
return 0;
}
• One step-size of a char pointer is 1byite while a step-size of an int is
4bytes
• Relationship between pointer and value
Pointer Variable
Conn’d
• Valid Pointer declarations in C
 int* ptr = 0;
 int * ptr = 0;
 int *ptr = 0;
• Pointer variable types in C indirection
symbol
 int *ptr //and all other integer types
 float *ptr
 char *ptr
• The step-size of a pointer is the number of bytes a pointer will
reference at a type due to the datatype it points at
Pinter Variable
Conn’d
• Arithmetic of pointers with two different datatypes
int var = 1;
int* int_ptr = NULL; // nullify the pointer
int_ptr = &var;
char* char_ptr = NULL;
char_ptr = (char*)&var;
printf("Before arithmetic: int_ptr: %u, char_ptr: %u\n",
(unsigned int)int_ptr, (unsigned int)char_ptr);
int_ptr++; // Arithmetic step is usually 4 bytes
char_ptr++; // Arithmetic step in 1 byte
printf("After arithmetic: int_ptr: %u, char_ptr: %u\n",
(unsigned int)int_ptr, (unsigned int)char_ptr);
Variable Pointer with Array
#define SIZE 5
int arr[SIZE];
arr[0] = 9;
arr[1] = 22;
arr[2] = 30;
arr[3] = 23;
arr[4] = 18;
int* ptr = &arr[0];
for (;;) {
printf("%d\n", *ptr);
if (ptr == &arr[SIZE - 1]) {
break;
}
ptr++;
}
• Infinite loop is used which break when the address of ptr points to the last
element of the array (SIZE-1)
Pointer Variable
Conn’d
• Generic pointers: it’s called the void pointer because it points to any datatype. Hence,
can’t be dereferenced and does not have arithmetic step-size
• They can be typecasted to any datatype
• They are used to define generic functions that can accept a wide range of different
pointers as their input arguments
• It enables iterating over range of memory addresses one at a time and processing all of
those bytes one after the other
• Dereferencing a generic pointer is not possible:
int main(int argc, char** argv) {
int var = 9;
int* ptr = &var;
void* gptr = ptr;
printf("%d\n", *gptr);
return 0;
}
 On attempt to run above code, you get error code: invalid use of void expression
 Typecasting: printf(“%d\n”,*(int*)gptr) defines the pointer type hence resolves the void issue
Pointer Variable
Conn’d
• Common use: malloc() and calloc() return a void pointer. Hence, they can
allocate memory for any kind of data
void print_bytes(void* data, size_t length) {
char delim = ' ';
unsigned char* ptr = data;
for (size_t i = 0; i < length; i++) {
printf("%c 0x%x", delim, *ptr);
delim = ',';
ptr++;
}
printf("\n");
}
int main(int argc, char** argv) {
int a = 9;
double b = 18.9;
print_bytes(&a, sizeof(int));
print_bytes(&b, sizeof(double));
return 0;
}
Pointer Variable
Conn’d
• Size of pointer: c does not have specific size of a pointer. The sized depend on
the a computer architecture.
 It can be obtained using sizeof(), the return type of size_t (any type in byte)
• Dangling pointers: when a pointer points to an invalid address in a memory.
int* create_an_integer(int default_value) {
int var = default_value;
return &var;
}
int main() {
int* ptr = NULL;
ptr = create_an_integer(10);
printf("%d\n", *ptr);
return 0; dangling pointer: ptr will be left pointing to an invalid
} address after printing since the address it was
pointing at was a copy of var address. var is local
to 1st funct
Pointer Variable Conn’d
• Segmentation fault/crash: is when a pointer is used to read or modify
address where there is no variable registered or accessing memory
location where your program is not allowed to
#include <stdio.h>
int* create_an_integer(int default_value) {
int* var_ptr = (int*)malloc(sizeof(int));
*var_ptr = default_value;
return var_ptr;
}
int main() {
int* ptr = NULL;
ptr = create_an_integer(10);
printf("%d\n", *ptr);
free(ptr);
return 0;
}
Keywords
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Comments
• Comments are statements which do not involve in running of the
program but provide clarity for someone reading the source code
C uses both single and double line comments:
//This is a single line comment
/*This is a double line comment*/
Or
/*
* This is another form of a double line comment
*/
Constant
• It is a value/literals that a program should not alter during its
execution
 Literal integer
const int SIDE = 10;
 Integer
const long top = 215u; //unsigned
 const int 0xFeeL; //Long
 Literal float
const float 3.14;
 String constant
String const greeting = “Hello world”;
 Using the preprocessor
#define LENGTH 10
#define WIDTH 5
Control Structures
• They are decision making aimed at altering the flow of execution of a
program.
• These include:
 Sequence structure
 Select Structure
 Loop structure
• Sequence structure: execution of statements or instruction are made
one after the other, or serially
 A statement is a unit of instruction given to a computer by a programmer
• Select structure: an item is selected out of two or set of items for
execution
• Loop: it executes block of statements many times until the stated
condition becomes false
Select Structure
• Select control structures include:
 if
 if/else
 Switch
• if statement: it enables instruction to execute only if condition is met
if(score >= 40){
printf(“You pass”);
}
Select Structure
Conn’d
• if else statement: it executes a statement if the expression is true or
it will execute another statement if the expression is false
If(number % 2 == 0){
printf(“%c is even”, number);
}else{
printf(“%c is odd”, number);
}
Select Structure
Conn’d
• Nested if statement: it executes statements if more than one conditions are true
if(employed == “Y”){
if(recentGrad==“Y”){
printf(“Your qualify”);
}
}
• Nesting with if/else

if(employed == “Y”){
if(recentGrad==“Y”){
printf(“Your qualify”);
}
}
else{
printf(“Not qualified”);
}
Select Structure Conn’d
• if/else if statement: it tests series of statement where only one will
be executed. Example
if(score>=40){
printf(“You pass with E”,);
else if(score>=50){
printf(“You pass with D”);
}
else if(score>=60){
printf(“You pass with B”);
}
else if(score >=70){
printf(“You pass with A”);
}
else {
printf(“You fail”);
}
}
Select Structure Con
n’d
• Switch statement: it tests series of statement where only one of the statement will be selected to
execute just like the if/else if statement however it takes each of the expressions as a “case”.
switch(score){
case “1”:
printf(“N100 recharge is successful”);
break;
case “2”:
printf(“N200 recharge is successful”);
break;
case “3”:
printf(“N400 recharge is successful”);
break;
case “4”:
printf(“N500 recharge is successful”);
break;
case “5”:
printf(“N1000 recharge is successful”);
break
case “6”:
printf(“N1500 recharge is successful”);
break;
deafalt:
printf(“You quit. Bey…”);
}
Operations
• Operation it is the use of mathematics operators on operands
• An operator is a symbol that tells the compiler to perform a specific
mathematical operation on operands
• Types of operators include:
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Misc operators
• An operand is a number string or character that mathematical
operator act upon
Operations Conn’d
• Arithmetic operators: arithmetic operators are binary unary
operators that act upon operands to produce a result. Arithmetic
operators supported in c assuming operand A=10 and operand B= 20

Operator Description Example


+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
Modulus Operator and remainder of after an integer
% B%A=0
division.
Increment operator increases the integer value by
++ A++ = 11
one (unary operator).
Decrement operator decreases the integer value by
-- A-- = 9
one (unary operator).
Operations Conn’d
• Relational operator is any binary operator that compares between
two operands from left to right. These include:
• The following example assumes variables A=10 and B=20
Operator Description Example
Checks if the values of two operands are equal or
== (A == B) is not true.
not. If yes, then the condition becomes true.
Checks if the values of two operands are equal or
!= not. If the values are not equal, then the condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater than
> the value of right operand. If yes, then the condition (A > B) is not true.
becomes true.
Checks if the value of left operand is less than the
< value of right operand. If yes, then the condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater than or
>= equal to the value of right operand. If yes, then the (A >= B) is not true.
condition becomes true.
Checks if the value of left operand is less than or
<= equal to the value of right operand. If yes, then the (A <= B) is true.
condition becomes true.
Operations Conn’d
• Logic operator connect two or more relational operations into one or
revers the logic of operation
 Ideal logic operators include: logic AND operator, &&; logic OR operator, ||
and the logic NOT, ! Operator
• && operator could be used to simplify a nested if statement
Example: instead of
if(employed == “Y”){
if(recentGrad==“Y”){
printf(“You qualify for the bonus”);
}
}
if(employed==“Y” && recentGrad==“Y”){
printf(“You qualify for the bonus’);
}
Operations Conn’d
• Determining if a year is a leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
• Using the || operator to find range of values between 20 and 100;
if(temp< 20 || temp >100)
printf(“The temperature is in the danger zone”);
• Bitwise operators work on bits and perform bit by bit operations
 Assuming variables A=60 = 00111100 and B=13 = 00001101
A&B = 0000 1100
A|B = 0011 1101
A^B =00000001
~A = 11000011
Operations Conn’d
Assuming variables A = 60 = 00001100 and B = 13 = 00001101
Operator Description Example
Binary AND Operator copies a bit to the result if it
& (A & B) = 12, i.e., 0000 1100
exists in both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 00001101
operand.
Binary XOR Operator copies the bit if it is set in
^ (A ^ B) = 49, i.e., 00000001
one operand but not both.
Binary One's Complement Operator is unary and
~ (~A ) = ~(60), i.e,. 11110011
has the effect of 'flipping' bits.
Binary Left Shift Operator. The left operands value
<< is moved left by the number of bits specified by the A << 2 = 240 i.e., 00110000
right operand.
Binary Right Shift Operator. The left operands
>> value is moved right by the number of bits specified A >> 2 = 15 i.e., 00000011
by the right operand.
Operations Conn’d
• Assignment operator: assigns value or variable to a variable using single
sign of equality
Operator Description Example
Simple assignment operator. Assigns values from C = A + B will assign the value
=
right side operands to left side operand of A + B to C
Add AND assignment operator. It adds the right
C += A is equivalent to C = C +
+= operand to the left operand and assign the result to
A
the left operand.
Subtract AND assignment operator. It subtracts the
C -= A is equivalent to C = C -
-= right operand from the left operand and assigns the
A
result to the left operand.
Multiply AND assignment operator. It multiplies
C *= A is equivalent to C = C *
*= the right operand with the left operand and assigns
A
the result to the left operand.
Divide AND assignment operator. It divides the left
C /= A is equivalent to C = C /
/= operand with the right operand and assigns the
A
result to the left operand.
Modulus AND assignment operator. It takes
C %= A is equivalent to C = C
%= modulus using two operands and assigns the result
%A
to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

• NB:
and
Operations Conn’d
• Misc operator: is conditional operator which has 3 operands, the first operand is always
evaluated first. If nonzero, the second operand is evaluated, and that is the value of the
result.

Operator Description Example


sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
&a; returns the actual address of the
& Returns the address of a variable.
variable.
* Pointer to a variable. *a;
If Condition is true ? then value X :
?: Conditional Expression.
otherwise value Y
Operations Conn’d
• Operator precedence in c: it is used to determine how an expression is evaluated by
grouping of terms.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right


String
• A string is an array terminated by a null character ‘\0’
char greeting[6] = {'H', 'e', 'l', 'l', 'o’, ‘\0'};
char greeting[] = "Hello";

• It is not a primitive type thus it has header, <string.h>


 String operations
strcpy(s1, s2): copy S2 into S1
strcat(S1, S2): concatenate S2 into the end of S1
strlength(S1) return the length of S1
strcmp(S1, S2): compare S2 and S1, return 0 if they are the same
strncmp(S1, S2): compare first n character of S2 in S1
strchr(s1, ch): return a pointer to the first occurrence of character ch in string S1
strstr(s1, s2): return a pointer to the first occurrence of S2 in S1 or null if not present
Preprocessor
• It tells the compiler the library to use in compiling a program
Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif
Ends preprocessor conditional.
Input and Output
• printf(): a function used for printing to the console
printf(“Hello world”);
• Scanf(): a function used for accepting input from the console
scanf(“%c”, &ch) : to accept character where “%c” is the format
specifier
scanf(“%d”, &ch) : to accept integer where “%c” is the format
specifier
Compilation in c
Escape sequences in
c
• It is a sequence of characters that does not represent itself when used inside a
character or string literal, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly
Escape sequence Character represented
\a Alert (Beep, Bell)
\b Backspace
\e Escape character
\f Formfeed Page Break
\n Newline (Line Feed); see notes below
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\' Apostrophe or single quotation mark
\" Double quotation mark
\? Question mark (used to avoid trigraphs)
Function
• A function is a set/block of programming statements for carrying out a specific
task enclosed withing curly brackets, { }.
• It can be called many time to carry out specific task (reusability)
• It enhance clarity of source code
• A system can be divided into component function and be assign to different
developers
• Function declaration: void rectangle(float l, float b);
• Types of function:
 Library: inbuild, made up the header libraries e.g. scanf(), printf(), gets(), puts(),
ceil(), floor() etc.
 User-define: defined by programmer e.g. void cuboid(float l, float b, float h)
 Return: can be int, float char etc. e.g.
float get(){
return 10.2;
}
 Void: does not return value
Function Conn’d
• A function may not accept argument e.g.
int circle (void){
float r, pi=3.14;
return r*pi;
}
Function Prototype
• It is a declaration of a function that specifies the name of the function, return
type and the type signature/parameter
int addNumbers(int a, int b);
parameter of the function addNumbers
int is the function
type
• The parameter of a function is variable that accept argument that is passed to
the function
• An argument is value that is passed to a function usually contained in a
variable
• Function definition contains a block of codes to perform a specific task
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
Example of Function
Prototype
void findReactangleArea(float a, float b);
int main()
{
float x,y;
printf("Enter the length: ");
scanf("%f", &x);
printf("Enter the breadth: ");
scanf("%f", &y);
findReactangleArea(x, y);
return 0;
}
void findReactangleArea(float a, float b){
float res;
res = a*b;
printf("\n The area of this rectangle = %0.2f squared\n",res);
return;
}
Recursion
• Direct recursion: When a function calls itself it is said to be a
recursion
funct_one(){
funct_one();
}
• Indirect recursion: is when a function calls itself through another
function
void funct_one(){
funct_two();
}
void funct_two(){
funct_one();
}
Example: Fibonacci
Sequence
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}
int main() {
int n;
printf("Enter the nth term: ");
scanf("%d", &n);
int i;
printf("Fibbonacci of %d: " , n);
for(i = 0;i<n;i++) {
printf("%d ",fibbonacci(i));
}
Array
• Arrays are kind of data structure that can store a fixed-size sequential collection of
elements/variables of the same type (primitive and derived)
• Declaration:
type arrayName [ arraySize ];
double balance[10];
• Array initialization:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• Accessing array:
double salary = balance[9]; //accessing the 10th element of an array
Arrays Conn’d
• Array size
Array Conn’d
• Accessing array elements:
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Array Pointers
• Array pointers: is a data structure that stores a fixed-sized sequence
collection of pointers to primitive or derived datatypes
• Declaration
 int *ptr[MAX];
Example:
int var[] = {10, 100, 200};
int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */
}

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
Arrays Conn’d
• Two dimensional arrays: when an array has a number of rows and
columns it is said to be a 2-dimentional array
• Declaration of two-dimensional arrays;
 arrayName[rowSize][colSize];
• Assignment in two-dimensional array
int num[2][3] = {{8,0,3},
{7,9,1}}
Arrays Conn’d
• Accessing 2-dimentional arrays elements
int num[2][3];
int i, j; //i = number of element in row while j = column
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for num[%d][%d]:", i, j);
scanf("%d", &num[i][j]);
}
}
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", num[i][j]);
if(j==2){
printf("\n");
}
}
}
Arrays Conn’d
• 3-Dimentional array: is an array in which each element is identified by 3
indices. It is figuratively isometric or a 3-dimensional vector space.
• Declaration
int num[widthSize][rowSize][colSize];
• Assignment
int num[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Assignment
1. Write a program in c that multiply and display the result of two 3-
dimensional matrix using pointer variable
2. Write a program in c that generates n terms of Fibonacci sequence
where 2nd term =< 1
Enumeration
• It is a user-define type which is used to assign names to integral constants
because names are easier to handle in programs
 Syntax: enum enum_name{const1, const2, ....... };
 Example:
enum Bool {False, True};
int main(){
enum Bool var;
var = True; Integral constants
printf(“%d”, var); Declaration in global scope scope
return 0;
} Declaration in local scope
 If you don’t asign any value to the enumerants, the first with be be 0 and the value
increase in series
 It can be decleared in a local scope
 Names are initialized by the comiler
 Two or more names can have the same value: enum values{x=0, y=1, z=0};
Enumeration Conn’d
 All unasigned names will get value as value of previous name + 1
enum values{x=2, y=34, t, z=0}: t=35
 Only integral values are allowed (i.e. float is not allowed)
 All enum constants must be unique in the same scope
enum values1{x=2, y=9, z=6};
enum values2 {x=3, p=3, q=5} illegal: x can’t be in values1 and
values2
Structure
• It’s a user-defined datatype that allows to combine different kinds of
data items
• Syntax:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
• NB: tag is optional
Structure example
struct Books {
char title[50]; Structure type
char author[50];
char subject[100];
int book_id;
} book1, book2; Structure variable
• Assigning values to members of a structure
strcpy( book1.title, "C Programming");
strcpy( book1.author, "Nuha Ali");
strcpy( book1.subject, "C Programming Tutorial");
book1.book_id = 6495407;

strcpy( book2.title, "Telecom Billing");


strcpy( book2.author, "Zara Ali");
strcpy( book2.subject, "Telecom Billing Tutorial");
book2.book_id = 6495700;
Structure Conn’d
• Printing structure
printf( “Book 1 title : %s\n", book1.title);
printf( “Book 1 author : %s\n", book1.author);
printf( “Book 1 subject : %s\n", book1.subject);
printf( “Book 1 book_id : %d\n", book1.book_id);

printf( "Book 2 title : %s\n", book2.title);


printf( "Book 2 author : %s\n", book2.author);
printf( "Book 2 subject : %s\n", book2.subject);
printf( "Book 2 book_id : %d\n", ook2.book_id);
Function with
Structure
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
}book1, book2;
/* function declaration */
void printBook( struct Books book );

int main( ) {
struct Books book1; /* Declare Book1 of type Book */
struct Books book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
book1.book_id = 6495407;
Structure with Function
Conn’d
/* book 2 specification */
strcpy( book2.title, "Telecom Billing");
strcpy( book2.author, "Zara Ali");
strcpy( book2.subject, "Telecom Billing Tutorial");
book2.book_id = 6495700;
/* print Book1 info */
printBook( book1 );

/* Print Book2 info */


printBook( book2 );
return 0;
}
void printBook( struct Books book ) {

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
Structure Conn’d
• Accessing member of a structure with pointer
struct_pointer->title;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
printBook( &book1 );
/* print Book2 info by passing address of Book2 */
printBook( &book2 );
}
void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
Structure Conn’d
• Bit fields
 At memory premium, bit field is used for packing of data in a structure
• Commonly used:
 Packing several objects into a machine word
 Reading non-standard file format
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
 From above, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-
bit type and a 9-bit my_int.
Text stream
• Text stream: is a sequence of characters divided into lines
• Each line consists of zero or more characters followed by a new line, \
n, character.
Writing to a file with
int main()
{
FILE * fPointer;
fPointer =
fopen("C:/Users/Tensor/Desktop/abracadabra.txt", "w");
//use "a" to append to content of a file
fprintf(fPointer, "Text written by c program\n");
fclose(fPointer);
return 0;
}
Reading content of File with EOF
int main()
{
FILE * fPointer;
fPointer = fopen C:/Users/Tensor/Desktop/abracadabra.txt");
char singleLine[150]; //copy the content of texteditor to arr
while(!feof(fPointer)){
fgets(singleLine, 150, fPointer);
puts(singleLine);
}
foclose(fPointer);
return 0;
}
Memory Structure
• Lack of garbage collectors due to large memory allocation and
deallocation
• A process is a running program in the main memory which contains
process ID
• It can be stopped with the following commands
 SIGTERM: it’s a termination signal but allows the process to clean up
 SIGINIT: it’s an interrupt signal (ctr c) usually sent to the foreground process
 SIGKILL: it kills a process forcefully without clean up
• Segments of memory that came directly from the base executable
object files are called static memory layout
Memory Structure
Conn’d
• Process segments include:
 Block Start by Symbol (BSS)/Uninitialized global segment
 Text or Code/Initialized segment
 Data Segment
 Stack
 Heap
Memory Structure
Conn’d
• Block Started by Symbol (BSS): it contains uninitialized global
variables. The variables could be initialized here to zeros
• Text or Code segment: contains all the initialized global variables
• Issues with declaring all variables globally:
 Posses security issues as variables are not encapsulated
 Concurrency issues: data races, namespace pollution, unknown ownership,
and having too many variables in the global scope
• Data segment: global variables with assigned values (non-zero
initialization)
Memory Structure Conn’d
• Stack segment: static memory layout: is a dynamic content which its
size changes in a process
 It’s a LIFO data structure
 The size can be determined from the object file size, it can be larger at runtime
though
 Stack overflow occurs when function call overflows the stack segment
 The stack region is limited in size and can’t hold object of larger size.
 Objects like arrays should be declared in a global scope not local
 Local variables to a function are always places on top of a stack; to be pop first as
compiler gets out of the scope
• Probing the content of an executable (static layout) file on Unix (Linux)
size ex4_1-linux.out
• variables declared in a function are contained in the data segment
mostly
• Memory segments that are built at runtime are called dynamic memory
layout
Memory Structure Conn’d
• Dump the object of a file in Unix
objdump -s -j .data ex4_4.out
 -s an option to show full content of a chosen section and -j data is to show that
content of data section
• Loader spawn executable and creates an initial memory (dynamic) for
a process
• The loader creates the stack and heap memories
Memory Structure
Conn’d
• Heap segment: dynamic memory layout. Say allocating memories for:
 Arrays
 Streams
 Functions
 The size is determined by its process
 Can be access by pointers only
• The heap region is adjustable and holds big sized objects and huge arrays
• Unlike stack, heap memory sizes are allocated manually using the
following common functions: malloc(), calloc(), relloc()
• Has large memory size
• Allocation and deallocation of memory are managed be programmer
• Variables allocated from the heap do not have any scope
• Only pointers can be used to address a memory block
Common used
functions for
memory allocation
• malloc(): void *malloc(size_t, size) allocates the
requested memory and returns a pointer to it.
• calloc(): the void *calloc(size_t nitems, size_t
size) allocates the requested memory, initializes the memory to
0s and returns a pointer to it
• relloc(): the void *realloc(void *ptr, size_t
size) attempts to resize the memory block pointed to by ptr that
was previously allocated with a call to malloc or calloc
Using malloc()
void fill(char* ptr) {
ptr[0] = 'H';
ptr[1] = 'e';
ptr[2] = 'l';
ptr[3] = 'l';
ptr[5] = 0;
}
int main(int argc, char** argv) {
void* gptr = malloc(10 * sizeof(char));
char* ptr = (char*)gptr;
fill(ptr);
printf("%s!\n", ptr);
free(ptr);
return 0;
}
Initializing memory with malloc()
int main(int argc, char** argv) {
char* ptr = (char*)malloc(16 * sizeof(char));
memset(ptr, 0, 16 * sizeof(char)); // Fill with 0
memset(ptr, 0xff, 16 * sizeof(char)); // Fill with 0xff
free(ptr);
}
• Having a piece of allocated heap memory that has no pointer variable to it is called
memory leakage
• The free() function is specifically made to prevent memory leakage
Using calloc()
int main () {
int i, n;
int *arrNum;
printf("Number of elements to be entered:");
scanf("%d",&n);
arrNum = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
printf("Enter number %d: ",i+1);
scanf("%d",&arrNum[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ ) {
printf("%d ",arrNum[i]);
}
free( arrNum );
return(0);
}
Using relloc()
int main()
{
int *ptr, i, n;
printf("Initial size of the array is 4\n\n");
ptr = (int*)calloc(4, sizeof(int));
if(ptr==NULL)
{
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i < 4; i++)
{
printf("Enter element at index %d: ", i);
scanf("%d", ptr+i);
}
printf("\nIncreasing the size of the array by 5 elements ...\n ");
ptr = (int*)realloc(ptr, 9 * sizeof(int));
if(ptr==NULL)
{
printf("Allocation failed or insufficient memory");
exit(1); // exit the program
}
printf("\nEnter 5 more integers\n\n");
for(i = 4; i < 9; i++)
{
printf("Enter element at index %d: ", i);
scanf("%d", ptr+i);
}
printf("\nFinal array: \n\n");

for(i = 0; i < 9; i++)


{
printf("%d ", *(ptr+i) );
}
return 0;
}
Thank you

Bye…

You might also like