Classic Programs in C, Java and Python

Learn six placement-programming methods through one clean implementation each. The focus is logic, edge cases, complexity and porting, not memorised code.

Prashant Jain

KnowledgeGate AI educator

Updated 14 Jul 20266 min read

Placement drives reuse a small family of programming tasks because each reveals whether you can turn a method into a correct loop. Interviewers watch how you handle input, invariants and edge cases, not whether you memorised a particular language's syntax.

This guide covers six classics. Each program has one full implementation, while the porting note shows what stays the same in C, Java and Python.

Fibonacci sequence in C

Start with 0 and 1. Print the current term, then replace the pair (a, b) with (b, a + b). At every iteration, the pair holds two consecutive Fibonacci terms.

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    long long a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        printf("%lld%s", a, i + 1 == n ? "\n" : " ");
        long long next = a + b;
        a = b;
        b = next;
    }
    return 0;
}

For n = 7, the output is 0 1 1 2 3 5 8. Check the updates: (0,1) becomes (1,1), then (1,2), then (2,3), so each printed value is the previous pair's first term.

Two edge cases matter. For n = 0, the loop prints no terms. For n = 1, it prints only 0; code that prints 0 1 before looping mishandles this case. Time is O(n) and auxiliary space is O(1). In Java or Python, the pair update is identical, though Python integers grow rather than overflowing at a fixed width.

Prime check in Java

A number below 2 is not prime. For larger numbers, it is enough to test possible divisors up to the square root because any larger factor must be paired with a smaller one.

public class PrimeCheck {
    static boolean isPrime(int n) {
        if (n < 2) return false;
        if (n == 2) return true;
        if (n % 2 == 0) return false;

        for (int d = 3; d <= n / d; d += 2) {
            if (n % d == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPrime(29));
    }
}

The output is true. Testing only odd divisors avoids redundant even checks, and d <= n / d avoids the overflow risk of forming d * d with large int values.

The usual traps are 0 and 1, which are not prime, and 2, which is the only even prime. The loop takes O(sqrt n) trial divisions and O(1) space. C uses the same remainder test; Python uses % and can express the loop with range(3, limit + 1, 2).

Armstrong number in Python

For a non-negative decimal integer with d digits, raise each digit to power d and add the results. The number is an Armstrong number when that sum equals the original.

def is_armstrong(n):
    if n < 0:
        return False
    digits = str(n)
    power = len(digits)
    total = sum(int(ch) ** power for ch in digits)
    return total == n

print(is_armstrong(153))

The output is True because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. A second check in the opposite direction is 154: the same digit powers total 1 + 125 + 64 = 190, so it is not an Armstrong number.

Treat 0 correctly: it has one digit, and 0^1 = 0, so the function returns True. This definition rejects negative values before processing the sign. With ordinary digit operations treated as constant-time, the scan is O(d) in the number of decimal digits and stores O(d) characters. In C or Java, extract digits using % 10 and count the digits before summing powers.

GCD with Euclid's algorithm in C

Euclid's method uses the identity gcd(a, b) = gcd(b, a % b). Replacing the larger problem by its remainder preserves the common divisors and rapidly shrinks the second value.

#include <stdio.h>

unsigned int gcd(unsigned int a, unsigned int b) {
    while (b != 0) {
        unsigned int remainder = a % b;
        a = b;
        b = remainder;
    }
    return a;
}

int main(void) {
    printf("%u\n", gcd(252, 105));
    return 0;
}

The three-step trace is:

  1. 252 = 105 * 2 + 42, so replace (252, 105) with (105, 42).

  2. 105 = 42 * 2 + 21, so replace (105, 42) with (42, 21).

  3. 42 = 21 * 2 + 0, so stop. The GCD is 21.

Verify it independently: 252 / 21 = 12 and 105 / 21 = 5, so 21 divides both. Since 12 and 5 share no factor greater than 1, no larger common divisor exists.

Euclid's algorithm trace for 252 and 105 showing exactly 252 = 105 x 2 + 42, 105 = 42 x 2 + 21, and 42 = 21 x 2 + 0, with the final non-zero remainder labeled GCD = 21.

If one input is zero, the loop returns the other input, matching gcd(a, 0) = a. Both zero has no standard positive GCD, so production input validation should reject that pair rather than silently assign mathematical meaning to the returned sentinel. Euclid's algorithm takes O(log min(a, b)) iterations and O(1) space. Its loop ports directly to Java or Python.

Reverse a number in Java

Repeatedly take the last digit with % 10, append it to the result using reversed * 10 + digit, and remove it from the input with integer division by 10.

public class ReverseNumber {
    static long reverse(int n) {
        long value = Math.abs((long) n);
        long reversed = 0;

        while (value > 0) {
            reversed = reversed * 10 + value % 10;
            value /= 10;
        }
        return n < 0 ? -reversed : reversed;
    }

    public static void main(String[] args) {
        System.out.println(reverse(12030));
    }
}

The output is 3021. The original trailing zero becomes a leading zero in the reversed digit sequence, and integer representation does not retain leading zeros.

For input 0, the loop does not run and the function returns 0. For a negative such as -120, the sign is restored after reversing, producing -21. Processing d digits takes O(d) time and O(1) auxiliary space. C needs careful choice of a wide result type, while Python removes fixed-width overflow concerns.

Palindrome number in Python

A non-negative integer is a palindrome if it equals its digit reversal. Preserve the original, build the reverse numerically, then compare.

def is_palindrome(n):
    if n < 0:
        return False

    original = n
    reversed_number = 0
    while n > 0:
        reversed_number = reversed_number * 10 + n % 10
        n //= 10
    return original == reversed_number

print(is_palindrome(12321))

The output is True: the constructed reverse is 12321, equal to the saved original. This numeric method also demonstrates the reverse-number invariant without converting to text.

Input 0 returns True because the original and initial reversed value are both zero. Negative integers return False under the common programming-question convention that the minus sign is not mirrored. Time is O(d) and extra space is O(1). The same arithmetic loop works in C and Java with integer division.

How placement rounds use these programs

TCS and Infosys-style rounds may present these methods as direct coding tasks, dry runs, debugging questions or viva prompts. The exact platform and permitted languages vary by drive, so read that drive's instructions. The reusable preparation is to state the invariant, handle two boundary cases, and give time and space costs before typing.

The TCS NQT exam structure guide shows one context in which coding basics appear, while the broader Placements guide helps organise aptitude, coding and interviews.

The short version

Learn six methods, not eighteen memorised code blocks. Practise them through the Coding for Placements course, then use the Coding Skills category to extend the same habits to arrays, strings and DSA. During every dry run, write the state after each loop iteration and test zero before declaring the program finished.