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

SP Topic 4 & 5 - Program Writing & Control Structures

Uploaded by

denisnzyoka14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

SP Topic 4 & 5 - Program Writing & Control Structures

Uploaded by

denisnzyoka14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

STRUCTURED PROGRAMMING

TOPIC 4: PROGRAM WRITING


WRITING A PROGRAM IN A STRUCTURED PROGRAMMING LANGUAGE
A C program typically consists of a series of statements that are written in the C programming language. The
program is written in a text file with a ".c" extension and can be compiled and executed by a C compiler.
Here is a general structure of a C program:
1. Preprocessor Directives: These directives are used to include header files or perform macro
expansions before the program is compiled. They usually begin with a '#' symbol. Common
examples include "#include" for including standard or user-defined header files and "#define" for
defining constants or macros.
2. Function Declarations: In C, functions are the building blocks of a program. Function declarations
specify the return type, name, and parameters of the functions used in the program. Typically, the
"main()" function is the entry point of the program and is required in every C program.
3. Global Variables: Global variables are declared outside of any function and can be accessed by all
functions in the program. They hold values that are available throughout the execution of the
program.
4. Function Definitions: Function definitions provide the implementation of the functions declared
earlier. They consist of a block of code enclosed within curly braces. Functions can perform specific
tasks and may return values to the calling code if specified.
5. Statements and Expressions: C programs contain statements that perform actions or control the
flow of execution. Common statements include assignment statements, control structures (e.g., if-
else, loops), and function calls. Expressions are combinations of operators and operands that produce
a value.
6. Comments: Comments are used to add explanatory notes within the code. They are not executed and
are ignored by the compiler. Comments can be single-line (denoted by //) or multi-line (enclosed
between /* and */).
7. Libraries and Header Files: C programs often make use of external libraries and header files to
access pre-defined functions and structures. These files provide additional functionality and are
included using the preprocessor directives.
Overall, a C program consists of a collection of functions, statements, and expressions that work together to
achieve a specific goal. It follows a procedural programming paradigm and can be compiled into an
executable file that can be run on a compatible system.

FORMAT SPECIFIERS IN C PROGRAMMING


In C programming, format specifiers are used in functions like printf() and scanf() to specify the type and
formatting of the variables being read from or written to the console. Here are some commonly used format
specifiers:
1. Integer Specifiers:
• %d - Used for printing or scanning decimal (integer) values.
• %u - Used for printing or scanning unsigned decimal values.
• %o - Used for printing or scanning octal values.
• %x or %X - Used for printing or scanning hexadecimal values.
2. Floating-Point Specifiers:
• %f - Used for printing or scanning float values.
• %lf - Used for printing or scanning double values.
• %e or %E - Used for scientific notation of float or double values.
• %g or %G - Used for printing or scanning float or double values in either normal or
scientific notation, depending on the value.
3. Character Specifiers:
• %c - Used for printing or scanning characters.
4. String Specifiers:
• %s - Used for printing or scanning strings.
5. Pointer Specifiers:
• %p - Used for printing pointer addresses.

FORMATTING & INDENTATION - NEWLINE CHARACTER


In C programming, the escape sequence \n represents a newline character. When it is encountered within a
string or character literal, it causes the cursor to move to the beginning of the next line.
The newline character is used to insert line breaks in output or to start a new line when printing text to the
console. It is often used along with printf() or puts() functions to format output or improve readability.
Here's an example to demonstrate the use of \n:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
printf("This is a new line.\n");
printf("I am on the next line.\n");

return 0;
}

Here are some examples of questions that can be used to practice C programming:
1. Write a C program to calculate the sum of two numbers entered by the user.
#include <stdio.h>
int main() {
int num1, num2, sum;

// Read the first number from the user


printf("Enter the first number: ");
scanf("%d", &num1);

// Read the second number from the user


printf("\nEnter the second number: ");
scanf("%d", &num2);

// Calculate the sum


sum = num1 + num2;

// Display the result


printf("\nThe sum is: %d\n", sum);

return 0;
}
2. Develop a C program that prompts a student’s name and calculates the total and average of that
student based on their marks for three subjects.

#include <stdio.h>

