Competitive Programming New

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 190

Q- 1

Task

This challenge requires you to print on a single line, and then print the already provided

input string . If you are not familiar with C, you may want to read about the printf()

command.

Example

The required output is:


Hello, World!
Life is beautiful
Function Descriptio
Complete the main() function below.
The main() function has the following input:
string s: a string
Prints
*two strings: * "Hello, World!" on one line and the input string on the next line.
Input Format
There is one line of text, .
Sample Input 0
Welcome to C programming.
Sample Output 0
Hello, World!
Welcome to C programming.
int main()
{

char s[100];
scanf("%[^\n]%*c", s);
printf("Hello, World!\n");
printf("%s", s);

return 0;
}
Q-2
This challenge will help you to learn how to take a character, a string and a sentence

as input in C.

To take a single character as input, you can use scanf("%c", &ch ); and printf("%c",

ch) writes a character specified by the argument char to stdout


char ch;
scanf("%c", &ch);
printf("%c", ch);

This piece of code prints the character .

You can take a string as input in C using scanf(“%s”, s). But, it accepts string only

until it finds the first space.


In order to take a line as input, you can use scanf("%[^\n]%*c", s); where is defined

as char s[MAX_LEN] where is the maximum size of . Here, [] is the scanset

character. ^\n stands for taking input until a newline isn't encountered. Then, with

this %*c, it reads the newline character and here, the used * indicates that this newline

character is discarded.

Note: The statement: scanf("%[^\n]%*c", s); will not work because the last statement

will read a newline character, \n, from the previous line. This can be handled in a

variety of ways. One way is to use scanf("\n"); before the last statement.
Task

You have to print the character, , in the first line. Then print in next line. In the last line

print the sentence, .

Input Format

First, take a character, as input.

Then take the string, as input.

Lastly, take the sentence as input.

Constraints

Strings for and will have fewer than 100 characters, including the newline.
Output Format

Print three lines of output. The first line prints the character, .

The second line prints the string, .

The third line prints the sentence, .

Sample Input 0
C
Language
Welcome To C!!

Sample Output 0
C
Language
Welcome To C!!
int main() {
char ch;
char s[20], sen[100];
scanf("%c", &ch);
scanf("%s", s);
scanf("\n");
scanf("%[^\n]%*c", sen);
printf("%c\n", ch);
printf("%s\n", s);
printf("%s\n", sen);
return 0;
}
Q-3
Objective

The fundamental data types in c are int, float and char. Today, we're discussing int

and float data types.

The printf() function prints the given statement to the console. The syntax

is printf("format string",argument_list);. In the function, if we are using an integer,

character, string or float as argument, then in the format string we have to

write %d (integer), %c (character), %s (string), %f (float) respectively.


The scanf() function reads the input data from the console. The syntax

is scanf("format string",argument_list);. For ex: The scanf("%d",&number) statement

reads integer number from the console and stores the given value in variable .

To input two integers separated by a space on a single line, the command

is scanf("%d %d", &n, &m), where and are the two integers.
Task

Your task is to take two numbers of int data type, two numbers of float data type as input and

output their sum:

 Declare variables: two of type int and two of type float.

 Read lines of input from stdin (according to the sequence given in the 'Input Format' section

below) and initialize your variables.

 Use the and operator to perform the following operations:

 Print the sum and difference of two int variable on a new line.

 Print the sum and difference of two float variable rounded to one decimal place on a new

line.
Input Format
The first line contains two integers.
The second line contains two floating point numbers.
Constraints
 integer variables
 float variables
Output Format
Print the sum and difference of both integers separated by a space on the
first line, and the sum and difference of both float (scaled to decimal place)
separated by a space on the second line.
Sample Input
10 4
4.0 2.0

Sample Output
14 6
6.0 2.0

Explanation

When we sum the integers and , we get the integer . When we subtract the second

number from the first number , we get as their difference.

When we sum the floating-point numbers and , we get . When we subtract the second

number from the first number , we get as their difference.


int main()
{
int n, m;
float a, b;
scanf("%d %d", &n, &m);
scanf("%f %f", &a, &b);
int sum_of_ints = n + m;
float sum_of_floats = a + b;
int diff_of_ints = n - m;
float diff_of_floats = a - b;
printf("%d %d\n", sum_of_ints, diff_of_ints);
printf("%.1f %.1f", sum_of_floats, diff_of_floats);

return 0;
}
Q-4
Objective
In this challenge, you will learn simple usage of functions in C. Functions are a
bunch of statements grouped together. A function is provided with zero or more
arguments, and it executes the statements on it. Based on the return type, it either
returns nothing (void) or something.

Task
Write a function int max_of_four(int a, int b, int c, int d) which reads four arguments
and returns the greatest of them.

Note
There is not built in max function in C. Code that will be reused is often put in a
separate function, e.g. int max(x, y) that returns the greater of the two values.
Input Format
Input will contain four integers - , one on each line.
Output Format
Print the greatest of the four integers.
Note: I/O will be automatically handled.
Sample Input
3
4
6
5
Sample Output
6
int max(int a, int b) {

return a > b ? a : b;
}
int max_of_four(int a, int b, int c, int d) {
return max(a, max(b, max(c, d)));
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);

return 0;
}
Q-5
Task
Complete the function void update(int *a,int *b). It receives two integer pointers,
int* a and int* b. Set the value of to their sum, and to their absolute difference. There
is no return value, and no return statement is needed.


Input Format
The input will contain two integers, and , separated by a newline.
Output Format
Modify the two values in place and the code stub main() will print their values.
Note: Input/ouput will be automatically handled. You only have to complete the
function described in the 'task' section.
Sample Input
4
5

Sample Output
9
1
void update(int *a,int *b) {
int temp = *a;
*a = *a + *b;
*b = temp - *b;
}
int main() {
int a, b;
int *pa = &a, *pb = &b;

scanf("%d %d", &a, &b);


update(pa, pb);
printf("%d\n%d", a, b);

return 0;
}
Q-6

Objective
In this challenge, you will learn the usage of the for loop, which is a programming
language statement which allows code to be executed until a terminal condition is met.
They can even repeat forever if the terminal condition is never met.
The syntax for the for loop is:
for ( <expression_1> ; <expression_2> ; <expression_3> )
 <statement>
 expression_1 is used for intializing variables which are generally used for
controlling the terminating flag for the loop.
 expression_2 is used to check for the terminating condition. If this evaluates to
false, then the loop is terminated.
 expression_3 is generally used to update the flags/variables.
The following loop initializes to 0, tests that is less than 10, and increments at
every iteration. It will execute 10 times.
Task
For each integer in the interval (given as input) :
 If , then print the English representation of it in lowercase. That is "one" for , "two"
