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

4.ICP - Writing structured code

Uploaded by

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

4.ICP - Writing structured code

Uploaded by

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

Writing structured code

Writing structured code involves:

i) Creating variables of a given type.

a) Identify type required for a given situation

There are several data types for different situations which include:

- Integer: Use `int` for whole numbers without decimal places. For
example, if you want to store a person's age, you can create a
variable like int age;

- Floating-point: Use float for numbers with decimal places. For


example, if you want to store a person's height, you can create a
variable like float height;

- Character: Use char to store individual characters. For example, if


you want to store a person's initial, you can create a variable like
char initial;

b) Create an instance of a type.

To create an instance of a type in C, you need to allocate memory


and initialise it as below:

Integer
// Creating an integer variable and initialise it with a value
int age = 25;

Floating-point
// Creating a float variable and initialise it with a value
float height = 1.75;

1
Character
// Creating a character variable and initialise it with a value
char initial = 'J';

Boolean
// Creating an integer variable and initialise it with a value
int isLightOn = 1;

In C, you don't generally need to explicitly allocate memory for


these variables as they are allocated automatically when you
declare them. However, if you want to create dynamic variables,
you can use functions like malloc() or calloc() to allocate memory
on the heap. Moreover to free the allocated memory when you no
longer need it you use the free() function.

ii) Writing sequences of code and control the flow of execution


with branches.

a) Choose the programming language to use


The choice of programming language depends on the specific
requirements and constraints of the program.

Commonly used languages for different purposes

- Java: A general-purpose language that is widely used for building


desktop, web, and mobile applications.

- C: A programming language commonly used for operating system


programming and embedded systems.

- PHP: A server-side scripting language used for web development.

2
- C#: A programming language developed by Microsoft for building
Windows applications and .NET framework.

- Python: A versatile language known for its simplicity and


readability. It is used for a wide range of applications, including web
development, data analysis, and artificial intelligence.

b) Enable a program to run


To enable a program to run, you need to write code in a structured
and organised manner. Some of the key concepts of doing this
include:

- Breaking down the program into smaller, manageable chunks


called functions or methods, which perform specific tasks.

- Ensuring that the code is logically organised and follows a proper


flow.

- Using appropriate naming conventions for variables, functions,


and classes to make the code readable and maintainable.

c) Take note of key words


Different programming languages have different keywords,
variables, operations, and predefined classes. You need to refer to
the documentation or language specification of the specific
programming language you are using to understand how these
elements are used.

- Keywords are reserved words in a programming language that


have special meaning and cannot be used as variable names.

- Variables store data that can be accessed and manipulated in the


program.

3
- Operations (such as arithmetic, logical, and comparison)
manipulate data and perform calculations.

- Predefined classes are built-in classes provided by the


programming language or its libraries to perform common tasks.
They have methods and properties that can be used to interact with
the data.

d) Adhere to syntax
Each programming language has its own syntax rules that
determine how code should be written. You need to follow these
rules to ensure that the code is valid and interpretable by the
language. Syntax errors can prevent the program from running or
cause unexpected behaviour.

e) Control the flow of execution


The flow of execution in a program can be controlled through the
use of branches, which include conditional statements and jump
instructions.

- For True/False decisions: We use conditional statements, such as


if-else or switch statements, to make decisions based on the
evaluation of a condition. The program takes different paths
depending on whether the condition is true or false.

-For Multiple branch decisions: We use nested if-else statements or


switch statements with multiple cases to handle multiple conditions
and choose different paths of execution.

- For conditional statements: We use if, else if, and else statements
to control the flow of execution based on certain conditions.

- Jump instructions: In Using looping constructs like for, while, and


do-while loops to repeat a section of code multiple times based on a

4
condition, we use keywords like break and continue to control the
flow within loops and switch statements.

iii) Structuring units of code into subroutines or functions


-Structuring code into subroutines or functions is a fundamental
principle of modular programming. It helps to organise code into
logical units, making it easier to understand, maintain, and reuse.

-In Structuring units of code, You break down the program into
smaller, self-contained functions or subroutines that perform
specific tasks. Each function should have a well-defined purpose,
making it easier to understand and test.

-Use appropriate syntax and conventions: Write functions or


subroutines using the correct syntax for the programming language
you are working with. Follow naming conventions and coding
standards to ensure consistency and readability.

-Identify data input and output: Determine the data input required
by each function or subroutine. This includes any parameters or
arguments that need to be passed into the function for it to perform
its task. Also, identify the expected output or return value from the
function.

-Handle errors/failures: Decide on an appropriate method to


indicate errors or failures to the caller of the function. This can be
done using return values, error codes, exceptions, or other
mechanisms depending on the programming language and the
specific requirements of the program.

5
/*Using error codes for error handling*/
#include <stdio.h>

int check_error_code(int num) {


if (num < 0) {
return -1; // Error code: negative number
}
return 0; // Success
}

int main() {
int num = -5;

int ret_error_code = check_error_code(num);


if (ret_error_code == -1) {
printf("Error (Error Code): Negative number\n");
} else {
printf("Result (Error Code): Number is non-negative\n");
}

return 0;
}

-If the input num is less than 0, the function returns an error code -1 to indicate a negative
number.
-If the input num is non-negative, the function returns 0 to indicate success.

6
/*Using return values for error handling*/
#include <stdio.h>

int check_return_value(int num) {


int ret = 0;

if (num < 0) {
return -1; // Error code: negative number
}

if (num % 2 == 0) {
ret = 1; // Warning: even number
}

return ret;
}

int main() {
int num = -5;

int ret_return_value = check_return_value(num);


if (ret_return_value == -1) {
printf("Error (Return Value): Negative number\n");
} else if (ret_return_value == 1) {
printf("Warning (Return Value): The number is even\n");
} else {
printf("Result (Return Value): The number is odd\n");
}

return 0;
}

-If the input num is less than 0, the function returns an error code -1 to indicate a negative
number.
-If the input num is non-negative and even, the function returns a warning value 1 to indicate
an even number.
-If the input num is non-negative and odd, the function returns 0 to indicate success.

You might also like