int main() {
char name[50];
float marks1, marks2, marks3, total, average;

// Read the student's name


printf("Enter the student's name: ");
scanf("%s", name);

// Read the marks for three subjects


printf("Enter the marks for the three subjects:\n");
scanf("%d %d %d", &marks1, &marks2, &marks3 );

// Calculate the total marks


total = marks1 + marks2 + marks3;

// Calculate the average marks


average = total / 3;

// Display the student's name, total marks, and average marks


printf("\nStudent Name: %s\n", name);
printf("Total marks: %.2f\n", total);
printf("Average marks: %.2f\n", average);

return 0;
}
3. Develop a program that converts temperature from Fahrenheit to Celsius.
To convert temperature from Fahrenheit to Celsius, you can use the following formula:
Celsius = (Fahrenheit - 32) * 5/9
Here's a C program that demonstrates the conversion:
#include <stdio.h>
int main ()
{
float fahrenheit, celsius;

// Read the temperature in Fahrenheit from the user


printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);

// Convert Fahrenheit to Celsius using the formula


celsius = (fahrenheit - 32) * 5 / 9;
// Display the converted temperature in Celsius
printf("\n Temperature in Celsius: %.2f\n", celsius);

return 0;
}
HANDLING ERRORS
In C programming, error handling is essential to ensure robust and reliable software. Here are some common
techniques and concepts for handling errors in C:
1. Return Values: Functions can return a value indicating success or failure. Typically, a return value
of 0 or a negative number represents an error, while a positive value indicates success. By checking
the return values of functions, you can detect and handle errors appropriately.

2. Error Codes: Error codes are specific values assigned to different types of errors. Functions can
return an error code that describes the encountered error. You can define your own set of error codes
or use predefined ones, such as those provided by the standard library.

3. Resource Management: Proper resource management is crucial for avoiding errors. Ensure that
resources like memory, file handles, and network connections are correctly allocated, used, and
released. Failure to do so can lead to memory leaks, file corruption, or other errors.

4. Logging: Incorporating logging mechanisms can help capture and track errors during program
execution. You can log error messages, stack traces, and other relevant information to aid in
debugging and error diagnosis.
Remember to handle errors gracefully and provide meaningful error messages to users or log files to aid in
troubleshooting. Proper error handling improves program reliability, maintainability, and user experience.
TOPIC 5: CONTROL STRUCTURES
MEANING AND IMPORTANCE OF CONTROL STRUCTURES
Controlled structures typically refer to control flow statements or constructs that allow you to control the
flow of execution in your program based on certain conditions.
These structures help you make decisions and repeat certain blocks of code based on those decisions.
Importance of control structures:
1. Decision making: Controlled structures allow you to make decisions in your code based on certain
conditions. This enables your program to choose different paths of execution, perform specific
actions, or handle various scenarios dynamically.
2. Flow control: Controlled structures provide mechanisms to control the flow of execution in your
program. Loops allow you to repeat a block of code multiple times, enabling efficient handling of
repetitive tasks and iterative processes.
3. Code efficiency: Controlled structures allow you to optimize your code by selectively executing
certain blocks of code based on conditions. By using if-else statements or switch statements, you can
avoid executing unnecessary code, which can lead to improved performance and efficiency.
4. Code reusability: Controlled structures promote code reusability and modularity. By encapsulating
blocks of code within functions or loops, you can easily reuse them in different parts of your
program, avoiding code duplication and improving maintainability.
5. User interaction: Controlled structures enable interaction with users or external systems by
providing conditional checks and input validation. For example, you can prompt users for input,
validate the input using if statements, and respond accordingly based on their choices.
TYPES OF CONTROL STRUCTURES
1. SEQUENCE
The sequence structure is the simplest type of control structure, where statements are executed in a
sequential order, one after another. It represents the default flow of execution in a program. Each statement
is executed once, following the one preceding it.
Syntax: Flowchart:
Start
Statement 1;
Statement 2;
Statement 3;
Stop

Example:
# include <stdio.h>
int main()
{
int a = 5, b = 10, sum;
sum = a + b; // Statements executed in
sequence
printf(“The sum of %d and %d is %d”, a,
b, sum);
return 0;
}
2. SELECTION
The selection structure allows the program to make decisions based on certain conditions. It is implemented
using the following constructs:
a. IF statement: It allows the program to execute a block of code if a given condition is true. If
the condition is false, the block is skipped.
Syntax for IF statement:
if (condition)
{
// Code block to be executed if the condition is true
}

