If you’re preparing for the TCS NQT exam or any fresher-level coding interview, ignoring basic problems can cost you the job.
In this blog, we’ve compiled 15 must-practice coding questions that are frequently asked in TCS and other entry-level interviews. Many candidates fail not because the questions are hard—but because they skip the fundamentals.
Each problem is explained with clean and simple implementations in:
- C++
- Java
- Python
- JavaScript
We’ve focused on core logic-building questions that test your problem-solving skills, not just syntax.
Don’t know what is TCS NQT? click here to Learn

1. Write a program to check wheather a number is prime or not?
bool isPrime(int num) {
if (num <= 1)
return false;
if (num <= 3)
return true;
// Even numbers greater than 2 are not prime
if (num % 2 == 0)
return false;
// Check only odd numbers
for (int i = 5; i <= sqrt(num); i += 2) {
if (num % i == 0)
return false;
}
return true;
} public static boolean isPrime(int num) {
if (num <= 1)
return false;
if (num <= 3)
return true;
// Even numbers greater than 2 are not prime
if (num % 2 == 0)
return false;
// Check only odd numbers
for (int i = 5; i <= Math.sqrt(num); i += 2) {
if (num % i == 0)
return false;
}
return true;
}import math
def isPrime(num):
if num <= 1:
return False
if num <= 3:
return True
# Even numbers greater than 2 are not prime
if num % 2 == 0:
return False
# Check only odd numbers
i = 5
while i <= math.sqrt(num):
if num % i == 0:
return False
i += 2
return Truefunction isPrime( num ) {
if ( num <= 1 )
return false;
if ( num <= 3 )
return true;
//Even numbers greater than 2 are Not Prime
if ( num % 2 === 0 )
return false;
//check only odd numbers
for ( let i = 5; i<= Math.sqrt(num);i+=2 ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}2. Write a program to find Factorial of a Number
long long findFactorial(int num) {
// Edge cases
if (num < 0) {
cout << "Factorial not defined for Negative Numbers" << endl;
return -1;
}
// 0! and 1! = 1
if (num == 0 || num == 1) {
return 1;
}
long long result = 1;
// Iterate from num to 1
for (int i = num; i >= 1; i--) {
result *= i;
}
return result;
} public static long findFactorial(int num) {
// Edge cases
if (num < 0) {
System.out.println("Factorial not defined for Negative Numbers");
return -1;
}
// 0! and 1! = 1
if (num == 0 || num == 1) {
return 1;
}
long result = 1;
// Iterate from num to 1
for (int i = num; i >= 1; i--) {
result *= i;
}
return result;
}def findFactorial(num):
# Edge cases
if num < 0:
return "Factorial not defined for Negative Numbers"
# 0! and 1! = 1
if num == 0 or num == 1:
return 1
result = 1
# Iterate from num to 1
for i in range(num, 0, -1):
result *= i
return resultfunction findFactorial( num ) {
//Edge cases
if ( num <0 )
return "Factorial not defined for Negetive Numbers";
// we know 0! & 1! is 1
if ( num === 0 || num ===1 ) {
return 1;
}
let result = 1;
//Iterate loop to 1
for ( let i = num ; i >=1 ; i-- ) {
result*=i;
}
return result;
}3. Write a program to check a Number is Even or Odd
void isEvenOrOdd(int num) {
if (num % 2 == 0)
cout << "Even";
else
cout << "Odd";
} public static void isEvenOrOdd(int num) {
if (num % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}def is_even_or_odd(num):
if num % 2 == 0:
print("Even")
else:
print("Odd")function isEvenOrOdd( num ) {
console.log( num % 2 === 0 ? "Even" : "Odd" );
}4. Write a program to calculate the sum of all digits of a given integer.
int sumOfDigits(int num) {
num = abs(num); // handle negative numbers
int sum = 0;
while (num != 0) {
int rem = num % 10;
sum += rem;
num = num / 10;
}
return sum;
}public static int sumOfDigits(int num) {
num = Math.abs(num); // handle negative numbers
int sum = 0;
while (num != 0) {
int rem = num % 10;
sum += rem;
num = num / 10;
}
return sum;
}def sum_of_digits(num):
num = abs(num) # handle negative numbers
total = 0
while num != 0:
rem = num % 10
total += rem
num = num // 10 # integer division
return totalfunction sumOfAllDigits( num ) {
num = Math.abs(num); // handle negetive numbers
let sum = 0;
while ( num !== 0 ) {
let rem = num % 10;
sum+=rem;
num = Math.floor(num/10);
}
return sum;
}5. Write a program to reverse the digits of a given integer.
int reverseNumber(int num) {
bool isNegative = num < 0;
num = abs(num);
int rev = 0;
while (num != 0) {
int rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
return isNegative ? -rev : rev;
}public static int reverseNumber(int num) {
boolean isNegative = num < 0;
num = Math.abs(num);
int rev = 0;
while (num != 0) {
int rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
return isNegative ? -rev : rev;
}def reverse_number(num):
is_negative = num < 0
num = abs(num)
rev = 0
while num != 0:
rem = num % 10
rev = rev * 10 + rem
num = num // 10
return -rev if is_negative else revfunction reverseNumber( num ) {
isNegetive = num < 0; // check negetive or not
num = Math.abs(num);
let revNum = 0;
while( num !== 0 ) {
let rem = num % 10;
revNum = revNum*10 + rem;
num = Math.floor( num / 10 );
}
console.log( isNegetive ? -revNum : revNum );
}6. Write a program to check whether a given integer is a Palindrome or not.
A palindrome number is an integer that remains the same when its digits are reversed, reading the same forwards and backwards. Examples include 121, 1331, 3223, and single-digit numbers.
bool isPalindrome(int num) {
int original = num;
num = abs(num);
int rev = 0;
while (num != 0) {
int rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
return original == rev;
}
public static boolean isPalindrome(int num) {
int original = num;
num = Math.abs(num);
int rev = 0;
while (num != 0) {
int rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
return original == rev;
}def reverse_number(num):
is_negative = num < 0
num = abs(num)
rev = 0
while num != 0:
rem = num % 10
rev = rev * 10 + rem
num = num // 10
return -rev if is_negative else revfunction isPalindrome(num) {
let original = num;
num = Math.abs(num);
let rev = 0;
while (num !== 0) {
let rem = num % 10;
rev = rev * 10 + rem;
num = Math.floor(num / 10);
}
return original === rev;
}7. Write a program to check whether a given number is an Armstrong Number or not.
An Armstrong number (or narcissistic number) is a positive integer that equals the sum of its own digits, each raised to the power of the total number of digits. For example, 153 is a three digit armstrong number because,
1^3 + 5^3 + 3^3 = 153
bool isArmstrong(int num) {
int original = num;
num = abs(num);
int digits = to_string(num).length();
int sum = 0;
int temp = num;
while (temp != 0) {
int rem = temp % 10;
sum += pow(rem, digits);
temp = temp / 10;
}
return sum == original;
}public static boolean isArmstrong(int num) {
int original = num;
num = Math.abs(num);
int digits = String.valueOf(num).length();
int sum = 0;
int temp = num;
while (temp != 0) {
int rem = temp % 10;
sum += Math.pow(rem, digits);
temp = temp / 10;
}
return sum == original;
}def is_armstrong(num):
original = num
num = abs(num)
digits = len(str(num))
total = 0
temp = num
while temp != 0:
rem = temp % 10
total += rem ** digits
temp //= 10
return total == originalfunction isArmstrong(num) {
let original = num;
num = Math.abs(num);
let digits = num.toString().length;
let sum = 0;
let temp = num;
while (temp !== 0) {
let rem = temp % 10;
sum += Math.pow(rem, digits);
temp = Math.floor(temp / 10);
}
return sum === original;
}8. Write a program to find the largest among three given numbers.
int largestOfThree(int a, int b, int c) {
if (a >= b && a >= c)
return a;
else if (b >= a && b >= c)
return b;
else
return c;
}public static int largestOfThree(int a, int b, int c) {
if (a >= b && a >= c)
return a;
else if (b >= a && b >= c)
return b;
else
return c;
}def largest_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return cfunction largestOfThree(a, b, c) {
if (a >= b && a >= c) {
return a;
} else if (b >= a && b >= c) {
return b;
} else {
return c;
}
}9. Write a program to calculate the GCD (Greatest Common Divisor) and LCM (Least Common Multiple) of two given integers.
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return abs(a);
}
int lcm(int a, int b) {
return abs(a * b) / gcd(a, b);
}public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return Math.abs(a);
}
public static int lcm(int a, int b) {
return Math.abs(a * b) / gcd(a, b);
}def gcd(a, b):
while b != 0:
a, b = b, a % b
return abs(a)
def lcm(a, b):
return abs(a * b) // gcd(a, b)function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return Math.abs(a);
}
function lcm(a, b) {
return Math.abs(a * b) / gcd(a, b);
}10. Write a program to check whether a given year is a Leap Year or not.
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}11. Move All Zeros to the End (Chocolate Packets Problem)
Problem Statement –
A chocolate factory is packing chocolates into the packets. The chocolate packets here represent an array of N number of integer values. The task is to find the empty packets(0) of chocolate and push it to the end of the conveyor belt(array).
Example 1 :
N=8 and arr = [4,5,0,1,9,0,5,0].
There are 3 empty packets in the given set. These 3 empty packets represented as O should be pushed towards the end of the array
Input :
8 – Value of N
[4,5,0,1,9,0,5,0] – Element of arr[O] to arr[N-1],While input each element is separated by newline
Output:
4 5 1 9 5 0 0 0
Example 2:
Input:
6 — Value of N.
[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by newline
Output:
6 1 8 2 0 0
void moveZerosToEnd(int arr[], int n) {
int k = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[k++] = arr[i];
}
}
while (k < n) {
arr[k++] = 0;
}
}public static int[] moveZerosToEnd(int[] arr) {
int k = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[k++] = arr[i];
}
}
while (k < arr.length) {
arr[k++] = 0;
}
return arr;
}def move_zeros_to_end(arr):
k = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[k] = arr[i]
k += 1
while k < len(arr):
arr[k] = 0
k += 1
return arrfunction moveZerosToEnd(arr) {
let k = 0;
// Move non-zero elements forward
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) {
arr[k++] = arr[i];
}
}
// Fill remaining with 0
while (k < arr.length) {
arr[k++] = 0;
}
return arr;
}12. Toggle Bits After MSB (Decimal to Binary)
Problem Statement –
Joseph is learning digital logic subject which will be for his next semester. He usually tries to solve unit assignment problems before the lecture. Today he got one tricky question. The problem statement is “A positive integer has been given as an input. Convert decimal value to binary representation. Toggle all bits of it after the most significant bit including the most significant bit. Print the positive integer value after toggling all bits”.
Constrains-
1<=N<=100
Example 1:
Input :
10 -> Integer
Output :
5 -> result- Integer
Explanation:
Binary representation of 10 is 1010. After toggling the bits(1010), will get 0101 which represents “5”. Hence output will print “5”.
int toggleBits(int num) {
int bits = 0, temp = num;
while (temp > 0) {
bits++;
temp /= 2;
}
int mask = (1 << bits) - 1;
return num ^ mask;
} public static int toggleBits(int num) {
int bits = Integer.toBinaryString(num).length();
int mask = (1 << bits) - 1;
return num ^ mask;
}
def toggle_bits(num):
bits = len(bin(num)) - 2 # remove '0b'
mask = (1 << bits) - 1
return num ^ maskfunction toggleBits(num) {
let bits = num.toString(2).length;
let mask = (1 << bits) - 1;
return num ^ mask;
}13. Write a program to count the number of vowels and consonants in a given string.
void countVC(string str) {
int vowels = 0, consonants = 0;
for (char ch : str) {
if (isalpha(ch)) {
ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants;
}public static int[] countVC(String str) {
int vowels = 0, consonants = 0;
str = str.toLowerCase();
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1)
vowels++;
else
consonants++;
}
}
return new int[]{vowels, consonants};
}def count_vowels_consonants(s):
vowels = 0
consonants = 0
for ch in s.lower():
if ch.isalpha():
if ch in "aeiou":
vowels += 1
else:
consonants += 1
return vowels, consonantsfunction countVowelsAndConsonants(str) {
let vowels = 0, consonants = 0;
let s = str.toLowerCase();
for (let ch of s) {
if (ch >= 'a' && ch <= 'z') {
if ("aeiou".includes(ch)) {
vowels++;
} else {
consonants++;
}
}
}
return { vowels, consonants };
}14. Write a program to check whether two given strings are Anagrams of each other.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all original letters exactly once. Example : Listen -> Silent
bool isAnagram(string str1, string str2) {
// Remove non-alphabet characters & convert to lowercase (optional step skipped for simplicity)
if (str1.length() != str2.length())
return false;
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
return str1 == str2;
} public static boolean isAnagram(String str1, String str2) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
if (str1.length() != str2.length())
return false;
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}def is_anagram(str1, str2):
s1 = ''.join(sorted(str1.lower()))
s2 = ''.join(sorted(str2.lower()))
return s1 == s2function isAnagram(str1, str2) {
//Convert string to lowercase and remove everything except letters (a–z)
let s1 = str1.toLowerCase().replace(/[^a-z]/g, '');
let s2 = str2.toLowerCase().replace(/[^a-z]/g, '');
if (s1.length !== s2.length) return false;
s1 = s1.split('').sort().join('');
s2 = s2.split('').sort().join('');
return s1 === s2;
}
15. Write a program to remove duplicate characters from a given string while maintaining the original order of characters.
string removeDuplicates(string str) {
unordered_set<char> seen;
string result = "";
for (char ch : str) {
if (seen.find(ch) == seen.end()) {
seen.insert(ch);
result += ch;
}
}
return result;
}public static String removeDuplicates(String str) {
Set<Character> seen = new HashSet<>();
StringBuilder result = new StringBuilder();
for (char ch : str.toCharArray()) {
if (!seen.contains(ch)) {
seen.add(ch);
result.append(ch);
}
}
return result.toString();
}def remove_duplicates(s):
seen = set()
result = ""
for ch in s:
if ch not in seen:
seen.add(ch)
result += ch
return resultfunction removeDuplicates(str) {
let seen = new Set();
let result = "";
for (let ch of str) {
if (!seen.has(ch)) {
seen.add(ch);
result += ch;
}
}
return result;
}Conclusion
Mastering coding interviews doesn’t require solving hundreds of complex problems—it starts with getting the basics right.
These 15 TCS NQT questions cover the most important foundational concepts that every fresher must know. If you can confidently solve these, you are already ahead of many candidates. You can practice more DSA problems here:
Don’t just read the solutions—try to solve each problem on your own first.
We will keep updating this list with more real interview questions, so stay connected with Tech Interview Hub and keep practicing consistently.


