Tcs Coding
Tcs Coding
This series is a mixture of 2 series fail the odd terms in this series form a
Fibonacci series and all the even terms are the prime numbers in ascending
order
The value N in a positive integer that should be read from mm. The Nth term
that is calculated by the program should be written to STDOUT Otherthan the
value of Nth term , no other characters / string or message should be written to
STDOUT.
For example, when N:14, the 14th term in the series is 17 So only the value 17
should be printed to STDOUT
Solution –
#include
void fibo(int);
void prime(int);
main()
int n,e;
scanf("%d",&n);
e=n/2;
if(n%2==0)
prime(e);
else
fibo(e+1);
}
void prime(int n)
int i,j,no,flag=0,count=0;
for(i=1;i<=100;i++)
flag=0;
for(j=2;j<=i/2;j++)
if(i%j==0)
flag=0;
else
flag=1;
if(flag==1)
count++;
if(count==n)
printf("%d\n",i);
break;
}
}
void fibo(int n)
int n0=0,n1=1,n2,i;
for(i=3;i<=n;i++)
n2=n0+n1;
n0=n1;
n1=n2;
printf("%d",n2);
--------------------------------------------------------------------------------------------------------
Coding Question-2
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-
place comparison-based algorithm in which the list is divided into two parts,
the sorted part at the left end and the unsorted part at the right end. Initially,
the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to
the right.
This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items.’
For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and
find that 10 is the lowest value.
Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.
Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.
Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus
leo.
The same process is applied to the rest of the items in the array.
In Python
In Java
Bubble Sort
Sorting Algorithms are concepts that every competitive programmer must know.
Sorting algorithms can be used for collections of numbers, strings, characters, or a
structure of any of these types.
Bubble sort is based on the idea of repeatedly comparing pairs of adjacent elements
and then swapping their positions if they exist in the wrong order.
Assume that A[] is an unsorted array of n elements. This array needs to be sorted in
ascending order. The pseudo code is as follows:
C/C++
Java
Python
def bubbleSort(arr):
n = len(arr)
bubbleSort(arr)
Coding Question-4
LCS Problem Statement: Given two sequences, find the length of longest subsequence
present in both of them. A subsequence is a sequence that appears in the same relative
order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”,
‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n
different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program
that outputs the differences between two files), and has applications in bioinformatics.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
C/C++
int m = strlen(X);
int n = strlen(Y);
Java
char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;
Python
if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
Coding Question-4
SubString Problem in C
Given a string as an input. We need to write a program that will print all non-empty
substrings of that given string.
#include<bits/stdc++.h>
using namespace std;
Java
Coding Question-5
Pythrogorous Triplets
A Pythagorean triplet is a set of three integers a, b and c such that a 2 + b2 = c2. Given a
limit, generate all Pythagorean Triples with values smaller than given limit.
Input : limit = 20
Output : 3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
A Simple Solution is to generate these triplets smaller than given limit using three
nested loop. For every triplet, check if Pythagorean condition is true, if true, then print
the triplet. Time complexity of this solution is O(limit 3) where ‘limit’ is given limit.
An Efficient Solution can print all triplets in O(k) time where k is number of triplets
printed. The idea is to use square sum relation of Pythagorean triplet, i.e., addition of
squares of a and b is equal to square of c, we can write these number in terms of m
and n such that,
a = m 2 - n2
b = 2 * m * n
c = m2 + n2
because,
a2 = m4 + n4 – 2 * m2 * n2
b2 = 4 * m 2 * n 2
c2 = m4 + n4 + 2* m2 * n2
We can see that a2 + b2 = c2, so instead of iterating for a, b and c we can iterate for m
and n and can generate these triplets.
if (c > limit)
break;
// Driver Code
int main()
{
int limit = 20;
pythagoreanTriplets(limit);
return 0;
}
Java
// Java program to generate pythagorean
// triplets smaller than a given limit
import java.io.*;
import java.util.*;
class GFG {
if (c > limit)
break;
System.out.println(a + " " + b + " " + c);
}
m++;
}
}
// Driver Code
public static void main(String args[])
{
int limit = 20;
pythagoreanTriplets(limit);
}
}
Python
# Python3 program to generate pythagorean
# triplets smaller than a given limit
# if c is greater than
# limit then break it
if c > limits :
break
print(a, b, c)
m = m + 1
# Driver Code
if __name__ == '__main__' :
limit = 20
pythagoreanTriplets(limit)
Coding Question-6
Armstrong Number
Given a number x, determine whether the given number is Armstrong number or not. A
positive integer of n digits is called an Armstrong number of order n (order is number
of digits) if.
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
C/C++
// C++ program to determine whether the number is
// Armstrong number or not
#include<bits/stdc++.h>
using namespace std;
Java
// Driver Program
public static void main(String[] args)
{
Armstrong ob = new Armstrong();
int x = 153;
System.out.println(ob.isArmstrong(x));
x = 1253;
System.out.println(ob.isArmstrong(x));
}
}
Python
# If condition satisfies
return (sum1 == x)
# Driver Program
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))
Coding Question-7
The square root of a Prime number by checking first if it is a prime number?
Also, you can study other Command Line Programming Questions here on
our TCS Dashboard.
lease also write the code in C/++/Java/Python in the comments section below
Please comment your own version of code in the comment section below –
[code language=”cpp”]
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<math.h>
bool isPrime(int n)
{
if(n<2)
return false;
int i;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
return false;
}
return true;
}
int main(int argc, char *argv[])
{
if(argc==1)
{
printf("No arguments");
return 0;
}
else
{
int n;
n=atoi(argv[1]);
float sq=0;
if(isPrime(n))
{
sq=sqrt(n);
printf("%.2f",sq);
}
else
printf("%.2f",sq);
return 0;
}
}
[/code]
Coding Question-8
Examples:
Input : 16
Output : 20
Input : 10
Output : 12
Input: 33
Output: 41
Algorithm:
For Example:
If the given decimal number is 16.
Step 1: Remainder when 16 is divided by 8 is 0. Therefore, arr[0] = 0.
Step 2: Divide 16 by 8. New number is 16/8 = 2.
Step 3: Remainder when 2 is divided by 8 is 2. Therefore, arr[1] = 2.
Step 4: Divide 2 by 8. New number is 2/8 = 0.
Step 5: Since number becomes = 0. Stop repeating steps and print the array in reverse
order. Therefore the equivalent octal number is 20.
C/C++
// C++ program to convert a decimal
// number to octal number
#include <iostream>
using namespace std;
decToOctal(n);
return 0;
}
Java
// Java program to convert a decimal
// number to octal number
import java.io.*;
class GFG
{
// Function to convert decimal to octal
static void decToOctal(int n)
{
// array to store octal number
int[] octalNum = new int[100];
// driver program
public static void main (String[] args)
{
int n = 33;
decToOctal(n);
}
}
#include
int main(int argc,char *argv[])
{
int n,s=0,b=1,r;
n=atoi(argv[1]);
int c=n;
while(c>0)
{
r=c%8;
s=s+r*b;
c=c/8;
b=b*10;
}
printf("%d",s);
getch();
}
Coding Question-9
return 0;
}
i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
Output
while(binnum > 0)
{
rem = binnum % 10;
decnum = decnum + rem*i;
//System.out.println(rem);
i = i*2;
binnum = binnum/10;
}
i=1;
quot = decnum;
while(quot > 0)
{
octnum[i++] = quot % 8;
quot = quot / 8;
}
}
}
Sample Output:
#include
void main(int argc,char *argv[])
{
long int n,r,c,b=1,s=0;
n=atoi(argv[1]);
c=n;
while(c!=0)
{
r=c%10;
s=s+r*b;
c=c/10;
b=b*2;
}
printf("%lo",s);
getch();
}
Coding Question-10
int main()
{
int year;
if(year%4 == 0)
{
if( year%100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
return 0;
}
Java
import java.util.Scanner;
public class Check_Leap_Year
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter any year:");
int year = s.nextInt();
boolean flag = false;
if(year % 400 == 0)
{
flag = true;
}
else if (year % 100 == 0)
{
flag = false;
}
else if(year % 4 == 0)
{
flag = true;
}
else
{
flag = false;
}
if(flag)
{
System.out.println("Year "+year+" is a Leap Year");
}
else
{
System.out.println("Year "+year+" is not a Leap Year");
}
}
}
Command Line
#include
void main(int argc,char *argv[])
{
int n;
n=atoi(argv[1]);
if(n%4==0)
{
if(n%100==0)
{
if(n%400==0)
printf("Leap Year");
else printf("Not Leap Year");
}
else printf("Leap Year");
}
else
printf("Not Leap Year");
getch(); }
Coding Question-11
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Java
public class Prime {
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Command Line
Please comment your own version of code in the comment section below –
#include
int n, i, flag = 0;
n = atol(argv[1]);
if(n%i==0)
flag=1;
break;
if (flag==0)
else
return 0;
Coding Question-12
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
printf("Reversed Number = %d", reversedNumber);
return 0;
}
Java
public class ReverseNumber {
while(num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
Please comment your own version of code in the comment section below –
#include
#include
int main(int argc, char *argv[])
{
if(argc==1)
{
printf("No Arguments");
return 0;
}
else
{
int n,reverseNumber,temp,rem;
n=atoi(argv[1]);
temp=n;
reverseNumber=0;
while(temp)
{
rem=temp%10;
reverseNumber=reverseNumber*10+rem;
temp=temp/10;
}
printf("%d",reverseNumber);
return 0;
}
}
Coding Question-13
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
gets(s);
end = count - 1;
r[begin] = '\0';
printf("%s\n", r);
return 0;
}
Coding Question-14
HFC is also called greatest common divisor (gcd). HCF of two numbers is a largest
positive numbers which can divide both numbers without any remainder. For example
HCF of two numbers 4 and 8 is 2 since 2 is the largest positive number which can
dived 4 as well as 8 without a remainder.
It is clear that any number is not divisible by greater than number itself.
☆In case of more than one numbers, a possible maximum number which can divide
all of the numbers must be minimum of all of that numbers.
Program :
#include<stdio.h>
int gcd(int , int , int);
int main()
{
int i , j , k , g;
scanf("%d %d %d", &i , &j , &k);
g = gcd(i , j , k);
printf("%d",g);
return 0;
}
}
Java
import java.util.*;
Coding Question-15
Second Largest Number in an Array using Command Line
Programming
#include <stdio.h>
#include <limits.h>
int main()
{
int arr[50], i, Size;
int first, second;
Coding Question-16
[code language=”cpp”]
#include <stdio.h>
#include <stdlib.h>
else {
Coding Question-17
int n1,n2;
n1=atoi(argv[1]);
n2=atoi(argv[2]);
n3=n1+n2;
printf(" The sum of the two numbers are %d",n3);
decimal=n3;
while(n3>0)
{
rem=n3%2;
binary=binary+rem*base;
base=base*10;
n3=n3/2;
}
Coding Question-18
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int status;
char sample[100];
read_string(sample);
status = check_string(sample);
while ( status == 1 )
read_string(sample);
status = check_string(sample);
convert_int(sample);
return 0;
strcpy(sample, “”);
gets(sample);
fflush(stdin);
*/
int i, flag = 0;
flag = 1;
}
else {
flag = 0;
break;
if ( flag == 0 ) {
return 1;
else {
return 0;
*/
*/
int i, sum = 0, j = 0;
j++;
Coding Question-19
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char c;
fp = fopen("input.txt", "r");
if (fp == NULL) {
exit(1);
c = fgetc(fp);
while ( c != EOF ) {
/* If the character read is a newline or tab or space */
if ( c == '\n')
line_count++;
c = fgetc(fp);
continue;
*/
char_count++;
c = fgetc(fp);
*/
return 0;
Coding Question-20
Here we can take the string and reverse it. Then compare
the original string with the reversed string. If they are the
same then it is a palindrome.
Coding Question-21
*/
#include <stdio.h>
#include <string.h>
int main()
char clear[25];
char token[25];
fflush(stdin);
while ( nitems != 1 ){
}
Solution 2 ( using integer manipulation )
#include <stdio.h>
#include <string.h>
int main() {
scanf(“%d”, &number);
temp = number;
while ( temp ) {
rem = temp%10;
temp = temp/10;
i = 0;
snumber[i++] = token[j];
snumber[i] = ‘\0’;
snumber);
Coding Question-22
*/
#include<stdio.h>
void main() {
scanf(“%u”,&num);
binary(num);
printf(“0”);
else
printf(“1”);
printf(“\n”);
}
Method 2 ( Consecutive Divide by 2 – The traditional
way in which we convert a number to Binary )
Coding Question-23
#include<stdio.h>
#include<stdlib.h>
int main(int c,char *v[])
{
int n1=atoi(v[1]),n2=8,res=0;
while(n2!=0)
{
res=res+n1;
n2--;
}
printf("%d",res);
}
Coding Question-24
n1=atoi(argv[1]);
while(n2!=0)
{
res=res+n1;
n2--;
}
printf("%d",res);
}
Coding Question-25
C/C++
#include <stdio.h>
int main()
{
int x = 10, y = 5;
return 0;
}
Java
class PrepInsta {
Python
x = 10
y=5
# x now becomes 15
x=x+y
# y becomes 10
y=x–y
# x becomes 5
x=x–y
print(“After Swapping: x =”,x ,” y =”, y);
Coding Question-26
Pushing all 0’s
Given an array of random numbers, Push all the zero’s of a given array to the end of
the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be
changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be
same. Expected time complexity is O(n) and extra space is O(1).
Example:
C/C++
// A C++ program to move all zeroes at the end of array
#include <iostream>
using namespace std;
Coding Question-27
Coding Question-28
#include
#define TRUE 1
#define FALSE 0
int main(){
char sentence[1000];
char pattern[25];
int result;
gets(sentence);
printf(“\n\n”);
gets(pattern);
char *p;
*/
p = strstr(sentence, pattern);
if ( p == NULL ){
return FALSE;
else {
printf(“\nThe search string was found in the
sentence\n\n”);
return TRUE;
}
}
Coding Question-29
Examples:
C/C++
// Simple C++ program to find k'th smallest element
#include<iostream>
#include<algorithm>
using namespace std;
Java
// Java code for kth smallest element
// in an array
import java.util.Arrays;
import java.util.Collections;
class GFG
{
// Function to return k'th smallest
// element in a given array
public static int kthSmallest(Integer [] arr,
int k)
{
// Sort the given array
Arrays.sort(arr);
// driver program
public static void main(String[] args)
{
Integer arr[] = new Integer[]{12, 3, 5, 7, 19};
int k = 2;
System.out.print( "K'th smallest element is "+
kthSmallest(arr, k) );
}
}
Coding Question-30
GCD Array of Numbers
The GCD of three or more numbers equals the product of the prime factors common
to all the numbers, but it can also be calculated by repeatedly taking the GCDs of
pairs of numbers.
result = arr[0]
For i = 1 to n-1
result = GCD(result, arr[i])
C/C++
// Driven code
int main()
{
int arr[] = { 2, 4, 6, 8, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findGCD(arr, n) << endl;
return 0;
}
Java
return result;
}
Coding Question-31
Coding Question-32
#include <stdio.h>
#include <string.h>
int main() {
char sentence[100];
char *p;
gets(sentence);
while ( p != NULL ){
printf(“%s\n”, p);
p = strtok(NULL, “\t”);
return 0;
}
Coding Question-33
*/
#include <stdio.h>
#include <string.h>
int main(){
char input[100];
char output[100];
char temp[100];
char *p;
gets(input);
strcpy(temp, input);
strcpy(output,””);
p = strtok(temp, ” “);
while ( p != NULL ){
strcat(output,p);
strcat(output,” “);
printf(“%s\n”, p);
p = strtok(NULL, ” “);
printf(“%s\n”, input);
printf(“%s\n”, output);
printf(“%d\n”, strlen(output));
return 0;
Coding Question-34
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
int length, i;
spaces = 0, others = 0;
length = strlen(buffer);
alpha++;
if ( islower( buffer[i] ))
lower++;
else
upper++;
else if (isdigit(buffer[i] ))
digit++;
}
else if (isspace(buffer[i])){
spaces++;
}
else if (ispunct(buffer[i])){
punct++;
}
else
others++;
Coding Question-35
Coding Question-36
Write a Program to remove vowels from a string?
Coding Question-37
Write a Program for Matrix Multiplication(Universal Program)