Explanation:
• The keyword "if" is followed by a condition enclosed in parentheses "()".
• The condition is an expression that evaluates to either true or false.
• If the condition is true, the code block enclosed in curly braces "{}" is executed.
• If the condition is false, the code block is skipped, and program execution continues with the next
statement after the if block.

Flowchart for IF statement: Example:


#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num > 0)
{
printf("The number is positive.\n");
}
printf(“This is the rest of the program\n”);
return 0;
}

In the above example, if the value of variable "num" is greater than 0, the statement "The number is
positive" will be printed to the console. If the condition is false, nothing will be printed, and the program
will continue to the next statement after the if block.
b. IF-ELSE statement: This structure extends the if statement by providing an alternative
block of code to execute when the condition is false.
Syntax for IF-ELSE statement:
if (condition)
{ Flowchart for IF-ELSE statement
// Code block to be executed if the condition is
true
}
else
{
// Code block to be executed if the condition is
false
}
Example:
#include <stdio.h>
int main() {
int num;
printf("Enter a number:\n");
scanf("%d", &num);
if (num > 0)
{
printf("The number is positive.\n");
}
else
{
printf("The number is negative.\n");
}
printf(“This is the rest of the program.\n”);
return 0; }

c. nested if-else statement: You can nest if-else statements inside each other to handle more
complex conditions.
Syntax for nested if-else statements:
if (condition1)
{
// code to be executed if condition1 is true
if (condition2)
{
// code to be executed if condition1 and condition2 are true
}
else
{
// code to be executed if condition1 is true and condition2 is false
}
}
else
{
// code to be executed if condition1 is false
if (condition3)
{
‘// code to be executed if condition1 is false and condition3 is true
}
else
{
// code to be executed if condition1 is false and condition3 is false
}
}

Flowchart for nested if statements Example:


#include <stdio.h>
int main()
{
int percentage;
printf("Enter your percentage: ");
scanf("%d", &percentage);

if (percentage >= 0 && percentage <= 100)


{
if (percentage >= 90)
printf("Grade: A\n");
else if (percentage >= 80)
printf("Grade: B\n");
else if (percentage >= 70)
printf("Grade: C\n");
else if (percentage >= 60)
printf("Grade: D\n");
else
printf("Grade: F\n");
}
else
printf("Invalid percentage
entered.\n");
return 0;
}

a) Switch statement: It allows the program to select one of many possible paths of execution
based on the value of an expression or variable.
Syntax for switch statement:
switch (expression) {
case constant1:
// code to be executed when expression matches constant1
break;
case constant2:
// code to be executed when expression matches constant2
break;
case constant3:
// code to be executed when expression matches constant3
break;
// ...
default:
// code to be executed when expression doesn't match any constant
}

Example
#include <stdio.h>
int main()
{
int number;
printf("Enter a number between 1 and 5: ");
scanf("%d", &number);

switch(number)
{
case 1:
printf("You entered number one.\n");
break;
case 2:
printf("You entered number two.\n");
break;
case 3:
printf("You entered number three.\n");
break;
case 4:
printf("You entered number four.\n");
break;
case 5:
printf("You entered number five.\n");
break;
default:
printf("Invalid input. Please enter a number between 1 and 5.\n");
break;
}

return 0;
}
Flowchart for switch statement
3. LOOPING/ITERATION
Looping or iteration in C programming allows you to repeat a block of code multiple times. There are
several types of loops in C that you can use:
while loop: The while loop repeatedly executes a block of code as long as the given condition is true. It is
useful when you don't know the exact number of iterations in advance.
Syntax for while loop:
while (condition) {
// Code to be repeated
}
Flowchart for while loop Example
#include <stdio.h>

int main() {
int i = 1;

while (i <= 5) {
printf("%d\n", i);
i++;
}

return 0;
}
do-while loop: The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once before checking the condition.
Syntax for do-while loop
do {
// Code to be repeated
} while (condition);
Flowchart for do-while loop Example
#include <stdio.h>

int main() {
int i = 1;

do {
printf("%d\n", i);
i++;
} while (i <= 5);

return 0;
}

for loop: The for loop is a commonly used loop that allows you to specify an initialization, condition, and
increment/decrement in a compact manner. It repeats a block of code as long as the condition is true.
Syntax for For loop
for (initialization; condition; increment/decrement) {
// Code to be repeated
}
Flowchart for FOR loop Example
#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 5; i++) {


printf("%d\n", i);
}

return 0;
}

You might also like