for , and so on.
 Else if and it is an even number, then print "even".
 Else if and it is an odd number, then print "odd".

Input Format

The first line contains an integer, .


The seond line contains an integer, .
Output Format

Print the appropriate English representation,even, or odd, based on the conditions

described in the 'task' section.

Note:

Sample Input
8
11

Sample Output
eight
nine
even
odd
int main() {
int a, b,i;
char* represent[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine"};
scanf("%d\n%d", &a, &b);
for( i = a; i <= b; i++)
{
if(i > 9) {
if(i % 2 == 0)
printf("even\n");
else printf("odd\n");
}
else {
printf("%s\n", represent[i]);
}
}
return 0;
}
Q-7
 Program to replace all 0's with 1 in a given integer is discussed here. Given an integer as an input, all the
0's in the number has to be replaced with 1.
 For example, consider the following number

 Input: 102405
 Output: 112415
 Input: 56004
 Output: 56114

 Algorithm to replace all 0's with 1 in a given integer

• Input the integer from the user.


• Traverse the integer digit by digit.
• If a '0' is encountered, replace it by '1'.
• Print the integer.
int replace(int number)
{
// Base case for recursion termination
if (number == 0)
return 0;
// Extract the last digit and change it if needed
int digit = number % 10;
if (digit == 0)
digit = 1;
// Convert remaining digits and append the last digit
return replace(number/10) * 10 + digit;
}
int main()
{
int number;
printf("\nEnter the number : ");
scanf("%d", &number);
printf("\nNumber after replacement : %d", replace(number));
return 0;
}
Q-8
if and else are two of the most frequently used conditionals in C/C++, and they enable
you to execute zero or one conditional statement among many such dependent
conditional statements.

Task

Given a positive integer denoting , do the following:

 If , print the lowercase English word corresponding to the number

(e.g., one for , two for , etc.).

 If , print Greater than 9.


Input Format
The first line contains a single integer, .
Output Format
If , then print the lowercase English word corresponding to the number
(e.g., one for , two for , etc.); otherwise, print Greater than 9 instead.
Sample Input
5
Sample Output
five
Sample Input #01
8
Sample Output #01
eight
Sample Input #02
44

Sample Output #02


Greater than 9
int main() {

int n;
scanf("%d", &n);
if(n == 1) {
printf("one");
}
else if(n == 2) {
printf("two");
}
else if(n == 3) {
printf("three");
}
else if(n == 4) {
printf("four");
} else if(n == 5) {
printf("five");
} else if(n == 6) {
printf("six");
} else if(n == 7) {
printf("seven");
} else if(n == 8) {
printf("eight");
}
else if(n == 9) {
printf("nine");
} else {
printf("Greater than 9");
} return 0; }
Q-9
The modulo operator, %, returns the remainder of a division. For example, 4
% 3 = 1 and 12 % 10 = 2. The ordinary division operator, /, returns a truncated
integer value when performed on integers. For example, 5 / 3 = 1. To get the
last digit of a number in base 10, use as the modulo divisor.
Task
Given a five digit integer, print the sum of its digits.
Input Format
The input contains a single five digit number, .

Output Format
Print the sum of the digits of the five digit number.

Sample Input 0
10564

Sample Output 0
16
int main() {

int n;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
int sum = 0;
do {
sum += (n % 10);
n /= 10;
}
while(n != 0);
printf("%d", sum);
return 0;
}
Q-10
In this challenge, you will use logical bitwise operators. All data is stored in its
binary representation. The logical operators, and C language, use to represent true
and to represent false. The logical operators compare bits in two numbers and return
true or false, or , for each bit compared.
 Bitwise AND operator & The output of bitwise AND is 1 if the corresponding bits
of two operands is 1. If either bit of an operand is 0, the result of corresponding bit
is evaluated to 0. It is denoted by &.
 Bitwise OR operator | The output of bitwise OR is 1 if at least one corresponding
bit of two operands is 1. It is denoted by |.
 Bitwise XOR (exclusive OR) operator ^ The result of bitwise XOR operator is 1 if
the corresponding bits of two operands are opposite. It is denoted by .
For example, for integers 3 and 5,
3 = 00000011 (In Binary)
5 = 00000101 (In Binary)

AND operation OR operation XOR operation


00000011 00000011 00000011
& 00000101 | 00000101 ^ 00000101
________ ________ ________
00000001 = 1 00000111 = 7 00000110 = 6
You will be given an integer , and a threshold, i1nnik$. Print the
results of the and, or and exclusive or comparisons on separate
lines, in that order.
Example
The results of the comparisons are below:
a b and or xor
12 0 3 3
13 1 3 2
23 2 3 1
For the and comparison, the maximum is . For the or comparison, none of the
values is less than , so the maximum is . For the xor comparison, the
maximum value less than is . The function should print:
2
0
2
Function Description
Complete the calculate_the_maximum function in the editor below.
calculate_the_maximum has the following parameters:
• int n: the highest number to consider
• int k: the result of a comparison must be lower than this number to
be considered
Prints
Print the maximum values for the and, or and xor comparisons, each on a
separate line.
Input Format
The only line contains space-separated integers, and .
Sample Input 0
54
Sample Output 0
2
3
3
void calculate_the_maximum(int n, int k) {
//Write your code here.
int max_and = 0, max_or = 0, max_xor = 0;
int v_and = 0, v_or = 0, v_xor = 0;
int i,j;
for ( i=1; i<=n; i++) {
for ( j=i+1; j<=n; j++) {
v_and = i & j;
v_or = i | j;
v_xor = i ^ j;
if (v_and > max_and && v_and < k) max_and = v_and;
if (v_or > max_or && v_or < k) max_or = v_or;
if (v_xor > max_xor && v_xor < k) max_xor = v_xor;
}
}
printf("%d\n%d\n%d\n", max_and, max_or, max_xor);
}
int main() {
int n, k;

scanf("%d %d", &n, &k);


calculate_the_maximum(n, k);

return 0;
}
Q-11
In this challenge, create an array of size n dynamically, and read the values from
stdin. Iterate the array calculating the sum of all elements. Print the sum and free
the memory where the array is stored.

Input Format
The first line contains an integer, n.
The next line contains n space-separated integers.
Constraints
1 <= n <=1000
1 <= a[i] <=1000
Output Format
Print the sum of the integers in the array.
Sample Input 0
6
16 13 7 2 1 12
Sample Output 0
51
Sample Input 1
7
1 13 15 20 12 13 2
Sample Output 1
76
int main()
{ int n, *arr, i, sum = 0;
scanf("%d", &n);
arr = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
scanf("%d", arr + i);
}
for(i = 0; i < n; i++) {
sum += *(arr + i);
}
printf("%d\n", sum);

return 0;
}
Q-12
In this challenge, create an array of size n dynamically, and read the
values from stdin.
Reverse the given array.

