[go: up one dir, main page]

0% found this document useful (0 votes)
5 views53 pages

Cognizant Coding Question

The document contains coding questions and solutions in various programming languages for tasks such as calculating the sum of natural numbers, checking for palindromes, computing factorials, counting frequencies in arrays, determining leap years, swapping numbers, finding min and max in arrays, summing arithmetic series, checking even or odd numbers, and rearranging arrays. Each question includes sample input and output along with code snippets in Java, C++, and Python. The document also briefly mentions sorting algorithms.

Uploaded by

soupayanwork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

Cognizant Coding Question

The document contains coding questions and solutions in various programming languages for tasks such as calculating the sum of natural numbers, checking for palindromes, computing factorials, counting frequencies in arrays, determining leap years, swapping numbers, finding min and max in arrays, summing arithmetic series, checking even or odd numbers, and rearranging arrays. Each question includes sample input and output along with code snippets in Java, C++, and Python. The document also briefly mentions sorting algorithms.

Uploaded by

soupayanwork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

COGNIZANT CODING QUESTION

COMPLETE PDF
Q.1 Given a number ‘N’, find out the sum of
the first N natural numbers.
Input: N=5
Output: 15
Explanation: 1+2+3+4+5=15
import java.util.Scanner;

public class SumNaturalNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int N = scanner.nextInt();
scanner.close();

int sum = N * (N + 1) / 2;

System.out.println("Sum of first " + N + " natural numbers


is: " + sum);
}
}
#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter a number: ";
cin >> N;

int sum = N * (N + 1) / 2; // Using formula

cout << "Sum of first " << N << " natural numbers is: " << sum
<< endl;
return 0;
}
N = int(input("Enter a number: "))

sum_natural = N * (N + 1) // 2 # Using formula

print(f"Sum of first {N} natural numbers is: {sum_natural}")


Q.2 Given an integer N, return true if it is a
palindrome else return false.
Input:N = 121
Output:Palindrome Number
import java.util.Scanner;
public class PalindromeNumber {
public static boolean isPalindrome(int N) {
int original = N, reversed = 0;
while (N > 0) {
int digit = N % 10;
reversed = reversed * 10 + digit;
N /= 10;
}

return original == reversed;


}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int N = scanner.nextInt();
scanner.close();

System.out.println("Is palindrome: " + isPalindrome(N));


}
}
#include <iostream>
using namespace std;
bool isPalindrome(int N) {
int original = N, reversed = 0;

while (N > 0) {
int digit = N % 10;
reversed = reversed * 10 + digit;
N /= 10;
}

return original == reversed;


}

int main() {
int N;
cout << "Enter a number: ";
cin >> N;

cout << "Is palindrome: " << (isPalindrome(N) ? "true" :


"false") << endl;
return 0;
}
def is_palindrome(N):
original, reversed_num = N, 0

while N > 0:
digit = N % 10
reversed_num = reversed_num * 10 + digit
N //= 10

return original == reversed_num

# Taking input from the user


N = int(input("Enter a number: "))
print("Is palindrome:", is_palindrome(N))
Q.3 Given a number X, print its factorial.
Input: X = 5
Output: 120
Explanation: 5! = 5*4*3*2*1
import java.util.Scanner;

public class Factorial {


public static long factorial(int X) {
long fact = 1;
for (int i = 2; i <= X; i++) {
fact *= i;
}
return fact;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int X = scanner.nextInt();
scanner.close();

System.out.println("Factorial of " + X + " is: " + factorial(X));


}
}
#include <iostream>
using namespace std;

long long factorial(int X) {


long long fact = 1;
for (int i = 2; i <= X; i++) {
fact *= i;
}
return fact;
}

int main() {
int X;
cout << "Enter a number: ";
cin >> X;

cout << "Factorial of " << X << " is: " << factorial(X) << endl;
return 0;
}
def factorial(X):
fact = 1
for i in range(2, X + 1):
fact *= i
return fact

X = int(input("Enter a number: "))


print("Factorial of", X, "is:", factorial(X))
Q.4 Count frequency of each element in the
array.
Input: arr[] = {10,5,10,15,10,5};
Output: 10 3
5 2
15 1
import java.util.HashMap;
import java.util.Map;

public class FrequencyCounter {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1, 4, 5, 1, 2, 3};

