SP Topic 4 & 5 - Program Writing & Control Structures
SP Topic 4 & 5 - Program Writing & Control Structures
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;
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;
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;
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.
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
}
}
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;
return 0;
}