Example: If array, arr=[1,2,3,4,5] , after reversing it, the array should


be, arr=[5,4,3,2,1].
Q-12
Input Format
The first line contains an integer, n, denoting the size of the array. The next
line contains n space-separated integers denoting the elements of the
array.
Constraints
1 <= n <=1000
1 <=arr[i] <= 1000
, where arr[i] is the ith element of the array.
Output Format
The output is handled by the code given in the editor, which would print the
array.
Sample Input 0
6
16 13 7 2 1 12
Sample Output 0
12 1 2 7 13 16
Q-13
The game of billiards involves two players knocking 3 balls around on a
green baize table. Well, there is more to it, but for our purposes this is
sufficient.
The game consists of several rounds and in each round both players obtain a
score, based on how well they played. Once all the rounds have been
played, the total score of each player is determined by adding up the scores
in all the rounds and the player with the higher total score is declared the
winner.
The Sports Club organises an annual billiards game where the top two
players play against each other. The Manager of Sports Club decided to add
his own twist to the game by changing the rules for determining the winner.
In his version, at the end of each round, the cumulative score for each
player is calculated, and the leader and her current lead are found. Once all
the rounds are over the player who had the maximum lead at the end of
any round in the game is declared the winner.
Q-13
Consider the following score sheet for a game with 5 rounds:
Round Player 1 Player 2

1 140 82
2 89 134
3 90 110
4 112 106
5 88 90
Q-13
The total scores of both players, the leader and the lead after each round
for this game is given below:

Round Player 1 Player 2 Leader Lead

1 140 82 Player 1 58

2 229 216 Player 1 13

3 319 326 Player 2 7

4 431 432 Player 2 1

5 519 522 Player 2 3

Note that the above table contains the cumulative scores.


Q-13

 The winner of this game is Player 1 as he had the


maximum lead (58 at the end of round 1) during the
game.
 Your task is to help the Manager find the winner and the
winning lead. You may assume that the scores will be
such that there will always be a single winner. That is,
there are no ties.
Q-13
Input
The first line of the input will contain a single integer N (N ≤ 10000)
indicating the number of rounds in the game. Lines 2,3,...,N+1
describe the scores of the two players in the N rounds. Line i+1
contains two integer Si and Ti, the scores of the Player 1 and 2
respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti
≤ 1000.

Output
Your output must consist of a single line containing two integers W
and L, where W is 1 or 2 and indicates the winner and L is the
maximum lead attained by the winner.
Q-13
Input:
5
140 82
89 134
90 110
112 106
88 90
Output:
1 58
Q-15
An English text needs to be encrypted using the following encryption
scheme. First, the spaces are removed from the text. Let L be the
length of this text. Then, characters are written into a grid, whose
rows and columns have the following constraints:

Example : if man was meant to stay on the ground god would


have given us roots.
After removing spaces, the string is 54 characters long. √(54) is
between 7 and 8, so it is written in the form of a grid with 7 rows
and 8 columns.
Q-15
The encoded message is obtained by displaying the characters of
each column, with a space between column texts. The encoded
message for the grid above is:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau

Create a function to encode a message.


Function Description
Complete the encryption function in the editor below.
encryption has the following parameter(s):
string s: a string to encrypt
Returns
string: the encrypted string
Q-15
Input Format :
One line of text, the string
Constraints :
1 <= Length_of_s <= 81
string contains characters in the range ascii[a-z] and space, ascii(32).
Sample Input :
haveaniceday
Sample Output :
hae and via ecy
Explanation :
L=12, √12 is between 3 and 4 . Rewritten with rows and columns:
feed
thed
og
Q-17
Given a list, rotate the list to the right by k places, where k is non-
negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.
Q-18
Raj is a boy. He loves Sanjeev’s recipes very much.
Raj like a positive integer p, and now he wants to get a receipt of
Sanjeev’s restaurant whose total price is exactly p. The current menus
of Sanjeev’s restaurant are shown the following table.
Q-18
Note that the i-th menu has the price 2i-1 (1 ≤ i ≤ 12).

Since Raj is a health conscious person, he cannot eat a lot. So please


find the minimum number of menus whose total price is exactly p.
Note that if he orders the same menu twice, then it is considered as
two menus are ordered.

Input
The first line contains an integer T, the number of test cases. Then T
test cases follow. Each test case contains an integer p.

Output
For each test case, print the minimum number of menus whose total
price is exactly p.
Q-18
Constraints
1≤T≤5
1 ≤ p ≤ 100000 (105)
There exists combinations of menus whose total price is exactly p.
Sample Input
4
10
256
255
4096
Sample Output
2
1
8
2
Q-18
Explanations
In the first sample, examples of the menus whose total price is 10 are
the following:
1+1+1+1+1+1+1+1+1+1 = 10 (10 menus)
1+1+1+1+1+1+1+1+2 = 10 (9 menus)
2+2+2+2+2 = 10 (5 menus)
2+4+4 = 10 (3 menus)
2+8 = 10 (2 menus)
Here the minimum number of menus is 2.

In the last sample, the optimal way is 2048+2048=4096 (2 menus).


Note that there is no menu whose price is 4096.
Q-19
Problem Description

Given a string A consisting only of '(' and ')'.


You need to find whether parentheses in A is balanced or not ,if it is
balanced then return 1 else return 0.

Problem Constraints
1 <= |A| <= 105

Input Format
First argument is an string A.

Output Format
Return 1 if parantheses in string are balanced else return 0.
Q-19
Example Input
Input 1:
A = "(()())"

Input 2:
A = "(()"

Example Output
Output 1:
1
Explanation 1:
Given string is balanced so we return 1
Output 2 :
0
Explanation 2:
Given string is not balanced so we return 0
Q-20
#include <stdio.h>
/* Function to get sum of digits */
int getSum(int n)
{
int sum;
/* Single line that calculates sum */
for (sum = 0; n > 0; sum += n % 10, n /= 10);

return sum;
}
int main()
{
int n = 687;
printf(" %d ", getSum(n));
return 0;
}
Q-20
/ C program to compute sum of digits in number using recursion.
#include <stdio.h>
using namespace std;
int sumDigits(int no)
{
return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}

