Top 45 Basic Coding Interview Questions and Answers
In FY23, the Indian IT industry created around 290,000 new jobs, increasing the total workforce to more than 5.4 million. With the tech sector expected to contribute 10% to India’s GDP by 2025, there will be a strong demand for positions like data scientists, machine learning engineers, full-stack developers, and cybersecurity specialists. This growth showcases the widening role of technology across different industries and underscores the necessity for skilled professionals in emerging areas. In this basic coding interview questions and answer blog, we have enlisted fresher coding questions with answers to help you learn all about coding interviews and develop the right skills.
C++ Basic Programming Interview Questions and Answers
C++ is widely used for its efficiency and control over system resources, making it a staple in technical interviews. This section covers C++ basic coding interview questions and answers that assess your understanding of core concepts like loops, arrays, pointers, and memory management. Practising these will help you strengthen your C++ abilities and impress interviewers with your expertise in this powerful language.
Q1. Find the largest element in an array.
Sample Answer: Finding the largest element in an array is a fundamental programming task that helps assess your understanding of basic loops and conditionals. This problem requires you to iterate through the array and compare its elements, allowing you to practice array traversal and conditional logic in C++.
Here’s how you can find the largest element in an array:
#include <iostream>
using namespace std;
int main() {
int arr[] = {3, 5, 7, 2, 8};
int size = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
cout << "Largest element: " << max << endl;
return 0;
}
Q2. What is the method to reverse a string?
Sample Answer: Reversing a string involves swapping characters from the beginning with those at the end until you reach the middle. It is a common exercise that tests your understanding of string manipulation and the use of loops in C++.
Here’s how you can reverse a string:
#include <iostream>
using namespace std;
void reverseString(string& str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
swap(str[i], str[n - i - 1]);
}
}
int main() {
string str = "Hello, World!";
reverseString(str);
cout << "Reversed string: " << str << endl;
return 0;
}
Q3. How can you determine if a number is prime?
Sample Answer: Determining if a number is prime is a classic algorithmic problem that helps you practice conditional logic and loops. To check if a number is prime, look for factors other than 1 and itself.
Here’s how you can check if a number is prime:
#include <iostream>
#include <cmath> // Include cmath for sqrt function
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false; // Numbers less than 2 are not prime
for (int i = 2; i <= sqrt(n); i++) { // Check up to the square root of n
if (n % i == 0) return false; // If n is divisible by i, it's not prime
}
return true; // If no divisors were found, it's prime
}
int main() {
int num = 29;
cout << num << " is " << (isPrime(num) ? "prime" : "not prime") << endl;
return 0;
}
Q4. What is linear search in an array and how is it implemented?
Sample Answer: Linear search is a straightforward algorithm that allows you to locate a specific element within an array. This simple coding interview question demonstrates your ability to iterate through data structures and implement search algorithms, providing a foundation for more complex searching techniques.
Here’s how you can implement linear search in an array:
#include <iostream>
using namespace std;
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) return i;
}
return -1; // Not found
}
int main() {
int arr[] = {4, 2, 3, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int index = linearSearch(arr, size, target);
cout << "Element found at index: " << index << endl;
return 0;
}
Q5. How do you count the number of vowels in a string?
Sample Answer: Counting vowels in a string is a practical exercise that showcases your understanding of character manipulation and loops in C++. To count vowels, iterate through the string and check each character.
Here is how you can count the number of vowels in a string:
#include <iostream>
using namespace std;
int countVowels(const string& str) {
int count = 0;
for (char c : str) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
count++;
}
}
return count;
}
int main() {
string str = "Hello, World!";
cout << "Number of vowels: " << countVowels(str) << endl;
return 0;
}
Also Read: SQL Coding Interview Questions
Q6. What is a bubble sort algorithm and why is it important?
Sample Answer: Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Implementing a sorting algorithm is essential for understanding how data can be organized. Bubble sort, while not the most efficient, is one of the simplest sorting algorithms to grasp.
Here’s how you can implement a bubble sort algorithm:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {5, 1, 4, 2, 8};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Q7. How do you merge two sorted arrays?
Sample Answer: Merging involves combining two sorted arrays into a single sorted array.
Here’s how you can merge two sorted arrays:
#include <iostream>
using namespace std;
void mergeArrays(int arr1[], int size1, int arr2[], int size2) {
int mergedSize = size1 + size2;
int* merged = new int[mergedSize];
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < size1) merged[k++] = arr1[i++];
while (j < size2) merged[k++] = arr2[j++];
cout << "Merged array: ";
for (int m = 0; m < mergedSize; m++) {
cout << merged[m] << " ";
}
cout << endl;
delete[] merged; // Free allocated memory
}
int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
mergeArrays(arr1, 3, arr2, 3);
return 0;
}
Q8. How to find the second-largest element in an array?
Sample Answer: To find the second largest element, traverse the array while maintaining the largest and second largest values.
Here’s how you can find the second-largest element in an array:
#include <iostream>
using namespace std;
int findSecondLargest(int arr[], int size) {
int largest = INT_MIN, secondLargest = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] < largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
int main() {
int arr[] = {3, 5, 7, 2, 8};
cout << "Second largest element: " << findSecondLargest(arr, 5) << endl;
return 0;
}
Q9. What is the method to remove duplicates from an array?
Sample Answer: Removing duplicates from an array is a practical problem that demonstrates your understanding of data storage and the use of data structures. You can remove duplicates by using a set to store unique elements. This task illustrates data structure usage and efficiency.
Here is how you can remove duplicates from an array:
#include <iostream>
#include <set>
using namespace std;
void removeDuplicates(int arr[], int size) {
set<int> uniqueElements;
for (int i = 0; i < size; i++) {
uniqueElements.insert(arr[i]);
}
cout << "Array after removing duplicates: ";
for (const int& elem : uniqueElements) {
cout << elem << " ";
}
cout << endl;
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
removeDuplicates(arr, 7);
return 0;
}
Q10. How do you calculate the Fibonacci series using recursion?
Sample Answer: The Fibonacci series can be computed by defining a recursive function that calls itself for the two preceding numbers. This basic programming question will help you understand how recursive functions work and the importance of base cases, while also reinforcing mathematical sequences in C++.
Here is how you can calculate the Fibonacci series using a recursion:
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms = 10;
cout << "Fibonacci series: ";
for (int i = 0; i < terms; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
Q11. How can you count the number of words in a string?
Sample Answer: Counting words involves traversing the string and counting spaces between words.
Here’s how you can count the number of words in a string:
#include <iostream>
#include <sstream>
using namespace std;
int countWords(const string& str) {
stringstream ss(str);
string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
int main() {
string str = "Hello, world! Welcome to C++ programming.";
cout << "Number of words: " << countWords(str) << endl;
return 0;
}
Q12. How do you create a simple calculator?
Sample Answer: Creating a simple calculator involves basic arithmetic operations and control flow in C++. This also includes the implementation of functions such as addition, subtraction, multiplication, and division, as well as managing user input and operator selection.
Here’s an example of how you can create a simple calculator:
#include <iostream>
using namespace std;
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
if (b == 0) {
cout << "Error! Division by zero." << endl;
return 0; // Handle division by zero
}
return a / b;
}
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
double result;
switch (operation) {
case '+': result = add(num1, num2); break;
case '-': result = subtract(num1, num2); break;
case '*': result = multiply(num1, num2); break;
case '/': result = divide(num1, num2); break;
default: cout << "Invalid operation!" << endl; return 1;
}
cout << "Result: " << result << endl;
return 0;
}
Q13. How do you find the greatest common divisor (GCD) of two numbers?
Sample Answer: Finding the greatest common divisor (GCD) of two numbers is a classic problem in number theory that can be solved using the Euclidean algorithm.
Here’s how to find the greatest common divisor (GCD) of two numbers:
#include <iostream>
using namespace std;
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1 = 56, num2 = 98;
cout << "GCD of " << num1 << " and " << num2 << " is " << gcd(num1, num2) << endl;
return 0;
}
Q14. How can you check if a string is a palindrome?
Sample Answer: To check if a string reads the same forwards and backward, we need to use loops to compare characters from both ends.
Here’s how we can check if a string is a palindrome:
#include <iostream>
using namespace std;
bool isPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string str = "racecar";
cout << str << (isPalindrome(str) ? " is a palindrome." : " is not a palindrome.") << endl;
return 0;
}
Q15. How do you print the factors of a number?
Sample Answer: To print factors, iterate through potential divisors and check for divisibility.
Here is how you can print the factors of a number:
#include <iostream>
using namespace std;
void printFactors(int n) {
cout << "Factors of " << n << ": ";
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
cout << i << " ";
}
}
cout << endl;
}
int main() {
int num = 28;
printFactors(num);
return 0;
}
Python Basic Coding Interview Questions with Answers for Practice
Python’s simplicity and versatility make it a popular choice for coding interviews. This Python basic coding interview questions and answers for practice section includes essential concepts like data types, control flow, functions, and data structures. Ideal for both beginners and seasoned programmers, these questions will enable you to demonstrate your Python skills and problem-solving strategies during interviews.
Q16. How can you check if a string contains only digits?
Sample Answer: You can check this by using the isdigit() method, which returns True if all characters in the string are digits.
Here’s how you can check if a string contains only digits:
def is_all_digits(s):
return s.isdigit()
test_str = "123456"
print(f"'{test_str}' contains only digits: {is_all_digits(test_str)}")
Q17. How do you count the occurrences of each character in a string?
Sample Answer: Counting can be done by iterating through the string and using a dictionary to track the count of each character. Counting character occurrences helps you practice working with dictionaries and string manipulation, reinforcing your understanding of collections.
Here’s how you can count the occurrences of each character in a string:
def count_characters(s):
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
return count
text = "hello"
print("Character occurrences:", count_characters(text))
Q18. How do you flatten a nested list?
Sample Answer: Flattening a nested list can be achieved by using a recursive function that checks if each item is a list and extends the flattened list accordingly.
Here’s how to flatten a nest list:
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
nested = [[1, 2], [3, [4, 5]]]
print("Flattened list:", flatten(nested))
Also Read: Python Coding Interview Questions
Q19. How to generate a random password?
Sample Answer: A random password generation can be done using the random module to select characters from a combination of letters, digits, and punctuation.
Here’s how you can generate a random password:
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
password = generate_password(12)
print("Generated password:", password)
Q20. What’s a simple way to remove all whitespace from a string?
Sample Answer: You can remove whitespace by using the split() method followed by join(), which effectively strips out spaces. Removing whitespace is a common task that helps you practice string manipulation methods. This basic programming question aims to enhance your understanding of string handling in Python.
Here’s how you can simply remove all whitespace from a string:
def remove_whitespace(s):
return ''.join(s.split())
text = " hello world "
print("String without whitespace:", remove_whitespace(text))
Q21. How will you find the longest word in a sentence?
Sample Answer: This can be done by splitting the sentence into words and using the max() function with a key to find the longest one.
Here’s how you can find the longest word in a sentence:
def longest_word(sentence):
words = sentence.split()
return max(words, key=len)
sentence = "The quick brown fox jumps over the lazy dog"
print("Longest word:", longest_word(sentence))
Q22. How will you build a simple calculator?
Sample Answer: We can create a calculator by taking user input for the operation and the numbers, and then performing the corresponding arithmetic operation.
Here’s how to build a simple calculator:
def calculator():
operation = input("Enter operation (+, -, *, /): ")
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b if b != 0 else "Cannot divide by zero"
else:
return "Invalid operation"
print("Calculator result:", calculator())
Q23. How do you identify duplicates in a list?
Sample Answer: Identifying duplicates in a list helps us understand the use of collections and iteration. To do this, we can use a set to track seen items and another set to collect duplicates as we iterate through the list.
Here’s a sample of how to identify duplicates in a list:
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
arr = [1, 2, 3, 2, 4, 1]
print("Duplicates in the list:", find_duplicates(arr))
Q24. How will you validate if a string is a valid email?
Sample Answer: Validating email formats is a common task in web applications. We can check for valid email formats using regular expressions with the re-module, which allows us to define a pattern for valid emails.
Here’s how to check if a string is a valid email:
import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(pattern, email) is not None
email = "test@example.com"
print(f"Is '{email}' a valid email? {is_valid_email(email)}")
Q25. What’s the best way to calculate the factorial of a number?
Sample Answer: Calculating factorials is a classic mathematical exercise that helps us understand recursion or iterative solutions in programming. We can calculate a factorial using a recursive function that multiplies the number by the factorial of the number minus one. This is the most common coding interview question designed to enhance your understanding of functions.
Here’s the best way to calculate the factorial of a number.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
num = 5
print(f"Factorial of {num} is {factorial(num)}")
Q26. How will you check if a number is a perfect square?
Sample Answer: Determining if a number is a perfect square is helpful in mathematical logic and conditionals. We can determine if a number is a perfect square by checking if its square root is an integer.
Here’s how you can check if a number is a perfect square:
import math
def is_perfect_square(n):
return n >= 0 and (math.isqrt(n) ** 2 == n)
num = 16
print(f"{num} is a perfect square: {is_perfect_square(num)}")
Q27. Count the number of even and odd numbers in a list.
Sample Answer: This can be done by iterating through the list and using a conditional to check each number’s parity.
Here’s how you can count the number of even and odd numbers in a list:
def count_even_odd(numbers):
even_count = sum(1 for num in numbers if num % 2 == 0)
odd_count = len(numbers) - even_count
return even_count, odd_count
arr = [1, 2, 3, 4, 5, 6]
even, odd = count_even_odd(arr)
print(f"Even numbers: {even}, Odd numbers: {odd}")
Q28. Generate a list of prime numbers up to n.
Sample Answer: You can achieve this by checking each number up to the limit to see if it has any divisors other than 1 and itself.
Here’s how to generate a list of prime numbers up to n.
def generate_primes(n):
primes = []
for num in range(2, n + 1):
if all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
primes.append(num)
return primes
limit = 20
print(f"Prime numbers up to {limit}:", generate_primes(limit))
Q29. How do you find the intersection of two lists?
Sample Answer: Finding the intersection of two lists helps practice set operations and list handling. You can find the intersection by converting both lists to sets and using the intersection operator to identify common elements.
Here’s how to find the intersection of two lists:
def intersect_lists(list1, list2):
return list(set(list1) & set(list2))
list_a = [1, 2, 3, 4]
list_b = [3, 4, 5, 6]
print("Intersection of the lists:", intersect_lists(list_a, list_b))
Q30. Create a function to check if a number is an Armstrong number.
Sample Answer: Checking for Armstrong numbers introduces you to number manipulation and conditionals. It can be done by calculating the sum of its digits raised to the power of the number of digits and comparing it to the original number.
Here’s how to check if a number is an Armstrong number or not:
def is_armstrong_number(num):
order = len(str(num))
sum_of_powers = sum(int(digit) ** order for digit in str(num))
return sum_of_powers == num
number = 153
print(f"{number} is an Armstrong number: {is_armstrong_number(number)}")
Java Basic Coding Interview Questions with Answers
Java continues to be a preferred choice for many developers and is essential for technical interviews. This section contains basic Java programming interview questions that highlight core concepts like object-oriented programming, exception handling, and collections. By solving these questions, you can improve your Java understanding, preparing you to tackle coding challenges with confidence.
Q31. How would you check if a string is a palindrome?
Sample Answer: To check if a string is a palindrome, you can compare characters from the beginning and the end of the string, moving toward the center. If all corresponding characters are the same, the string is a palindrome.
Here’s how to check if a string is a palindrome or not:
public class PalindromeChecker {
public static boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String text = "racecar";
System.out.println(text + " is palindrome: " + isPalindrome(text));
}
}
Q32. How would you find the second-largest number in an array?
Sample Answer: You can iterate through the array while maintaining two variables: one for the largest number and another for the second largest. Update these variables as you find larger numbers.
Here’s how to find the second-largest number in an array:
public class SecondLargestFinder {
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int number : arr) {
if (number > largest) {
secondLargest = largest;
largest = number;
} else if (number > secondLargest && number < largest) {
secondLargest = number;
}
}
return secondLargest;
}
public static void main(String[] args) {
int[] numbers = {3, 5, 7, 2, 8};
System.out.println("Second largest number: " + findSecondLargest(numbers));
}
}
Q33. How would you determine if two strings are anagrams?
Sample Answer: You can check if two strings are anagrams by sorting the characters in both strings and comparing the sorted versions. If they are the same, the strings are anagrams.
Here’s how to check if two strings are anagrams:
import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
char[] charArray1 = str1.toLowerCase().toCharArray();
char[] charArray2 = str2.toLowerCase().toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
System.out.println(str1 + " and " + str2 + " are anagrams: " + areAnagrams(str1, str2));
}
}
Q34. How can you find the greatest common divisor (GCD) of two numbers?
Sample Answer: You can use the Euclidean algorithm, which involves repeatedly applying the modulo operation until one of the numbers becomes zero. The other number at that point is the GCD.
Here’s how you can find the greatest common divisor (GCD) of two numbers:
public class GCDCalculator {
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
int a = 56;
int b = 98;
System.out.println("GCD of " + a + " and " + b + " is " + gcd(a, b));
}
}
Also Read: Java Coding Interview Questions
Q35. How would you count the number of words in a string?
Sample Answer: You can count words by splitting the string using whitespace as a delimiter and then checking the length of the resulting array. This basic coding question for the interview reinforces your understanding of text processing.
Here’s how to count the number of words in a string:
public class WordCounter {
public static int countWords(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
String[] words = s.trim().split("\\s+");
return words.length;
}
public static void main(String[] args) {
String text = "Hello world, this is Java!";
System.out.println("Number of words: " + countWords(text));
}
}
Q36. How would you remove all spaces from a string?
Sample Answer: You can remove spaces by using a regular expression to replace all whitespace characters with an empty string.
Here’s how to remove all spaces from a string:
public class SpaceRemover {
public static String removeSpaces(String s) {
return s.replaceAll("\\s+", "");
}
public static void main(String[] args) {
String original = "This is a test string.";
System.out.println("String without spaces: " + removeSpaces(original));
}
}
Q37. How can you check if a string contains only alphabetic characters?
Sample Answer: You can use a regular expression to match the string against a pattern that allows only alphabetic characters.
Here’s how to check if a string contains only alphabetic characters:
public class AlphabetChecker {
public static boolean isAlphabetic(String s) {
return s.matches("[a-zA-Z]+");
}
public static void main(String[] args) {
String text = "HelloWorld";
System.out.println(text + " contains only alphabetic characters: " + isAlphabetic(text));
}
}
Q38. How would you find the longest word in a sentence?
Sample Answer: You can split the sentence into words and iterate through them, keeping track of the longest one you encounter.
Here’s how to find the longest word in a sentence:
public class LongestWordFinder {
public static String findLongestWord(String s) {
String[] words = s.split("\\s+");
String longestWord = "";
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}
return longestWord;
}
public static void main(String[] args) {
String sentence = "I love programming in Java";
System.out.println("Longest word: " + findLongestWord(sentence));
}
}
Q39. How can you convert a string to uppercase?
Sample Answer: Converting a string to uppercase is simple but useful for practicing string manipulation and method usage in Java. You can convert a string to uppercase by using the built-in toUpperCase() method.
public class UppercaseConverter {
public static String toUpperCase(String s) {
return s.toUpperCase();
}
public static void main(String[] args) {
String original = "hello world";
System.out.println("Uppercase: " + toUpperCase(original));
}
}
Q40. How would you count the occurrences of a specific character in a string?
Sample Answer: You can iterate through the string, checking each character and maintaining a count of how many times the specified character appears. Counting occurrences of a specific character in a string helps you practice loops and character manipulation. This basic coding question for an interview enhances your analytical skills with string data.
Here’s how you can count the occurrences of a specific character in a string:
public class CharacterOccurrenceCounter {
public static int countCharacter(String s, char c) {
int count = 0;
for (char ch : s.toCharArray()) {
if (ch == c) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String text = "character";
char characterToCount = 'c';
System.out.println("Occurrences of '" + characterToCount + "': " + countCharacter(text, characterToCount));
}
}
Q41. How would you implement a simple calculator?
Sample Answer: You can create a simple calculator that takes user input for two numbers and an operator, then performs the calculation based on the operator provided.
Here’s how to implement a simple calculator:
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator!");
return;
}
System.out.println("Result: " + result);
}
}
Q42. How would you check if a number is even or odd?
Sample Answer: You can determine if a number is even or odd by checking if it is divisible by 2. If the remainder is zero, the number is even; otherwise, it is odd.
Here is how you can check if a number is even or odd:
public class EvenOddChecker {
public static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
int num = 10;
System.out.println(num + " is even: " + isEven(num));
}
}
Q43. How would you calculate the sum of the digits of a number?
Sample Answer: Calculating the sum of the digits of a number is simple yet effective and reinforces understanding of loops and arithmetic operations. You can repeatedly extract the last digit of the number using the modulo operation and add it to a sum, then remove the last digit by performing an integer division by 10.
Here’s how to calculate the sum of the digits of a number:
public class DigitSumCalculator {
public static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
int num = 12345;
System.out.println("Sum of digits: " + sumOfDigits(num));
}
}
Q44. How would you implement a basic bank account class?
Sample Answer: You can create a class that encapsulates account details, allowing methods for deposit, withdrawal, and checking the balance.
Here’s how to implement a basic bank account class:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount("12345678");
account.deposit(500);
account.withdraw(200);
System.out.println("Balance: " + account.getBalance());
}
}
Q45. How would you implement a basic temperature converter?
Sample Answer: You can create methods to convert temperatures between Celsius and Fahrenheit, using the respective formulas for conversion.
Here’s how you can implement a basic temperature converter:
import java.util.Scanner;
public class TemperatureConverter {
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9/5) + 32;
}
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
System.out.println("Temperature in Fahrenheit: " + celsiusToFahrenheit(celsius));
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = scanner.nextDouble();
System.out.println("Temperature in Celsius: " + fahrenheitToCelsius(fahrenheit));
}
}
Pro Tip: Want to learn more and explore Java-related interview topics? Check out our comprehensive guide on Deloitte Java developer interview questions to enhance your preparation!
Conclusion
Mastering basic coding interview questions and answers is a key step toward securing a programming job role. From system resource management in C++ to Python’s versatile data structures and Java’s object-oriented principles, these questions aim to refine your problem-solving skills and technical understanding. Preparing for an interview through this blog will also equip you for coding challenges in any technical interview. With a solid grasp of these fundamentals, you’re well on your way to securing your desired programming role and advancing your career. To expand your career horizon, explore our blog on Amazon software developer interview questions. It is packed to equip you with insights and strategies to succeed in landing your ideal role at Amazon!
Answer: In coding interviews, you can expect questions on data structures, algorithms, system design, dynamic programming, object-oriented programming, and problem-solving. These topics are asked in coding interviews to check your ability to write efficient and scalable code.
Here are some examples of common coding interview questions:
Q1. How do you reverse a linked list?
Q2. Solve a knapsack problem using dynamic programming.
Q3. What is the time complexity of merge sort?
Q4. Write a function to perform quick sorting.
Q5. Implement a binary search algorithm.
Q6. How do you find the longest substring without repeating characters?
Answer: The difficulty level for coding interviews depends on your preparation and the position you have applied for. Coding interviews can seem easy if you know the programming techniques and tools. To learn everything about taking the coding test, enroll in Internshala’s short-term training like how to ace the coding interview course that can help you prepare for the interview effectively. This course will help you test and improve your knowledge through quizzes and hands-on practice with coding questions.
Answer: Here are some tips that you can follow to ace a coding interview:
1. Learn Important Concepts: You should focus on data structures, algorithms, and system design. Additionally, you should understand their implementation and use cases.
2. Practice Regularly: Solve problems on online coding platforms to improve problem-solving speed and efficiency.
3. Appear for Mock Interviews: Participate in as many mock interviews as you can. This will help you practice various questions and improve your programming skills.
4. Understand Job Requirements: Research the company and understand the job requirements. This will help you answer accordingly during the interview.
5. Consider Preparatory Course: Whether you appear for Java, Python, C++, or JavaScript programming tests, consider taking a short-term preparatory course in that particular programming language. This will allow for targeted preparation for your coding interview.