C Loops Exercises & Practice Problems with Solutions

C loop coding challenges and iteration checkpoints.
C loop coding challenges and iteration checkpoints.

Problem Statement

Write a C program that reads a positive integer N from standard input, computes the sum of its digits, reverses the integer arithmetically in memory, and classifies whether the reversed integer is prime, composite, or neither.

Real-World Systems Context

In network packet decoding, telemetry serialization, and numeric checksum validation, extracting decimal digits and checking mathematical properties are foundational operations. This challenge builds fluency with loop invariants, integer extraction, and optimal primality testing without relying on heavy string conversion libraries.

Detailed Task Specifications:

  1. Standard Input: Read a single positive integer N (e.g. 1234).
  2. Digit Sum: Calculate and print Digit Sum: <sum>.
  3. Number Reversal: Arithmetically reverse the integer digits and print Reversed: <reversed>.
  4. Primality Status: Check if the reversed integer is prime. Print Status: Prime, Status: Composite, or Status: Neither (for values <= 1).

Complexity & Editorial

The Engineering Behind Digit Extraction and Primality

Manipulating integers directly in C requires thinking about numeric hardware representation rather than string conversions. Converting an integer to a char buffer just to reverse it causes unnecessary stack allocations and cache misses.

  1. Arithmetic Digit Extraction:
    In C, the modulo operator (temp % 10) isolates the least significant decimal digit in a single instruction. Dividing (temp /= 10) immediately strips that digit away. Inside a while (temp > 0) loop, this extracts all digits in logarithmic time O(log10(N)).

  2. Arithmetically Constructing the Reversed Integer:
    To construct the reversed integer without allocating memory, multiply your running accumulator by 10 and add the extracted digit:
    reversed = (reversed * 10) + digit;
    Each loop iteration shifts existing digits one decimal place to the left.

  3. Optimized 6k ± 1 Primality Testing:
    A naive primality check tests all divisors up to N - 1 in O(N) time. Checking divisors up to sqrt(N) cuts work significantly, but we can do even better using the 6k ± 1 rule: all primes greater than 3 can be expressed as 6k + 1 or 6k - 1. By testing 2 and 3 first, we can step through potential divisors by 6 (i += 6), testing only i and i + 2. This reduces loop iterations by 66% compared to checking all odd numbers.

Starter Code

#include <stdio.h>
#include <stdbool.h>

// Function to check if a number is prime
bool is_prime(int n) {
    // TODO: Implement prime checking logic (O(sqrt(N)))
    return false;
}

int main(void) {
    int n;
    if (scanf("%d", &n) != 1) {
        return 1;
    }

    // TODO: 1. Calculate sum of digits
    // TODO: 2. Reverse the integer N
    // TODO: 3. Check if reversed integer is Prime

    // Expected print format:
    // printf("Digit Sum: %d\n", sum);
    // printf("Reversed: %d\n", reversed);
    // printf("Status: %s\n", is_prime(reversed) ? "Prime" : "Composite");

    return 0;
}

Frequently Asked Questions

Why does reversing 100 produce 1 instead of 001?

Integer variables in C represent numerical magnitudes in binary hardware registers, not string literals. Leading zeros have no mathematical significance, so reversing 100 mathematically produces 1.

How do for loops and while loops differ in C assembly code?

Modern optimizing compilers (GCC -O2) emit virtually identical assembly jumps and branch instructions for equivalent for and while loops.

Related exercises