National Institute of Public Administration
Course Code: BC2010
Course Name: Programming with C
Student ID: 2023001588
Student Name: Kondwani Nyanga
Title: Exercise 2
Due Date: 2024
TABLE OF CONTENT
INTRODUCTION...........................................................................................................................................2
Question 1: Create a program that identifies if a number is a palindrome.................................................3
Question 2: Write a program to identify if a number is an Armstrong number.........................................10
Question 3: Create a program that prints the Fibonacci series.................................................................15
Question 4: Write a program to convert a decimal number to a binary number......................................19
INTRODUCTION
Programming is essential for effectively resolving challenging real-world issues. Widely utilized
in many software development sectors, the C programming language is renowned for its
performance and command over system resources. Through real-world situations, this exercise
offers a chance to investigate basic C programming concepts. This exercise attempts to
strengthen fundamental programming skills by creating programs for typical computational tasks
like recognizing palindromes, Armstrong numbers, creating Fibonacci sequences, and converting
decimal numbers to binary.
This exercise's programs show how to use fundamental programming components like loops,
conditionals, arrays, and user input handling. Every program aims to teach effective problem-
solving strategies, fundamental algorithmic thinking, and numerical manipulation. In subsequent
assignments, more complex programming tasks will be built upon the knowledge acquired from
creating and evaluating these programs.
LABORATORY WORK
Question 1: Create a program that identifies if a number is a palindrome.
Aim:
This program's objective is to figure out whether an integer entered by the user is a palindrome.
A number that reads the same both forward and backward is called a palindrome. In order to
accomplish this, the program will extract each digit of the number, reverse their order, and
compare the original digit sequence with the reversed sequence. The software will report that the
number is a palindrome if the sequences match; if not, it will indicate that it is not.
Task Description
Step 1: Initialize variables:
UserInput: stores the integer input from the user
PlaceHolderCounter: counter for the number of digits in the input
DivisionResultInt: stores integer division result - loop: loop control variable (initially set to 0)
CurrentPlaceHolderInt: stores the current extracted digit as an integer
DivisionResultDouble: stores the intermediate division result as a double
CurrentPlaceHolderDouble: holds the decimal part of the division result
UserInputValues: array to store digits of UserInput
UserInputValuesReverser: array to store digits in reverse order
PlaceHolderCounterReverser: counter for the reversed array of digits
PlaceHolderCounter2, ArrayComparingVar, CurrentPlaceHolderDouble2: auxiliary variables for
reversing and comparing arrays
Step 2: Prompt user to enter an integer:
Print "Input Number:"
Read integer input from user and store in UserInput
Step 3: Initialize DivisionResultDouble with UserInput
Step 4: Extract digits from UserInput and store them in UserInputValues array:
WHILE (loop == 0):
o Divide DivisionResultDouble by 10 to shift the number one digit to the right
o Set DivisionResultInt to integer part of DivisionResultDouble
o Calculate decimal remainder by subtracting DivisionResultInt from DivisionResultDouble
o Add a small offset to CurrentPlaceHolderDouble to avoid rounding issues
o Multiply CurrentPlaceHolderDouble by 10 to get the digit
o Convert CurrentPlaceHolderDouble2 to integer and store in CurrentPlaceHolderInt
o Store CurrentPlaceHolderInt in UserInputValues[PlaceHolderCounter]
o Increment PlaceHolderCounter
o IF (DivisionResultDouble < 0.9):
Set loop to 1 to exit
Step 5: Prepare to reverse the digits:
Set loop to 0, PlaceHolderCounterReverser to PlaceHolderCounter, PlaceHolderCounter2 to -1
Step 6: Reverse digits from UserInputValues and store in UserInputValuesReverser:
WHILE (loop == 0):
o Store UserInputValues[PlaceHolderCounter2] in
UserInputValuesReverser[PlaceHolderCounterReverser]
o Increment PlaceHolderCounter2
o Decrement PlaceHolderCounterReverser
o IF (PlaceHolderCounter2 > PlaceHolderCounter):
Set loop to 1 to exit
Step 7: Compare UserInputValues and UserInputValuesReverser to check if UserInput is a palindrome:
Set loop to 0, ArrayComparingVar to 0
WHILE (loop == 0):
o IF (UserInputValuesReverser[ArrayComparingVar] equals
UserInputValues[ArrayComparingVar]): Increment ArrayComparingVar
o ELSE: Print "Input is not a Palindrome" EXIT program c. IF (ArrayComparingVar >
PlaceHolderCounter): Print "Input is a Palindrome" Set loop to 1 to exit
Step 8: Return 0 to indicate successful completion
METHOD/ ALGORITHM
1. Declare UserInput to store the integer input from the user.
2. Set PlaceHolderCounter to 0 to track the number of digits processed.
3. Declare DivisionResultInt, DivisionResultDouble, loop (set to 0), CurrentPlaceHolderInt, and
CurrentPlaceHolderDouble for intermediate calculations.
4. Create arrays UserInputValues and UserInputValuesReverser to store the digits and their
reverse order.
5. Declare additional variables for reversing and comparing arrays
(PlaceHolderCounterReverser, PlaceHolderCounter2, ArrayComparingVar).
6. Display a message "Input Number: ".
7. Read the integer input and store it in UserInput.
8. Set DivisionResultDouble to UserInput.
9. Repeat until all digits are extracted:
I. Divide DivisionResultDouble by 10 to shift digits to the right.
II. Assign the integer part of DivisionResultDouble to DivisionResultInt.
III. Calculate the decimal part (CurrentPlaceHolderDouble) as DivisionResultDouble -
DivisionResultInt.
IV. Add a small offset (0.000005) to handle precision issues.
V. Multiply CurrentPlaceHolderDouble by 10 to get the current last digit as a whole
number.
VI. Convert this result to an integer (CurrentPlaceHolderInt) and store it in
UserInputValues[PlaceHolderCounter].
VII. Increment PlaceHolderCounter.
VIII. If DivisionResultDouble is less than 1:
10. Reset loop to 0.
11. Set PlaceHolderCounterReverser to PlaceHolderCounter - 1 (position of the last digit in
UserInputValues).
12. Set PlaceHolderCounter2 to 0 (start of UserInputValues).
13. Repeat until all digits are reversed:
I. Assign UserInputValues[PlaceHolderCounter2] to
UserInputValuesReverser[PlaceHolderCounterReverser].
II. Increment PlaceHolderCounter2 and decrement PlaceHolderCounterReverser.
III. If PlaceHolderCounter2 exceeds PlaceHolderCounter:
14. Reset loop to 0.
15. Set ArrayComparingVar to 0.
16. Repeat until all digits are compared:
I. If UserInputValues[ArrayComparingVar] equals UserInputValuesReverser[ArrayComparingVar]:
a. Increment ArrayComparingVar.
II. Else:
a. Display "Input is not a Palindrome" and exit the program.
III. If ArrayComparingVar exceeds PlaceHolderCounter:
a. Display "Input is a Palindrome" and exit the loop (set loop to 1).
17. Return 0 to indicate successful completion.
PROGRAM CODE
CONCLUSION
This application effectively determines if a user-inputted integer is a palindrome. The software
extracts, stores, and reverses the number's digits, then compares the original and reversed
sequences to see if they match. If they do, the software verifies that the number is a palindrome;
if not, it makes a note to that effect. In the process, the program reinforces fundamental
programming concepts like loops, conditional statements, and receiving user input while
demonstrating a method of manipulating numbers and basic array operations. This method works
well for checking for palindromic integers and can be modified for various programming
comparisons or digit-based manipulations.
Question 2: Write a program to identify if a number is an Armstrong
number.
Aim:
This program's objective is to identify if an integer is an Armstrong number, sometimes referred
to as a narcissistic number. A three-digit number that equals the sum of the cubes of its digits is
known as an Armstrong number. After extracting the input number's component digits and
raising each one to the power of three, the software determines whether the sum of these cubes
equals the original number. The program recognizes the number as an Armstrong number if the
total equals the original number; if not, it does not.
Task Description
Step 1:Declare UserInput, PlaceHolderCounter, DivisionResultInt, loop,
CurrentPlaceHolderInt, BaseCounter, Sum, Base, PowerFinder, Indice,
NewPlaceHolderCounter
Step 2:Declare PlaceHolderValues[1000]
Step 3:Display "Armstrong number: "
Step 4:Read UserInput from user
Step 5:DivisionResultDouble equate it to UserInput
Step 6:PlaceHolderCounter equate it to 0
Step 7:loop equate it to 0
Step 7:Indice equate it to 3
Step 8:WHILE loop is equal to 0, DivisionResultDouble will be equated to
DivisionResultDouble divided by 10, equate DivisionResultInt to integer part of
DivisionResultDouble, Equate CurrentPlaceHolderDouble to DivisionResultDouble
minus DivisionResultInt, equate CurrentPlaceHolderInt to CurrentPlaceHolderDouble
multiplied by 10, equate PlaceHolderValues at the PlaceHolderCounter to
CurrentPlaceHolderInt, equate PlaceHolderCounter to PlaceHolderCounter plus 1and if
DivisionResultInt is equal to 0 equate loop to 1.
Step 9:Equate BaseCounter to 0
Step 10:Equate Sum to 0
Step 11:Equate NewPlaceHolderCounter to PlaceHolderCounter minus 1
Step 12: WHILE BaseCounter is less than or equal to NewPlaceHolderCounter, equate
Base to PlaceHolderValues at the BaseCounter location, equate PowerFinder to Base
raised to the power of Indice, equate Sum to Sum pluse PowerFinder, equate
BaseCounter to BaseCounter plus 1and if Sum is equal to UserInput print "Input is an
Armstrong Number" else print "Input is not an Armstrong Number".
Step 13: End the program.
METHOD/ ALGORITHM
1. Start
2. Declare variables:
a. UserInput: To store the input number.
b. PlaceHolderCounter: To count the digits of the number.
c. DivisionResultInt: To store the integer part after division by 10.
d. loop: To control the extraction of digits.
e. CurrentPlaceHolderInt: To store each digit.
f. BaseCounter, Sum, Base, PowerFinder: For calculating the sum of powered digits.
g. Indice: Set to 3 (since we are dealing with a 3-digit number).
h. NewPlaceHolderCounter: To track the last index of digits.
3. Input the number:
a. Display the prompt: "Armstrong number: "
b. Read the UserInput number.
4. Extract digits:
a. Set DivisionResultDouble to UserInput.
b. Initialize PlaceHolderCounter = 0 and loop = 0.
c. While loop == 0:
i. Divide DivisionResultDouble by 10.
ii. Set DivisionResultInt to the integer part of DivisionResultDouble.
iii. Calculate CurrentPlaceHolderDouble as the fractional part of
DivisionResultDouble.
iv. Multiply CurrentPlaceHolderDouble by 10 to extract the current digit and
store it in CurrentPlaceHolderInt.
v. Store CurrentPlaceHolderInt in
PlaceHolderValues[PlaceHolderCounter].
vi. Increment PlaceHolderCounter by 1.
vii. If DivisionResultInt == 0, set loop = 1 to stop the extraction.
5. Calculate the sum of powered digits:
a. Initialize BaseCounter = 0, Sum = 0, and NewPlaceHolderCounter =
PlaceHolderCounter - 1.
b. While BaseCounter <= NewPlaceHolderCounter:
i. Get the digit from PlaceHolderValues[BaseCounter] and store it in Base.
ii. Raise Base to the power of Indice (3) and store the result in PowerFinder.
iii. Add PowerFinder to Sum.
iv. Increment BaseCounter by 1.
6. Compare the sum with the original number:
a. If Sum == UserInput, print "Input is an Armstrong Number".
b. Else, print "Input is not an Armstrong Number".
7. End
PROGRAM CODE
CONCLUSION
By following a methodical procedure, the computer successfully ascertains whether a given
number is an Armstrong number. The input number's digits are extracted, the total of the cubes
of those digits is calculated, and the sum is compared to the original number. It verifies if the
number is an Armstrong number if the sum equals the input number; if not, it does not.
The program can be made to handle numbers with any number of digits by dynamically varying
the power according to the number of digits, even though it is made for three-digit numbers
because the power of three is hardcoded. The program is an excellent illustration of number-
based reasoning in programming since it illustrates fundamental ideas of digit manipulation,
loops, and arithmetic operations.
Question 3: Create a program that prints the Fibonacci series.
Aim:
Creating the Fibonacci series up to a user-specified number of terms is the program's goal. The
user can specify the length of the Fibonacci sequence to be printed by entering an integer into the
software. It deals with a range of cases, including:
Printing the first term
Printing the first two terms
Printing more than two terms in the Fibonacci series
Validating user input for positive integers
Providing an error message for invalid or negative input
Task Description
Declare UserInput, FibonacciCounter
Declare number_1 as 0, number_2 as 1, number_3. Declare variables to store the length
of the Fibonacci sequence (UserInput), a counter to keep track of how many terms have
been printed (FibonacciCounter), and the first two Fibonacci numbers (number_1 and
number_2). number_3 will be used to calculate the next Fibonacci number.
Print "Input Required Length of Fibonacci series:" Display a message asking the user to
input the desired length of the Fibonacci sequence.
Read UserInput. Accept the user input and store it in the UserInput variable.
If UserInput is less than 1, print "Invalid Input. Please enter a positive integer." Exit
If the input is less than 1 (invalid input), display an error message and terminate the
program. A valid input must be a positive integer.
Print "Fibonacci series:"
Print the header message indicating that the Fibonacci sequence will follow.
If UserInput is equal to 1, Print value number_1
If the user asks for only the first term (UserInput equals 1), print the first Fibonacci
number (number_1, which is 0).
Else If UserInput is equal to 2, Print number_1, number_2
If the user asks for the first two terms (UserInput equals 2), print the first two Fibonacci
numbers (number_1, which is 0, and number_2, which is 1).
Else, Print number_1, number_2
Set FibonacciCounter to 2
If the user asks for more than two terms, first print the first two Fibonacci numbers.
Initialize the FibonacciCounter to 2 because we have already printed two terms.
While FibonacciCounter is less than UserInput, Set number_3 to the sum of number_1
and number_2, Calculate the next Fibonacci number by adding the previous two
numbers, (number_1 and number_2) and store the result in number_3. Print number_3,
Print the newly calculated Fibonacci number (number_3). Set number_1 to number_2.
Update number_1 to the value of number_2. This shifts the previous number to the new
"first" number. Set number_2 to number_3. Update number_2 to the value of number_3.
This shifts the newly calculated Fibonacci number to the new "second" number.
Increment FibonacciCounter by 1. Increase the FibonacciCounter by 1 to reflect that one
more term has been printed. End While. End of the loop that continues until the
Fibonacci sequence has reached the length specified by the user.
Print a new line. Once the Fibonacci sequence is printed, add a new line to make the
output neat and readable.
End. End of the program.
METHOD/ ALGORITHM
Start
Declare UserInput, FibonacciCounter
Declare number_1 as 0, number_2 as 1, number_3
Print "Input Required Length of Fibonacci series: "
Read UserInput
If UserInput is less than 1
o Print "Invalid Input. Please enter a positive integer."
o Exit
Print "Fibonacci series:"
If UserInput is equal to 1
o Print number_1
Else If UserInput is equal to 2
o Print number_1, number_2
Else
o Print number_1, number_2
Set FibonacciCounter to 2
While FibonacciCounter is less than UserInput
o Set number_3 to the sum of number_1 and number_2
o Print number_3
o Set number_1 to number_2
o Set number_2 to number_3
o Increment FibonacciCounter by 1
End While
Print a new line
End
PROGRAM CODE
CONCLUSION
Up to a user-specified number of words, this software can properly construct and show the
Fibonacci series. In order to ensure that the input is a valid positive integer, it first asks the user
to enter the desired length of the series. The application manages many situations, such as when
the user wants more than two terms, the first two terms, or just the first term. Until the desired
length is attained, it iteratively computes the Fibonacci sequence, updating and printing the
subsequent term in the series.
The application guarantees effective operation and user-friendly interaction by employing input
validation and generating the Fibonacci numbers using a straightforward loop. The program is a
reliable method for creating Fibonacci sequences since it can handle varying series lengths and
clearly indicate incorrect input.
Question 4: Write a program to convert a decimal number to a binary
number
Aim:
This program's objective is to translate a user-inputted decimal number's whole number portion
into its binary equivalent. After separating the input's integer and fractional components, the
program will process the integer portion to determine its binary representation before showing
the user the binary value.
Task Description
Start.
Input: Ask the user to input a decimal number.
Extract Whole and Fractional Parts:
Convert the decimal number to an integer and store it in UserInputInt (this will give the
whole number part).
Subtract the whole number part from the original decimal number to get the fractional
part (UserInputDouble).
Initialize Arrays and Variables:
Create an array WholeNumberBinValue[] to store the binary digits of the whole number
part.
Create a variable WholeNumberBinValueCounter to count the number of binary digits.
Initialize NewUserInputInt to the whole number part UserInputInt.
Convert Whole Number to Binary:
While NewUserInputInt is not 0:
o Find the remainder when dividing NewUserInputInt by 2. This gives the binary
digit (either 0 or 1).
o Store the binary digit in
WholeNumberBinValue[WholeNumberBinValueCounter].
o Update NewUserInputInt by dividing it by 2 (integer division).
o Increment WholeNumberBinValueCounter.
Reverse the Binary Digits:
Create a new array ReverseWholeNumberBinValue[] of size
WholeNumberBinValueCounter.
Copy the binary digits from WholeNumberBinValue[] into
ReverseWholeNumberBinValue[] in reverse order.
Print the Binary Output:
Print the binary digits stored in ReverseWholeNumberBinValue[] from the first to the
last digit.
End.
METHOD/ ALGORITHM
START
Declare UserInput, UserInputDouble as double
Declare UserInputInt as integer
Declare WholeNumberBinValue as array of integers
Declare ReverseWholeNumberBinValue as array of integers
Declare BinNumber, NewUserInputInt, WholeNumberBinValueCounter, Reverse,
Forward as integer
PRINT "Input Decimal Number: "
READ UserInput
UserInputInt = Integer part of UserInput
UserInputDouble = Fractional part of UserInput
WholeNumberBinValueCounter = 0
NewUserInputInt = UserInputInt
WHILE NewUserInputInt != 0
BinNumber = NewUserInputInt % 2
WholeNumberBinValue[WholeNumberBinValueCounter] = BinNumber
NewUserInputInt = NewUserInputInt / 2
WholeNumberBinValueCounter = WholeNumberBinValueCounter + 1
END WHILE
// Reverse the binary digits
Reverse = WholeNumberBinValueCounter - 1
Forward = 0
WHILE Reverse >= 0
ReverseWholeNumberBinValue[Forward] = WholeNumberBinValue[Reverse]
Forward = Forward + 1
Reverse = Reverse - 1
END WHILE
// Display the binary equivalent
PRINT "Binary Output Number: "
FOR i = 0 TO WholeNumberBinValueCounter - 1
PRINT ReverseWholeNumberBinValue[i]
END FOR
END
PROGRAM CODE
CONCLUSION
To sum up, this software effectively translates a decimal input's whole number portion into its
binary equivalent. To show the correct binary representation, the program harvests binary digits
and stores them in reverse order using a division-by-2 approach. This program illustrates the
fundamentals of binary conversion, which can be expanded to incorporate the fractional portion
of the input, even if it only processes the integer portion. In computer science, the software
provides a strong basis for comprehending number systems and the conversion process.
Handling negative values, translating the fractional portion, and enhancing memory management
are possible additional improvements.