Map<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : arr) {


frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {


System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
#include <iostream>
#include <unordered_map>
using namespace std;

void countFrequency(int arr[], int size) {


unordered_map<int, int> freqMap;

for (int i = 0; i < size; i++) {


freqMap[arr[i]]++;
}

for (auto pair : freqMap) {


cout << pair.first << " -> " << pair.second << endl;
}
}

int main() {
int arr[] = {1, 2, 3, 2, 1, 4, 5, 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);

countFrequency(arr, size);
return 0;
}
from collections import Counter

arr = [1, 2, 3, 2, 1, 4, 5, 1, 2, 3]

frequency = Counter(arr)

for key, value in frequency.items():


print(f"{key} -> {value}")
Q.5 Check if given year is a leap year or not.
Input: 1996
Output: Yes
import java.util.Scanner;

public class LeapYearCheck {


public static boolean isLeapYear(int year) {
if (year % 400 == 0) return true;
if (year % 100 == 0) return false;
return year % 4 == 0;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
scanner.close();

if (isLeapYear(year))
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
#include <iostream>
using namespace std;

bool isLeapYear(int year) {


if (year % 400 == 0) return true;
if (year % 100 == 0) return false;
return year % 4 == 0;
}

int main() {
int year;
cout << "Enter a year: ";
cin >> year;

if (isLeapYear(year))
cout << year << " is a leap year." << endl;
else
cout << year << " is not a leap year." << endl;

return 0;
}
def is_leap_year(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 0

year = int(input("Enter a year: "))

if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
SORTING ALGORITHMS :-
• BUBBLE SORT
• INSERTION SORT
• SELECTION SORT
• QUICK SORT
• MERGE SORT
Q.6 Swap Two Numbers Without Using a Third
Variable.
Input: a = 5, b = 10
Output: a = 10, b = 5
import java.util.Scanner;

public class SwapNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number (a): ");
int a = scanner.nextInt();
System.out.print("Enter second number (b): ");
int b = scanner.nextInt();
scanner.close();

// Swapping without third variable


a = a + b;
b = a - b;
a = a - b;

System.out.println("After swapping: a = " + a + ", b = " + b);


}
}
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter first number (a): ";
cin >> a;
cout << "Enter second number (b): ";
cin >> b;

// Swapping without third variable


a = a + b;
b = a - b;
a = a - b;

cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))

# Swapping without third variable


a=a+b
b=a-b
a=a-b

print(f"After swapping: a = {a}, b = {b}")


Q.7 Find the largest and smallest elements in
an array.
Input : arr = { 2,3,6, 7, 8,9 }
Output : Largest Element : 9
Smallest Element : 2
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int min = arr[0], max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("Smallest element: " + min);
System.out.println("Largest element: " + max);
}
}
#include <iostream>
#include <climits>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int min = arr[0], max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
cout << "Smallest element: " << min << endl;
cout << "Largest element: " << max << endl;
def find_min_max(arr):
min_element = arr[0]
max_element = arr[0]

for num in arr[1:]:


if num < min_element:
min_element = num
if num > max_element:
max_element = num

return min_element, max_element

n = int(input("Enter the number of elements: "))


arr = list(map(int, input("Enter the elements: ").split()))

min_value, max_value = find_min_max(arr)

print(f"Smallest element: {min_value}")


print(f"Largest element: {max_value}")
Q.8 Given an A.P. Series, we need to find the
sum of the Series.
Input:
n=4
a=2
d=2
Output: 20
import java.util.Scanner;

public class APSum {


public static int sumOfAP(int a, int d, int n) {
return (n * (2 * a + (n - 1) * d)) / 2;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first term (a): ");
int a = scanner.nextInt();
System.out.print("Enter common difference (d): ");
int d = scanner.nextInt();
System.out.print("Enter number of terms (n): ");
int n = scanner.nextInt();
scanner.close();

int sum = sumOfAP(a, d, n);


System.out.println("Sum of the A.P. series: " + sum);
}
}
#include <iostream>
using namespace std;

int sumOfAP(int a, int d, int n) {


return (n * (2 * a + (n - 1) * d)) / 2;
}

int main() {
int a, d, n;
cout << "Enter first term (a): ";
cin >> a;
cout << "Enter common difference (d): ";
cin >> d;
cout << "Enter number of terms (n): ";
cin >> n;

int sum = sumOfAP(a, d, n);


cout << "Sum of the A.P. series: " << sum << endl;

return 0;
}
def sum_of_ap(a, d, n):
return (n * (2 * a + (n - 1) * d)) // 2

a = int(input("Enter first term (a): "))


d = int(input("Enter common difference (d): "))
n = int(input("Enter number of terms (n): "))

sum_ap = sum_of_ap(a, d, n)
print(f"Sum of the A.P. series: {sum_ap}")
Q.9 Write a Code to Check whether a given
number is even or odd.
Input: n=5
Output: odd
import java.util.Scanner;

public class EvenOddCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
scanner.close();

if (num % 2 == 0)
System.out.println(num + " is an Even number.");
else
System.out.println(num + " is an Odd number.");
}
}
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num % 2 == 0)
cout << num << " is an Even number." << endl;
else
cout << num << " is an Odd number." << endl;

return 0;
}
num = int(input("Enter a number: "))

if num % 2 == 0:
print(f"{num} is an Even number.")
else:
print(f"{num} is an Odd number.")
Q.10 Rearrange array in increasing-decreasing
order.
Input: 8 7 1 6 5 9
Output: 1 5 6 9 8 7
import java.util.Arrays;
public class Main {

public static void main(String args[]) {

int arr[] = {8,7,1,6,5,9};


int n = arr.length;
Arrays.sort(arr);
for (int i = 0; i < n / 2; i++) {
System.out.print(arr[i] + " ");
}
for (int i = n - 1; i >= n / 2; i--) {
System.out.print(arr[i] + " ");
}
}
}
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int arr[] = {8, 7, 1, 6, 5, 9};
int n = sizeof(arr) / sizeof(arr[0]);

sort(arr, arr + n);

for (int i = 0; i < n / 2; i++) {


cout << arr[i] << " ";
}
// Print the second half in decreasing order
for (int i = n - 1; i >= n / 2; i--) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
arr = [8, 7, 1, 6, 5, 9]

# Sort the array


arr.sort()
n = len(arr)

# Print the first half in increasing order


for i in range(n // 2):
print(arr[i], end=" ")
# Print the second half in decreasing order
for i in range(n - 1, n // 2 - 1, -1):
print(arr[i], end=" ")
print()

You might also like