int main(void)
{
printf("%d", sumDigits(687));
return 0;
}
Q-21
Lucky numbers are some special integer numbers. From basic
numbers, some special numbers are eliminated by their position.
Instead of their value, for their position, the numbers are eliminated.
The numbers which are not deleted, they are the lucky numbers.

Take the set of integers


1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,……
First, delete every second number, we get following reduced set.
1, 3, 5, 7, 9, 11, 13, 15, 17, 19,…………
Now, delete every third number, we get
1, 3, 7, 9, 13, 15, 19,….….
Continue this process indefinitely……
Any number that does NOT get deleted due to above process is
called “lucky”.
Q-21
Example 1:
Input:
N=5
Output: 0
Explanation: 5 is not a lucky number as it gets deleted in the second
iteration.

Example 2:
Input:
N = 19
Output: 1
Explanation: 19 is a lucky number
Q-21
#include <stdio.h>
/* Returns 1 if n is a lucky no. otherwise returns 0*/
int isLucky(int n ,int counter)
{

int next_position = n;
if(counter > n)
return 1;
if(n%counter == 0)
return 0;

/*calculate next position of input no*/


next_position -= next_position/counter;
return isLucky(next_position,counter+1);
}
int main()
{
int x = 13;
if( isLucky(x,2) )
printf("%d is a lucky no.", x);
else
printf("%d is not a lucky no.", x);

}
Q-22

Given a stack ,the task is to reverse a stack using recursion


Example 1:

Input:
12345

Output:
54321
Q-23

Given a stack, the task is to sort it such that the top of the stack has
the greatest element.

Example 1:

Input:
Stack: 3 2 1
Output: 3 2 1
Example 2:

Input:
Stack: 11 2 32 3 41
Output: 41 32 11 3 2
Q-23

Given n pairs of parentheses, write a function to generate all


combinations of well-formed parentheses of length 2*n.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"


Make sure the returned list of strings are sorted.
Q-24
Given an array of meeting time intervals where
intervals[i] = [starti, endi] , determine if a person could attend all
meetings.

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]


Output: false
Example 2:

Input: intervals = [[7,10],[2,4]]


Output: true
Q-25
Example :
Input 1:
[ [1, 18], [18, 23], [15, 29], [4, 15], [2, 11], [5, 13] ]
Output 1:
4
Q-26
Given an integer array nums and an integer k, return the kth largest
element in the array.

Note that it is the kth largest element in the sorted order, not the kth
distinct element.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2


Output: 5
Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4


Output: 4
Q-27
Problem Description

Given an array A , representing seats in each row of a stadium. You


need to sell tickets to B people.

Each seat costs equal to the number of vacant seats in the row it
belongs to. The task is to maximize the profit by selling the tickets
to B people.

Input Format
First argument is the array A.

Second argument is integer B.

Output Format
Return one integer, the answer to the problem.
Q-27

Example Input
Input 1:
A = [2, 3]
B=3

Input 2:
A = [1, 4]
B=2
Example Output
Output 1:
7
Output 2:
7
Q-12
Given a sentence, , print each word of the sentence in a new line.
Input Format
The first and only line contains a sentence, .
Constraints
Output Format
Print each word of the sentence in a new line.
Sample Input 0
This is C
Sample Output 0
This
is
C
Explanation 0
In the given string, there are three words ["This", "is", "C"]. We have to print
each of these words in a new line.
Sample Input 1
Learning C is fun
Sample Output 1
Learning
C
is
fun
Sample Input 2
How is that
Sample Output 2
How
Is
that
int main()
{ char *s;
int i;
s =(char*)malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
for( i = 0; i < len; i++) {
if(s[i] == ' ') {
printf("\n"); }
else {
printf("%c", s[i]);
} }
free(s); return 0;
}
Q-13
Given a string, , consisting of alphabets and digits, find the frequency of each
digit in the given string.
Input Format
The first line contains a string, which is the given number.
Constraints

All the elements of num are made of english alphabets and digits.
Output Format
Print ten space-separated integers in a single line denoting the frequency of
each digit from to .
Sample Input 0
a11472o5t6
Sample Output 0
0210111100
Explanation 0
In the given string:
 occurs two times.
 and occur one time each.
 The remaining digits and don't occur at all.
Sample Input 1
lw4n88j12n1
Sample Output 1
0 2 1 0 1 0 0 0 2 0
Sample Input 2
1v88886l256338ar0ekk
Sample Output 2
1 1 1 2 0 1 2 0 5 0
int main()
{

char *s;
s = (char*)malloc(1024 * sizeof(char));
scanf("%s", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s), i;
int arr[10];
for(i = 0; i < 10; i++)
arr[i] = 0;

for(i = 0; i < len; i++) { //


if(s[i] >= '0' && s[i] <= '9') {
arr[(int)(s[i]-'0')]++;
}
}
for(i = 0; i < 10; i++)
printf("%d ", arr[i]);
printf("\n");
free(s);
return 0;
}
Q-14
You are given n triangles, specifically, their sides ai, bi and ci . Print them in
the same style but sorted by their areas from the smallest one to the largest
one. It is guaranteed that all the areas are different.
The best way to calculate a area of the triangle with sides , and is Heron's
formula:
S = sqrt(p*(p-a)*(p-b)*(p-c))
where . P =(a+b+c)/2
Input Format
First line of each test file contains a single integer . lines follow with ai, bi and
ci on each separated by single spaces.
Output Format
Print exactly lines. On each line print integers separated by single spaces,
which are ai, bi and ci of the corresponding triangle.
Sample Input 0
3
7 24 25
5 12 13
345
Sample Output 0
345
5 12 13
7 24 25
struct Triangle
{
int a, b, c;
};

int square(struct Triangle t)


