4.ICP - Writing structured code
4.ICP - Writing structured code
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;
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;
2
- C#: A programming language developed by Microsoft for building
Windows applications and .NET framework.
3
- Operations (such as arithmetic, logical, and comparison)
manipulate data and perform calculations.
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.
- For conditional statements: We use if, else if, and else statements
to control the flow of execution based on certain conditions.
4
condition, we use keywords like break and continue to control the
flow within loops and switch statements.
-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.
-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.
5
/*Using error codes for error handling*/
#include <stdio.h>
int main() {
int num = -5;
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>
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;
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.