0% found this document useful (0 votes)
2 views12 pages

Programming Assignment

The document is an assignment for a computer programming course at Kampala International University, focusing on concepts such as selection statements, if-else structures, switch statements, pointers, and unions. It includes explanations, code examples, and real-life scenarios demonstrating the application of these programming constructs. Additionally, it outlines the differences between structures and unions, emphasizing memory allocation and usage scenarios.

Uploaded by

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

Programming Assignment

The document is an assignment for a computer programming course at Kampala International University, focusing on concepts such as selection statements, if-else structures, switch statements, pointers, and unions. It includes explanations, code examples, and real-life scenarios demonstrating the application of these programming constructs. Additionally, it outlines the differences between structures and unions, emphasizing memory allocation and usage scenarios.

Uploaded by

junioradam2808
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

KAMPALA INTERNATION UNIVERSITY IN TANZANIA

COMPUTING DEPARTMENT AND IT


COURSE TITLE: PRINCIPLE OF COMPUTER PROGRAMMING
COURSE CODE: CS 1102
YEAR: 1.1
LECTURE NAME: MR. CHARLES
ASSIGNMENT TYPE: INDIVIDUAL ASSIGNMENT
STUDENT’S NAME: ADAM SIMON DANDA
STUDENT REG NO: BCS/19364/2101/DT
Assignment Questions

Question 1: Selection

a) Explain the difference between if–else and switch/case statements.

ANSWER:

Primary different is that if-else statements evaluates general Boolean


expressions (true/false) and can handle complex conditions and values ranges,
WHILE switch statements test a single expression against a list of specific,
constant values for equality.

Aspect If-else statement Switch/case statement


Condition Evaluates a Boolean Tests for equality against constant
expression(true/false) values
Flexibility Highly flexible; handles Limited to simple, fixed value
complex conditions, ranges (e.g., comparisons of single expression.
x>10&&x<20), and multiple
variables.
Data type Can evaluate various data types Typically works with integral types
(integers, floats, characters, (integers, characters, enum) string
Booleans, strings, etc.). support depends on the language
version (e.g., Java SE 7+).
Execution flow Condition are checked Often uses a “jump table “ for
sequentially (linear search) faster access to the matching case
(constant time lookup)
Readability Can be difficulty to read and More readable and concise for
manage with many nested multiway bleaching based on a
condition single variable
b) Give two real-life examples where selection control structures are used.

ANSWER:

1). ATM Cash withdrawal:

Scenario: A user wants to withdraw $100

Selection logic: IF user account balance >=$100

THEN dispense $100, subtract from balance.

ELSE (balance <$100)

THEN display “Insufficient funds” message.

2) Ecommerce Order Processing (discount/shipping)

Scenario: A customer checks out with items in their cart.

IF cart total >=$50:

THEN Apply 10% discount AND offer free shipping.

ELSE IF cart total >=$20

THEN offer standard shipping (not free).

ELSE:

THEN Charge standard shipping fee.

Question 2: If Statement
Write a program that accepts a student's marks and prints:

● "Pass" if the marks are 50 or above


● "Fail" if the marks are below 50

ANSWER:

#include <stdio.h>

int main( )

int marks;

printf (“Enter the student’s mark: ’’)

scanf (“%d’’ , &marks);