{
int a = t.a, b = t.b, c = t.c;
return (a + b + c)*(a + b - c)*(a - b + c)*(-a + b + c);
}
void sort_by_square(struct Triangle* a, int n)
{
int i,j;
for ( i = 0; i < n; i++)
for ( j = i + 1; j < n; j++)
if (square(a[i]) > square(a[j]))
{
struct Triangle temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int main()
{
int n,i;
scanf("%d", &n);

struct Triangle *a = calloc(n, sizeof(struct Triangle));


for (i = 0; i < n; i++)
scanf("%d%d%d", &a[i].a, &a[i].b, &a[i].c);
sort_by_square(a, n);
for (i = 0; i < n; i++)
printf("%d %d %d\n", a[i].a, a[i].b, a[i].c);
return 0;
}
Q-15
Program to find the array type (odd, even or mixed array) is discussed here.
Given an array of integers, display the type of the array.

Input format:

• Input consists of 1 integer and 1 array.


• Integer corresponds to the size of an array.
Sample Input:

5
2
4
1
3
5

Sample output:

Mixed
int main() {
//fill the code;
int n;
scanf("%d",&n);
int arr[n];
int i;
int odd = 0, even = 0;
for(i = 0; i < n; i++) {
scanf("%d",&arr[i]); }
for(i = 0; i < n; i++) {
if(arr[i] % 2 == 1)
odd++;
if(arr[i] % 2 == 0)
even++;
}
if(odd == n)
printf("Odd");
else if(even == n)
printf("Even");
else
printf("Mixed");
return 0;
}
Q-16
Program to find the sum of perfect square elements in an array is discussed
here. An array is given as input and the sum of all the perfect square
elements present in the array is produced as output.

For example, consider the array

Input: arr = {1, 2, 3, 4, 5, 9}


The perfect squares are 1, 4, 9.
Sum = 1 + 4 + 9 = 14
#include<stdio.h>
#include<math.h>
int isPerfectSquare(int number)
{
int iVar;
float fVar;

fVar=sqrt((double)number);
iVar=fVar;

if(iVar==fVar)
return number;
else
return 0;
}
int main() {
int n;
scanf("%d",&n);
int arr[n];
int i;
for(i = 0; i < n; i++){
scanf("%d",&arr[i]);}
int sum = 0;
for(i = 0; i < n; i++)
{
sum = sum + isPerfectSquare(arr[i]);
}
printf("%d",sum);
return 0;
}
Q-17
Program to sort a string in alphabetical order is discussed here. Given a string,
the task is to sort the string in alphabetical order and display it as output.

For example, consider the following strings

Input: face

Output: acef
int main ()
{
char string[100];
printf("\n\t Enter the string : ");
scanf("%s",string);
char temp;
int i, j;
int n = strlen(string);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (string[i] > string[j]) {
temp = string[i];
string[i] = string[j];
string[j] = temp; } } }

printf("The sorted string is : %s", string);


return 0;
}
Q-18
Program to find all possible permutations in which 'n' people can occupy 'r' seats in a
theater is discussed here.

N friends are planning to go to a movie. One among them suggested few movies and
all others started to discuss and finally they selected a movie. One among them quickly
booked their tickets online, to their surprise they are unable to select their seats. All of
them got confused. Then anyhow, decided to go to the movie. They rushed to reach the
theater on time. Again they are surprised that no one was there in the theater. They are
the only people about to watch the movie. There is 'r' number of seats in which, 'n'
number persons should sit. In how many ways they can sit inside the theater?

Given the number of people 'n' and the number of seats 'r' as input. The task is to find
the different number of ways in which 'n' number of people can be seated in those 'r'
number of seats.
Input:
Number of people: 5
Number of Rows: 3
Output:
The total number of ways in which 'n' people can be seated in 'r' seats = 60.
Calculation:
P(n,r) = n! /(n-r)!
#include<stdio.h>
int fact(long int x)
{
long int f=1,i;
for(i=1;i<=x;i++)
{
f=f*i;
}
return f;
}
int main()
{
long int n,r,p,temp;
long int num,den;
// Enter the number of seats
printf("Enter the number of seats available : ");
scanf("%ld",&r);
// Enter the number of people
printf("nEnter the number of persons : ");
scanf("%ld",&n);
// Base condition
// Swap n and r
if(n < r)
{
temp=n;
n=r;
r=temp;
}
num=fact(n);
den=fact(n-r);
p=num/den;
printf("nNumber of ways people can be seated : ");
printf("%ld",p);
}
Q-19
Program to toggle each character in a string is discussed here. A string is
given as input in which all the lower case letters are converted to upper case
and the upper case letters are converted to lower case.
For example, consider the following string
Input: FacePrep
Output: fACEpREP
Input: FocucAcadeMy
Output: fOCUSaCADEmy
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
void toggleCase(char * str);
int main()
{
char str[MAX_SIZE];
printf("Enter any string: ");
gets(str);

printf("String before toggling case: %s", str);


toggleCase(str);
printf("String after toggling case: %s", str);
return 0;
}
void toggleCase(char * str)
{
int i = 0;
while(str[i] != '\0’) {
if(str[i]>='a' && str[i]<='z')
{
str[i] = str[i] - 32; }
else if(str[i]>='A' && str[i]<='Z')
{
str[i] = str[i] + 32;
}
i++;
}
}
Q-20
Program to remove all characters in a string except alphabets is discussed
here. Given a string, remove all the characters except alphabets and display it
as output. For example, consider the following example

Input and Output Format:


Input consists of a string. Assume the maximum length of the string is 200.
The characters in the string can contain both uppercase, lowercase, and
symbols.

Sample Input:
pro$#&gra7m
Sample Output:
program
int main()
{
char str[150];
int i, j;
printf("\nEnter a string : ");
gets(str);
for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] ==
'\0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
printf("\nResultant String : ");
puts(str);
return 0;
}
Q-21
Printing an array into Zigzag fashion is discussed here. Suppose you were
given an array of integers, and you are told to sort the integers in a zig-zag
pattern. In general, in a zig-zag pattern, the first integer is less than the second
integer, which is greater than the third integer, which is less than the fourth
integer, and so on.
Hence, the converted array should be in the form of
e1 < e2 > e3 < e4 > e5 < e6.
Input 1:
7
4 3 7 8 6 2 1

Output 1:
3 7 4 8 2 6 1

Input 2:
4
1 4 3 2

