AGH Computer Science C Programming Laboratory 4
AGH Computer Science C Programming Laboratory 4
2024
1. [3points] Write a C program that will calculate the number of digits of the number given by the
user (scanf). Use a do-while loop. To check the result, use the logarithm and the ternary operator
(? : ) to count the number of digits in a given integer.
Test data:
Enter any number: 123456789
Total digits: 9
Total digits (log10): 9
A palindrome is a word, number, phrase, or other sequence of characters which reads the same
backward as forward, such as madam, racecar.
There are also numeric palindromes: 121, 12321, ...
The algorithm:
a) Use the scanf function to input an integer (n).
b) Make a copy of n.
c) Find the reverse of n and assign it to rev.
Example: Reverse of 1234 is 4321.
The rev calculation should be performed in the while loop.
What will be the loop termination condition?
The body of the while loop consists of two lines.
- The first line is the calculation of rev.
- The second line is necessary for the loop to end.
To calculate the rev values use: *, +, %, rev, n, 10.
d) Check if rev is equal to copy of n. If so, the number is a palindrome, if not, it is not.
Test data:
Enter any number to check palindrome: 1234
1234 is not palindrome.
1
3. [5points] In mathematics, the Fibonacci numbers (Fn), form a sequence, called the Fibonacci
sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
Test data:
4. [6 points] Write a C program that prints all prime numbers in the range (a,b). The program uses
two loops and continue and break statements. Count how many primes are in a given range. Use
variable flagprime to break the inner loop when we know the number can't be prime. In the inner
loop, the sqrt function will come in handy.
Program structure:
int main(void){
//declarations and printf
for(………………………………………){
char flagprime = ……………
//Special cases 0, 1, 2 and divisible by 2. Use logical operators.
if (………………………………………)
//continue or break
//Divisibility by odd numbers 3, 5, …
//What is the loop termination condition?
for(……………………………………)
if(……………………………){
flagprime = ……………………………
//continue or break
}
if(flagprime){
printf(………………………………………);
……………………………………………………
}
}
printf("\nNumber of primes in (%d, %d): %d\n", ………………………………);
return 0;
}
Test data:
2
5. [2 points] Modify the previous program to count how many primes there are in every
hundred from 0 to 1000.
Test data:
Next time:
Laboratory 05 – Loops and arrays.
To prepare for the next class, read the lecture or book chapter on loops and arrays. Check
how sample programs from the lecture or book work. Check if you can modify them in any
way you want. Write some example programs that use loops and arrays.