if (marks >=50) {

printf (“pass\n”);

else {

printf(“Fail\n”);

return 0;

Question 3: Else-If Ladder


Write a program that accepts a student's score and displays the grade according to
the following:

● 80 – 100: A
● 70 – 79: B
● 60 – 69: C
● 50 – 59: D
● Below 50: F

ANSWER:

#include <stdio.h>

int main ( ) {

int score;

printf(“Enter student score:’’);

scanf(“%d”, &score);

if (score >=80 && score <=100) {

printf(“Grade: A\n”);

} else if (score >= 70 && score<=79){

printf(“Grade: B\n”);

} else if (score >= 60 && score<=69) {

printf(“Grade: C\n”);

} else if (score >=50 && score<=59) {

Printf(“Grade: D\n”);

} else if (score >=0 && score <50){

printf(“Grade: Fail\n);
} else {

Printf(“Invalid score entered.\n”);

return 0;

Question 4: Switch Statement

Write a program that displays the name of the day based on a number entered by
the user (1–7).

Example:

● 1 → Monday
● 2 → Tuesday
● …
● 7 → Sunday

ANSWER:

#include <stdio.h>

int main ( )

int week;

switch(week)
{

case 1:

printf(“Monday”);
break

case 2:

printf(“Tuesday”);

break;

case3:

printf(“Wednesday”);

break;

case 4:

printf(“Thursday”);

break;

case 5:

printf(“Friday”);

break;

case 6:

printf(“Saturday”);

break;

case 7:

printf(“Sunday”);

break;

default:

printf(“Invalid input! Please enter week number between 1-7.”);


}

return 0;

Question 5: Pointers
a) Explain pointers and provide ways in which they can be implemented.
ANSWER:
>Pointer is the programming variable that stores the memory address of
another variable rather than storing a direct data value (like 5, ‘a’, or 3.14).
> Pointers are fundamental for low-level memory manipulation, enhancing
efficiency by allowing a functions to modify variables outside their scope and
enabling dynamic memory allocation.
Key concepts in pointer implementation.
1) Declaration (*): Tells the compiler that the variable stores and address of a
specific data type.
2) Initialization (&): Uses the “address-of” operator to store the address of an
existing variable.
3) Differencing (*): Uses the pointer to access or modify the data stored at that
address.
Ways Pointers are implemented
1) Basic pointers (Integer Pointer) this is the most common form, holding
the address of a standard variable.
E.g., of C program
#include <stdio.h>
int main( ) {
int var =10;
int *ptr;
ptr = &var;
printf (“Address: %p\n”, ptr);
printf (“Values: %d\n”, *ptr);
*ptr =20;
return 0;
}
2) Pointer to pointer (Double pointer) A pointer that stores the address of
another pointer.
E.g., of program
int var = 5;
int *ptr =&var;
int **dptr =&ptr;
3) Pointer to function (function pointer) Stores the address of a function,
allowing it to be passed as argument or invoked dynamically. E.g., of
program
void sayHello( ) {
printf(“Hello!”);
}
void (*funcPtr) ( ) =&sayHello;
funcptr( );
4) Pointer arithmetic: Since pointer are addresses (numerical values); they
can be incremented or decremented to navigate to through contiguous
memory, such as arrays.
E.g. program
int arr[3] ={10,20,30};
int *ptr = arr;
ptr++;
5) Dynamic memory allocation: pointers are essential for allocating
memory on the heap at runtime when the size is unknown at compile
time.
e.g. program
int *ptr =(int*)malloc(5 *sizeof (int));
free(ptr);

b) Write a program to swap two numbers using pointers.


ANSWER:
#include <stdio.h>
Void swap (int *x, int *y) {
int temp;
temp = *x;
*x =*y;
*y =temp;
}
int main( ) {
int num1, num2;
printf (“Enter value of num1: ”);
scanf (“%d”, &num1);
printf (“Enter value of num2: ”);
scanf (%d”, &num2);
printf (“\nBefore swapping: num1 is: %d, num2: %d\n”, num1, num2);
swap (&num1, &num2);
printf (“After swapping: num1 is %d, num2 is: %d\n”, num1, num2);
return 0;
}

Question 6: Unions
a) State the difference between a structure and a union.
ANSWER:
Structure (struct) and unions (union) are user defined data types in C, but they
differ primarily in memory allocation and member access. Structures are
allocate unique, separate memory for every member, allowing all to hold values
simultaneously. Unions allocate a single shared memory location for all
members, meaning only one member can be safely accessed at a time.
Feature structure Union
Memory Each member has its own, All members share the
unique memory allocation. same memory
allocation.
Size Sum of sizes of all members Size of the largest
(plus padding) member.
Simultaneous All members can be used at Only one member can
access once be used at a time
Data overwriting Modifying one member does Modifying one member
not affect others affects other members
Use case Storing complex, mixed data Memory sensitive
types (e.g., student record). applications, type-
punning.

b) When should a union be used instead of a structure?


ANSWER:
A union should be used instead of a structure to save memory when you need to
store only one of several possible data type at a time, or when members are
mutually exclusive (never used simultaneously).
While structures store all members independently, unions share a single
memory space equal to their largest member.
The scenarios for using a Union
>Memory-constrained systems: When optimizing memory usage in embedded
systems or when dealing with large arrays of data.
>Mutually exclusive data: When a variable can hold different data types but
only one at a time (e.g., a variant type that is either an integer, float, or string)
>Alternative data views: When you need to reinterpret the same memory block
differently (e.g., accessing a 32-bit integer as form individual 8-bit bytes)
>Discriminated unions: Using a union inside a structure along with a tag field
to manage complex, variant data types securely.

You might also like