Output 2:
1 4 2 3
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void zig_zag_fashion(int arr[], int n)
{
int flag = 1;
int i;
for (i=0; i<=n-2; i++)
{
if (flag)
{
if (arr[i] > arr[i+1])
swap(&arr[i], &arr[i+1]);
}
else
{
if (arr[i] < arr[i+1])
swap(&arr[i], &arr[i+1]);
}
flag = !flag;
}
}
int main()
{
int n,i;
printf("\nEnter the number of elements : " );
scanf("%d", &n);
int arr[n];
printf("\nInput the array elements : ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("\nZigzag pattern of the array : ");
zig_zag_fashion(arr, n);
for (i=0; i<n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Q-22
Program to print Pascal's triangle is discussed here. Pascals triangle is a
triangular array of the binomial coefficients.
The numbers outside Pascal's triangle are all "0". These "0s" are very
important for the triangular pattern to work to form a triangular array. The
triangle starts with a number "1" above, and any new number added below the
upper number "1" is just the sum of the two numbers above, except for the
edge, which is all "1".
row 0 =1
row 1 = (0+1), (1+0) = 1, 1
row 2 = (0+1), (1+1), (1+0) = 1, 2, 1
row 3 = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1
row 4 = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
row 5 = (0+1), (1+4), (4+6), (6+4), (4+1),(1+0) = 1, 5, 10, 10, 5, 1
row 6 = (0+1), (1+5), (5+10), (10+10), (10+5), (5+1), (1+0) = 1, 6, 15, 20, 15,
6, 1
int main()
{
int rows, coef = 1, space, i, j;
printf("\nEnter the number of rows : ");
scanf("%d",&rows);
printf("\n");

for(i=0; i<rows; i++)


{
for(space=1; space <= rows-i; space++)
printf(" ");
for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;

printf("%4d", coef);
}
printf("\n\n");
}

return 0;
}
Q-23
Input:
First line contains an integer, the number of test cases ‘T’. Each test case
should be an integer. Size of the array ‘N’ in the second line. In the third line,
input the integer elements of the array in a single line separated by space.
Element X should be inputted in the fourth line, i.e., after entering the
elements of array. Repeat the above steps second line onwards for multiple
test cases.
Output:
Print the output in a separate line returning the index of the element X. If the
element is not present, then print -1.
Constraints:
1 <= T <= 100
1 <= N <= 100
1 <= Arr[i] <= 100
Input:
2
4
1234
3
5
10 90 20 30 40
40
Output:
2
4
Explanation:
There are 2 test cases (Note 2 at the beginning of input)
Test Case 1: Input: arr[] = {1, 2, 3, 4},
Element to be searched = 3.
Output: 2
Explanation: 3 is present at index 2.

Test Case 2: Input: arr[] = {10, 90, 20, 30, 40},


Element to be searched = 40.
Output: 4
Explanation: 40 is present at index 4.
#include<stdio.h>
// This function returns index of element x in arr[]
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
{
// Return the index of the element if the element
// is found
if (arr[i] == x)
return i;
}
//return -1 if the element is not found
return -1;
}
int main()
{
// Note that size of arr[] is considered 100 according to
// the constraints mentioned in problem statement.
int arr[100], x, t, n, i;

// Input the number of test cases you want to run


scanf("%d", &t);

// One by one run for all input test cases


while (t--)
{
// Input the size of the array
scanf("%d", &n);

// Input the array


for (i=0; i<n; i++)
scanf("%d",&arr[i]);
// Input the element to be searched
scanf("%d", &x);

// Compute and print result


printf("%d\n", search(arr, n, x));
}
return 0;
}
Q-24
Enormous Input Test Problem Code:
The purpose of this problem is to verify whether the method you are using
To read input data is sufficiently fast to handle problems branded with the
enormous Input/Output warning. You are expected to be able to process at
least 2.5 MB. Of input data per second at runtime.
Input:-
The input begins with two positive integers n, k (n,k<=10’7). The next n lines
of input contains one positive integer t’i not greater then 10’9, each.

Output:
Write a single integer to output , denoting how many integers t’i are divisible
by k.
Input:-
7 3
1
51
966369
7
9
999996
11

Output:-

4
void main()
{
int n,k,i,t;

int tot=0;
printf("Enter Two Value\n");
scanf("%d%d",&n,&k);

for(i=0; i<n;i++)
{
scanf("%d",&t);
if(t%k==0)
{
tot++;
}
}

printf("Value is :%d\n",tot);

}
Q-25
You are given an integer N, Write a program to calculate the sum of the digits
of N.

Input:-
The first line contains an integer T, total number of testcases. Then follow T
lines, each line contains an integer N.
Output:- Calculate the sum of digits of N.

Constraints:-
1 <= T <=1000
1 <= N <=100000
Input:-
3
12345
31203
2123

Output:-
15
9
8
void main()
{
int T;
printf("Enter Number of TestCase\n");
scanf("%d",&T);

while(T--)
{
int N;
int rem,sum=0;
printf("Enter Number\n");
scanf("%d",&N);
while(N!=0)
{
rem = N%10;
sum = sum + rem;
N = N/10;
}
printf("%d\n",sum);
}
}
Q-26
You are given four integers a,b,c and d. Determine if there is a rectangle such
that the lengths of its sides are a,b,c and d(in any order).

Input:-
The first line of the input contains a single integer T denoting the number of
test cases. The description of T test cases follows.
The first and only of each test case contains four space-separated integer
a,b,c and d.

Output:-
For each test case , print a single line containing one string “YES” or “NO”
Constraints:
1 <= t <=1000
1<= a,b,c,d <=10000

Input:
3
1 1 2 2
3 2 2 3
4 2 2 2

Output:-
YES
YES
NO
void main()
{
int T;
printf("Enter Number of TestCase\n");
scanf("%d",&T);

while(T--)
{
int a,b,c,d;
printf("\nEnter Four Side\n");
scanf("%d%d%d%d",&a,&b,&c,&d);
if((a==c && b==d) || (a==b && c==d) || (a==d && c==b))
{
printf("\nYES");
}
else
{
printf("NO");
}
}
}
Q-27

Chef is a really and respectful person, in sharp contrast to his little brother,
Who is a very nice and disrespectful person. Chef always sends messages to his
friends in all small letters, whereas the little brother sends messages in all capital
letters.

You just received a message given by a string s. You don’t know whether this
message is sent by Chef or his brother. Also the communication channel through
which you received the message is erroneous and hence can flip a letter from
uppercase to lowercase or vice versa. However you know that this channel can make
at most k such flips.

Determine whether the messages could have been sent only by Chef , only by the
little brother , the message could have been sent only by Chef , only by the little
brother, by both or by none.
Input:-
The first line of the input contains a single integer T denoting the number of
test cases. The description of T test cases follows.
The first line of each test cases contains two space-separated integer N and K
denoting the length of the string S and the maximum number of flips that the
erroneous channel can make.
The second line contains a single string s denoting the messages you received.

Output:-
For each test case , output a single line containing one string- ‘chef’ , ‘brother’
, ‘both’ , ‘none’.
Constraints:-
1 <= t <= 1000
1 <= N <= 100
0 <= K <=N
S consists only of (lowercase and uppercase)
Input:-
4
5 1
frauD
6 1
FRAUD
7 4
Life
10 4
sTRAWBerry
Output:-

Chef
brother
both
none
void main()
{
int T;
printf("Enter Number of TestCase\n");
scanf("%d",&T);

while(T--)
{
int n,k,i;
int cap=0;
int small=0;
char ch[20];

printf("\nEnter Value of N\n ");


scanf("%d",&n);
printf("\nEnter Value of K\n");
scanf("%d",&k);
printf("\n Enter String Value\n");
scanf("%s",&ch);
for(i=0; i<n; i++)
{
char ch1;
int p;
ch1= ch[i];
p = ch1; // ASCII CODE
// CAPITAL ASCII 65 to 90
// SMALL ASCII 97 to 122

if(p>=65 && p<=90)


{
cap++;
}
else
{
small++;
}
}
// we have no. of small and capital letters

if(cap==small)
{
if(k>=cap)
{
printf("both\n");
}
else if(k<cap)
{
printf("none\n");
}

}
else if(small > cap)
{
if(k>=small)
{
printf("both\n");
}
else if(k<cap)
{
printf("none\n");
}
else
{
printf("chef\n");
}
}
else if(cap > small)
{
if(k>=cap)
{
printf("both\n");
}
else if(k<small)
{
printf("none\n");
}
else
{
printf("brother\n");
}
}

}
}
Q-28
He knows some subset of the letter of lattin alphabet. In order to help Jeff to
study, Chef gave him a book with the text consisting of N words . Jeff can read
a word if it consists only of the letters he knows.

Now Chef is curious about which words his brother will be able to read and
which are not. Please help him!.

Input:-
The first line of the input contains a lowercase Latin letter string S. consisting
of the letters Jeff can read. Every letter will appear in S no more than once.

The second line of the input contains an integer N denoting the number of
words in the book.
Output:-
For each of the words output “Yes” in case Jeff can read it. And “No”
otherwise.

Constraints
1<= ISI <=26
1<= N <=1000
1<=|wi|<=12
Each letter will appear in S no more than once
S,W consist only of lowercase Lattin letters.

Input:-
act
2
cat
dog
Output:-

Yes

No
void main()
{
char s[100];
int a[26]= {0}; // we put the value 0 in all the blocks
int len,len1,i,j;

printf("Enter String Value\n");


scanf("%s",&s);
len = strlen(s);

for(i=0; i<len; i++)


{
char x = s[i]; // lets suppose x = 'c'
int p = x; // p = 99
p = p-97; // index of that character p=2

a[p]=1;
}
int n;
printf("Enter N\n");
scanf("%d",&n);

for(i=0;i<n;i++)
{
int count=0; // no of character that not present in string s
char k[10];
printf("Enter String\n");
scanf("%s",&k); // k ---> words
len1= strlen(k);

for(j=0; j<len1; j++)


{
char z = k[j]; // let's supose z = 'f'
int h=z; // h = 102
h = h-97; // h =5
if(a[h]==0)
count++;
else
count = count;
}
if(count>0)
printf("NO\n");
else
printf("YES\n");
}

}
Q-29
What is the maximum number of squares of size 2x2 that can be fit in a right
angled isosceles triangle of base B.
One side of the square must be parallel to the base of the isosceles triangle.
Base is the shortest side of the triangle

Input:-
First line contains T, the number of test cases.
Each of the following T lines contains 1 integer B.

Output:-
Output exactly T lines, each line containing the required answer.
Constraints:-
1 ≤ T ≤ 103
1 ≤ B ≤ 104
Sample Input

11
1
2
3
4
5
6
7
8
9
10
11
Sample Output

0
0
0
1
1
3
3
6
6
10
10
#include<stdio.h>
int main()
{
int T;
printf("Enter Test Case\n");
scanf("%d",&T);

while(T--)
{
int b;
printf("Enter Side of Triangle\n");
scanf("%d",&b);
if(b==1 || b==2 || b==3)
{
printf("0\n");
}
else
{
if(b%2==0) // for even
{
int area =0.5*b*b;
int res = (area -b)/4;
printf("%d \n",res);
}
else // for odd
{
b = b-1;
int area =0.5*b*b;
int res = (area -b)/4;
printf("%d \n",res);
}
}
}
}
Q-30
Kostya likes the number 4 much. Of course! This number has such a lot of properties,
like:
• Four is the smallest composite number;
• It is also the smallest Smith number;
• The smallest non-cyclic group has four elements;
• Four is the maximal degree of the equation that can be solved in radicals;
• There is four-color theorem that states that any map can be colored in no
more than four colors in such a way that no two adjacent regions are colored in the
same color;
• Lagrange's four-square theorem states that every positive integer can be
written as the sum of at most four square numbers;
• Four is the maximum number of dimensions of a real division algebra;
• In bases 6 and 12, 4 is a 1-automorphic number;
• And there are a lot more cool stuff about this number!
Impressed by the power of this number, Kostya has begun to look for occurrences of
four anywhere. He has a list of T integers, for each of them he wants to calculate the
number of occurrences of the digit 4 in the decimal representation. He is too busy
now, so please help him.

Input:-
The first line of input consists of a single integer T, denoting the number of integers in
Kostya's list.
Then, there are T lines, each of them contain a single integer from the list.
Output:-
Output T lines. Each of these lines should contain the number of occurences of the
digit 4 in the respective integer from Kostya's list.
Constraints:-
• 1 ≤ T ≤ 105
• (Subtask 1): 0 ≤ Numbers from the list ≤ 9 - 33 points.
• (Subtask 2): 0 ≤ Numbers from the list ≤ 109 - 67 points.
Input:
5
447474
228
6664
40
81

Output:
4
0
1
1
0
#include<stdio.h>
int main()
{
int T;
printf("Enter Test Case\n");
scanf("%d",&T);

while(T--)
{
int n,i;
char ch[100];
scanf("%d",&n);
sprintf(ch, "%d", n);
int count=0;
int len;
len = strlen(ch);
for(i=0; i<len; i++)
{
if(ch[i]=='4')
{
count++;
}
else
{
count=count;
}
}
printf("%d \n",count);
}
}
Q-31
Chef's daily routine is very simple. He starts his day with cooking food, then he eats
the food and finally proceeds for sleeping thus ending his day. Chef carries a robot as
his personal assistant whose job is to log the activities of Chef at various instants
during the day. Today it recorded activities that Chef was doing at N different instants.
These instances are recorded in chronological order (in increasing order of time). This
log is provided to you in form of a string s of length N, consisting of characters 'C', 'E'
and 'S'. If s[i] = 'C', then it means that at the i-th instant Chef was cooking, 'E' denoting
he was eating and 'S' means he was sleeping.
You have to tell whether the record log made by the robot could possibly be correct or
not.
Input:-
The first line of the input contains an integer T denoting the number of test cases. The
description of T test cases follows.
The only line of each test case contains string s.
Output:-
For each test case, output a single line containing "yes" or "no" (without quotes)
accordingly.
Constraints
• 1 ≤ T ≤ 20
• 1 ≤ N ≤ 105
Input:
5
CES
CS
CCC
SC
ECCC

Output:
yes
yes
yes
no
no
#include<stdio.h>
int main()
{
int T;
printf("Enter Number of Test Case\n");
scanf("%d",&T);

while(T--)
{
int len,i,count=0;
char ch[10];
printf("Enter A String\n");
scanf("%s",&ch);

len = strlen(ch);
for(i=0; i<len-1; i++)
{
if(ch[i]=='C')
{
if(ch[i+1]=='E' || ch[i+1]=='S' || ch[i+1]=='C')
{
count++;
}
}
else if(ch[i]=='E')
{
if(ch[i+1]=='S' || ch[i+1]=='E')
{
count++;
}
}
else if(ch[i]=='S')
{
if(ch[i+1]=='S')
{
count++;
}
}
}

if(count==len-1)
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
}
Q-32
Chef Two and Chef Ten are playing a game with a number XX. In one turn, they can
multiply XX by 22. The goal of the game is to make XX divisible by 1010.
Help the Chefs find the smallest number of turns necessary to win the game (it may be
possible to win in zero turns) or determine that it is impossible.
Input
• The first line of the input contains a single integer TT denoting the number
of test cases. The description of TT test cases follows.
• The first and only line of each test case contains a single integer denoting the
initial value of XX.
Output
For each test case, print a single line containing one integer — the minimum required
number of turns or −1−1 if there is no way to win the game.
Constraints
• 1≤T≤10001≤T≤1000
• 0≤X≤1090≤X≤109
Example Input
3
10
25
1
Example Output
0
1
-1
#include<stdio.h>
int main()
{
int T;
printf("Enter Number of Test Case\n");
scanf("%d",&T);

while(T--)
{
int n;
printf("Enter A Number\n");
scanf("%d",&n);
if(n%10==0)
{
printf("0\n");
}
else if(n%5==0)
{
printf("1\n");
}
else
{
printf("-1\n");
}
}
}
Q-33
Print a pattern of numbers from to as shown below. Each of the numbers is
separated by a single space.
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Input Format
The input will contain a single integer .
Constraints
Sample Input 0
2
Sample Output 0
222
212
222
Sample Input 1
5
Sample Output 1
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
#include<stdio.h>
void print2Dsequence(int n){
int i,j,k,l;
int s = 2 * n - 1;
for (i = 0; i < (s / 2) + 1; i++) {
int m = n;
for ( j = 0; j < i; j++) {

printf("%d ",m);
m--;
}
for ( k = 0; k < s - 2 * i; k++) {

printf("%d ",n-i);
}
m = n - i + 1;
for ( l = 0; l < i; l++) {

printf("%d ",m);
m++;
}

printf("\n");
}
for (i = s / 2 - 1; i >= 0; i--) {
int m = n;
for (j = 0; j < i; j++) {

printf("%d ",m);
m--;
}
for (k = 0; k < s - 2 * i; k++) {

printf("%d ",n-i);
}
m = n - i + 1;
for ( l = 0; l < i; l++) {

printf("%d ",m);
m++;
}

printf("\n");
}
}
int main(){
int n = 4;

printf("The sequence of concurrent rectangle of 4 is : \n");


print2Dsequence(n);
return 0;
}
Q-34

Given a time in -hour AM/PM format, convert it to military (24-hour) time.

Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.

- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

 Return '12:01:00'.

 Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor below. It should return a new string

representing the input time in 24 hour format.

timeConversion has the following parameter(s):


Returns
• string: the time in hour format
Input Format
A single string that represents a time in -hour clock format (i.e.:
or ).
Constraints
• All input times are valid
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
int main() {

char s[20];
scanf("%s",s);
if(s[strlen(s)-2]=='P' || s[strlen(s)-2]=='p')
{
if(!(s[0]=='1' && s[1]=='2'))
{

s[0]=s[0]+1;
s[1]=s[1]+2;
}
}
else if(s[strlen(s)-2]=='A' || s[strlen(s)-2]=='a')
{
if(s[0]=='1' && s[1]=='2')
{
s[0]='0';
s[1]='0';
}
}

s[strlen(s)-2]='\0';
printf("%s",s);

return 0;
}
Q-35
You are in charge of the cake for a child's birthday. You have decided the cake will

have one candle for each year of their total age. They will only be able to blow out the

tallest of the candles. Count how many candles are tallest.

Example

The maximum height candles are units high. There are of them, so return .

Function Description

Complete the function birthdayCakeCandles in the editor below.

birthdayCakeCandles has the following parameter(s):

 int candles[n]: the candle heights


You are in charge of the cake for a child's birthday. You have decided the cake will

have one candle for each year of their total age. They will only be able to blow out the

tallest of the candles. Count how many candles are tallest.

Example

The maximum height candles are units high. There are of them, so return .

Function Description

Complete the function birthdayCakeCandles in the editor below.

birthdayCakeCandles has the following parameter(s):

 int candles[n]: the candle heights


int main() {
int i;
int n;
int max = 0;
scanf("%d", &n);
int a[n];
int count = 0;
for (i = 1; i <= n; i++) {
scanf("%d", & a[i]);
if (max < a[i])
max = a[i];
}
for (i = 1; i <= n; i++)
if (a[i] == max)
count++;
printf("%d", count);
return 0;
}
Q-36
Given five positive integers, find the minimum and maximum values that can
be calculated by summing exactly four of the five integers. Then print the
respective minimum and maximum values as a single line of two space-
separated long integers.
Example

The minimum sum is and the maximum sum is . The function prints
16 24
Function Description
Complete the miniMaxSum function in the editor below.
miniMaxSum has the following parameter(s):
• arr: an array of integers
Print

Print two space-separated integers on one line: the minimum sum and the maximum sum

of of elements.

Input Format

A single line of five space-separated integers.

Constraints

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values

that can be calculated by summing exactly four of the five integers. (The output can be greater

than a 32 bit integer.)


Sample Input
12345
Sample Output
10 14
Explanation
The numbers are , , , , and . Calculate the following sums using four of the five
integers:
1. Sum everything except , the sum is .
2. Sum everything except , the sum is .
3. Sum everything except , the sum is .
4. Sum everything except , the sum is .
5. Sum everything except , the sum is .
int main()
{
long long int a[5],i,max=-1,min=100000000000,sum=0;
for(i=0;i<5;i++)
{
scanf("%lld",&a[i]);
sum = sum + a[i];
if(a[i]<min){
min = a[i];
printf("Min %d\n",min);
}
if(a[i]>max){
max = a[i];
printf("Max %d\n",max);
}
}
printf("%lld %lld",sum-max,sum-min);
return 0;
}

You might also like