0% found this document useful (0 votes)
8 views

Automata _code_Fix

The document contains a series of sample practice questions for the AMCAT exam, focusing on identifying and correcting errors in C++ code snippets. Each question includes a description of the problem, the provided code, and a link for further solutions. The questions cover various programming concepts such as loops, conditionals, and functions.

Uploaded by

Aman kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Automata _code_Fix

The document contains a series of sample practice questions for the AMCAT exam, focusing on identifying and correcting errors in C++ code snippets. Each question includes a description of the problem, the provided code, and a link for further solutions. The questions cover various programming concepts such as loops, conditionals, and functions.

Uploaded by

Aman kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Sample Practice Questions for AMCAT

Sr.No Questions/Incorrect Correct Code Link for the


code Questions with
Solution

1. Ram is a 6 years old #include <iostream> https://prepinsta.com/


boy who loves to play using namespace std; dxc/automata-fix-que
with numeric legos. stions-and-answers/#
One day ram’s mom int main()
created a number using
those legos and asked {
ram to tell the number
of elements available int starting_point,
between two specific ending_point, arr[20],
numbers ‘alpha1’ and length, j;
‘alpha2’. After 15 years
when ram started cin >> length >>
learning C++, he now starting_point >>
wants to write a C++ ending_point;
code to find the number
of elements lies for(j=0; j<length;
between ranges alpha1 j++)
and alpha2. If the
number is arr and the {
starting and ending
points are alpha1 and cin>>arr[j];
alpha2, find the
numbers of elements }
lies in the range
for(j=0;j<length;j++)
Input:​
Three space-separated {
integers​
1. First is the length of
arr.​ if(arr[j]>=starting_point
2. Second is the starting &&
point as alpha1​ arr[j]<ending_point)
3. The third is the
endpoint as alpha2​ {
Output:​
Indexes of elements lie cout<<" "<< j ;
between this range.
}
Example​
Input​ }
9 2 6​
123456789 return 0;
Output​ }
1234

Find the error in the


given code

#include <iostream>

using namespace std;

int main() {

int starting_point,
ending_point, arr[20],
length, j;

cin >> length >>


starting_point >>
ending_point;

for (j = 0; j <=
length; j++) {

cin >> arr[j];

for (j = 0; j < length;


j++) {

if (arr[j] >=
starting_point && arr[j]
<= ending_point) {

cout << j << " ";

return 0;}

2. Given Function/method #include https://prepinsta.com/


pow need to return the <bits/stdc++.h> amcat/automata-fix/q
x raised to the power n, double myPow(double uestion-2/
with the help of stl x, int n) {
function. You are
required to fix logical return pow(x,n);
errors in given code.
}
Note : Use STL
Function only similar to
power.

Input: x = 2.00000, n =
10

Expected Output:
1024.00000

Current output: 10.0000

double myPow(double
x, int n)

return (x,n);

3. You need to fix the bool isUgly(int n) { https://prepinsta.com/


code syntactically and if(n==0)return amcat/automata-fix/q
if there are any logical false; uestion-4/
errors fix them too.
Statement : An ugly while(n%2==0)n/=2;
number is a positive
integer whose prime while(n%3==0)n/=3;
factors are limited to 2,
3, and 5. while(n%5==0)n/=5;
return n==1;
Given an integer n, }
return true if n is an
ugly number.

bool isUgly(int n) {

if(n==0)return
false;

While
n/=2;(n%2==0)

While
n/=3;(n%3==0)

whilen/=5;(n%5==0)
return n==1;

4. Write a logical part for int isPalindrome(string https://prepinsta.com/


checking the S) amcat/automata-fix/
palindrome of string in ​ {
the given code. ​ int left=0;
​ int
Input: S = “abba” right=S.length()-1;
Output: 1 while(left<=right){

int isPalindrome(string if(S[left]!=S[right]){


S) return 0;
​ { }else{
​ int left=0; left++;
​ int right--;
right=S.length()-1; }
while(left<=right){ }
if( ){ if(left>right){
return 0; return 1;
}else{ ​ }
left ; ​ }
right ;
}
}
if( ){
return 1;
​ }
​ }

5. write a logical part for void https://prepinsta.com/


the program to Convert binarytointegerl(numbe amcat/automata-fix/
Binary to Decimal by r)
using the given {
function. int dval=0, base=1,
rem;
Example 1: while(number > 0)
{
Input: “0001”​ rem = number %
Output: “1” 10;
dval = dval + rem *
Example 2: base;
num = number /
Input: “0010”​ 10;
Output: “2” base = base * 2;
}
Example 3: cout<>num;
binarytointeger(num);
Input: “0100”​ return 0;
Output: “3” }

Void
binarytointeger(number
)
{
// Type your code
here
}
void main()
{
int num;
cin>>num;
binarytointeger(num);
}

6. Check for syntax error/ int main(){ https://prepinsta.com/


logical error and correct int n; amcat/automata-fix/
the error to get the cin>>n;
desired output. for(int
i=1;i<=n;i++);{
review the code for ​ cout<<i;
syntax errors and }
logical mistakes, then }
make the necessary
corrections to achieve
the desired output.

print from 1 to n.

The function/method
main compiles
unsuccessfully due to
syntactical error , your
task is to debug the
program​
is to debug the program
so that it passes all test
case

Int main(){
Int n;
cin<<n;
for(int
i==1;i>=n;i++);{
cout>>i;
}
}

7. Check for syntax error/ #include <stdio.h> https://prepinsta.com/


logical error and correct amcat/automata-fix/
the error to get the int main() {
desired output. int n;
scanf("%d",&n);
Rectify the error, printf("%d”,n);
recompile the code, and }
debug the code.

#include
Int main(){
Int n;
Scanf(%f,”&n”);
Printf(%f,”n”);
}

8. Check for syntax error/ int fib(int n) { https://prepinsta.com/


logical error and correct if(n<=1) return n; amcat/automata-fix/
the error to get the int prev2 = 0,
desired output. prev1 = 1, cur;
for(int
You’re required Write i=2;i<=n;i++){
the logic for printing cur =
the ‘nth’ fibonacci prev1+prev2;
number In a given prev2 = prev1;
function no need to prev1 = cur;
write any boiler code. }
Only Write Logical part return cur;
in given section }

int fib(int n) {
if(n<=1) return n;
int prev2 = 0,
prev1 = 1, cur;
for(int
i=2;i<=n;i++){
//write your code
here.
}
return cur;
}
9. Review the code for int binarysearch(int https://prepinsta.com/
syntax errors and arr[], int n, int k) { amcat/automata-fix/
logical mistakes for int start = 0;
binary search. int end = n - 1;

int binarysearch(int while (start <= end) {


arr[], int n, int k){ int middle = start +
int start=0; (end - start) / 2; //
int end=n-1; Corrected middle
while (start <= calculation
end) {
int middle = start+ if (arr[middle] ==
(end + start) / 2; k)
return middle;
if (arr[middle] ==
k) if (arr[middle] > k)
return middle; end = middle -
1; // Corrected update
if (arr[middle] > k) of end
start = middle -
1; else
start = middle +
else 1; // Corrected update
end = middle + of start
1; }
}
return -1;
return -1; }
}

10. You are required to fix https://prepinsta.com/


logical error if any and amcat/automata-fix/
required write full logic
for the code

Statement:Given two
non-decreasingly sorted
integer arrays, nums1
and nums2, which are
already sorted in
non-decreasing order.
Additionally, you are
given two integers, m
and n, representing the
number of elements in
nums1 and nums2,
respectively. void merge(int
nums1[], int m, int
nums2[], int n) {
Your task is to merge int j = 0;
the elements from for(int i = m; i < m +
nums1 and nums2 into n; i++) { // Fixed loop
a single array and store condition
the result in nums1. nums1[i] =
The total number of nums2[j]; // Copy
elements in nums1 elements from nums2
should be m + n. to nums1
j++;
void merge(int }
nums1[], int m, int sort(nums1, nums1 +
nums2[], int n) { m + n); // Sort the final
int j = 0; merged array
for(int i = m; i < }
(); i++) {
//Write your code
here.
}
sort(nums1, nums1
+ m + n);
}

11. Check for syntax error/ void sortArray(int len, https://prepinsta.com/


logical error and correct int *arr) dxc/automata-fix-que
the error to get the { stions-and-answers/#
desired output. int i, max, location,
temp, j,k;
The function sortString if(len%2 == 0)
modifies the input list {
by sorting its elements for(i=0;i<len;i++)
depending upon the {
length of the array, i.e; max=arr[i];
if the length of the location = i;
array is even, then the for(j=i;j<len;j++)
elements are arranged if(max>arr[j])
in the ascending order, {
and if the length of the max=arr[j];
array is odd, then the location = j;
elements are arranged
in the descending order }
temp=arr[i];
arr[i]=arr[location];
arr[location]=temp;
}
}
else
{
for(i=0;i<len;i++)
The function sortString {
accepts two arguments max=arr[i];
– len representing the location = i;
length of the string, and for(j=i;j<len;j++)
arr a list of characters, if(max<arr[j])
representing the input {
list respectively. max=arr[j];
location = j;
The function sortString
compiles successfully }
but fails to get the temp=arr[i];
desired results for some arr[i]=arr[location];
test cases due to logical arr[location]=temp;
errors. Your task is to }
fix the code, so that it }
passess all the test cases }

void sortArray(int len,


int *arr)
{
int i, max, location,
temp, j,k;
if(len/2 == 0)//error
in this line
{
for(i=0;i<len;i++)
{
max=arr[i];
location = i;
for(j=i;j<len;j++)

if(max<arr[j])//error in
this line
{
max=arr[j];
location = j;

}
temp=arr[i];

arr[i]=arr[location];

arr[location]=temp;
}
}
else
{
for(i=0;i<len;i++)
{
max=arr[i];
location = i;
for(j=i;j<len;j++)
if(max>arr[j])//error in
this line
{
max=arr[j];
location = j;

}
temp=arr[i];

arr[i]=arr[location];

arr[location]=temp;
}
}
}

12. Check for syntax error/ void maxReplace(int https://prepinsta.com/


logical error and correct size, int *inputList) dxc/automata-fix-que
the error to get the { stions-and-answers/#
desired output. int i,sum=0;
for(i=0;i<size;i++)
The function {
maxReplace print space sum +=
separated integers inputList[i];
representing the input }
list after replacing all for(i=0;i<size;i++)
the elements of the {
input list with the sum
of all the elements of inputList[i]=sum;
the input list. }
for(i=0;i<size;i++)
The function {
maxReplace accepts cout<<inputList[i];
two arguments – size }
an integer representing }
the size of the input list
and inputList, a list of
integers representing
the input list
respectively.
The function
maxReplace compiles
unsuccessfully due to
compilation errors.
Your task is to fix the
code so that it passes all
the test cases.

void maxReplace(int
size, int *inputList)
{
int i,sum=0;
for(i=0;i<size;i++)
{
sum +=
inputList[i];
}
for(i=0;i<size;i++)
{
sum =
inputList[i];//error in
this line
}
for(i=0;i<size;i++)
{
cout<<inputList[i];
}
}

13. Check for syntax error/ https://prepinsta.com/


logical error and correct void dxc/automata-fix-que
the error to get the replaceElements(int stions-and-answers/#
desired output. size, int *arr)
{
The function int i,j;
replaceElements is int sum=0;
modifying the input list for (i=0;i<size;i++)
in such a way – if the {
sum of all the elements sum+=arr[i];
of the input list is odd, }
then all the elements of if(size % 2 ==
the input list are 0)//error in this line
supposed to be replaced {
by 1s, and in case if the i=0;
sum of all the elements while(i<size)
of the input list is even, {
then the elements arr[i] = 0;
should be replaced by i += 1;
0s.
}
For example, given the }
input list [1,2,3,4,5], the else
function will modify {
the input list like [1, 1, j=1;
1, 1, 1] while(j<size)
{
The function arr[j]=1;
replaceElements j+=1;
accepts two arguments }
– size an integer }
representing the size of
the given input list and
arr, a list of integers
representing the input
list.

The function
replaceElements
compiles successfully
but fails to get the
desired result for some
test cases due to
incorrect
implementation of the
function. Your task is to
fix the code so that it
passes all the test cases

void
replaceElements(int
size, int *arr)
{
int i,j;
int sum=0;
for (i=0;i<size;i++)
{
sum+=arr[i];
}
if(size % 2 ==
0)//error in this line
{
i=0;
while(i<size)
{
arr[i] = 0;
i += 1;

}
}
else
{
j=1;
while(j<size)
{
arr[j]=1;
j+=1;
}
}

14. #include <iostream> #include <iostream> https://stackoverflow.


com/questions/68276
unsigned long long unsigned long long 060/problem-to-return
factorial(int n) { factorial(int n) { -and-printf-unsigned-l
if (n == 0) { if (n == 0 || n == 1) { ong
return 1; return 1;
} else { } else {
return n *
} factorial(n - 1);
} }
}

15. Find the security key to #include <iostream> https://prepinsta.com/


access the bank account #include <cstring> dxc/automata-fix-que
from the encrypted stions-and-answers/#
message. The key in the using namespace std;
message is the first
repeating number from int main() {
the given message of char arr[20];
numbers. int x, y, len, flag = 0;

Input format: cin >> arr;


len = strlen(arr); //
Single Integer value Corrected function
name
Output format:
for (x = 0; x < len;
The first repeating x++) {
number from the for (y = x + 1; y <
message len; y++) {
if (arr[x] ==
Example: arr[y] && flag == 0) {
cout << arr[y]
Input: << endl; // Fixed
missing semicolon and
123456654321 replaced printf with
cout
flag = 1;
Output: break;
}
1 }
if (flag == 1) {
Find the error in the break; // Ensure
given C++ loop exits after finding
programming code: first duplicate
}
#include }

#include return 0;
}
int main()

char arr[20];

int x, y, len, flag=0;

scanf("%s",arr);

len = strIn(arr);

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

for(y=x+1;y<len;y++)

if(arr[x]==arr[y]
&& flag == 0)

printf("%c",arr[y])

flag = 1;

break;

}
return 0;

16. From the given set of int sumOfValue(int len, https://prepinsta.com/


the array, integer int* arr, int value) dxc/automata-fix-que
numbers in an array stions-and-answers/#
Write the program to {
add the numbers the
same as the given int sum = 0;
number. The program
takes 3 space-separated for(int i =0 ; i < len ;
values, First is the i++)
length as ’len’, Second
arr[]ar as ’arr’, Third {
the given number as
‘value’. if(arr[i]==value)
sum += value;
Input format:
}
Three space-separated
inputs return sum;

1.​ Length }
2.​ Input number
3.​ Element

Output format:

Sum of elements the


same as the value

Example:

Input:

8 12342562 2

Output:

The code for the given


problem is solved by
one of our coders
finding the error in the
given code.
int sumOfValue(int len,
int* arr, int value)

int sum = 0;

for(int i =0 ; i < len


-1 ; )

if(arr[i]==value)

sum += value;

return sum;

17. For the generation of #include <iostream> https://prepinsta.com/


energy at the atomic using namespace std; dxc/automata-fix-que
center the energy used stions-and-answers/#
to start the plant is in int main() {
negative sign and the int total_reading, i,
energy generated after arr[20];
the plant started is
represented with a cin >> total_reading;
positive sign. Our task
is to calculate the total for (i = 0; i <
number of energy that total_reading; i++) {
is generated throughout cin >> arr[i];
the day. }

Below is the code in C int sum = 0;


programming but it is
not working well find for (i = 0; i <
the error in the code total_reading; i++) {
sum += arr[i];
Input format: }

cout << sum << endl;

return 0;
}
Two inputs One for the
number of times energy
was recorded as
‘total_reading’ and
second the reading of
the energy used or
produced ‘arr’

Output format:

Sum of the total energy


produced

Example:

Input:

1 4 -5 6 7 -4 4 -1

Output:

12

#include <stdio.h>

int main()

int total_reading, i,
arr[20];

cin>>total_reading;

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

cin>>arr[i]);

int sum = 0;

for(i =
0;i<total_reading;i++){
sum+=arr[i];

cout<<sum;

return 0;

18. Print the number at the #include <iostream> https://prepinsta.com/


given index of the using namespace std; dxc/automata-fix-que
series 1 1 2 3 5… and stions-and-answers/#
so on. Consider the int main() {
index as the number int val1 = 0, val2 = 1,
and print the value val3 = 1;
int number, i;
Input format:
cin >> number;
Single input of the
index of the number as for (i = 2; i <=
‘number’ number; i++) {
val3 = val1 + val2;
Output format: val1 = val2;
val2 = val3;
The number at the }
given index of the
series cout << val3 <<
endl;
Example:
return 0;
Input: }
10

Output:

55

below is the code for


this problem find the
problem in the given
code:

#include <stdio.h>

int main()

{
int val1 = 0, val2 = 1,
val3 = 1;

int number, i;

cin>>number);

for(i=2; i<=number;
i++)

val2 = val1 +val3;

val1 = val2;

val2 = val3;

cout<<&val3;

return 0;

19. Function/method int employeeID (int len, https://prepinsta.com/


employeeID ​accepts int start, int end, int dxc/automata-fix-que
four arguments-len​​, an *arr) stions-and-answers/#
integer representing the {
length of input list. arr,​
start , end of range and for (i = 0; i < len;
a list of integers It i++)
returns an integer {
representing the sum of
all id’s of the if (arr[i] > start &&
employees in that range arr[i] < end)
for example ​ {
flag = 1;
len = }
6,start=30,end=50, arr else
= [29 38 12 48 39 55] ​ {
flag = -1;
}

if (flag == 1)
​ {
s = s + i;
}
}
function /method will return s;
return 8 i.e 1+3+4.
Function/method
compiles successfully
but fails to return the
desired result for
some/all cases due to
incorrect
implementation. Your
task is to debug the
code so that it passes all
test cases.

Example

Input

6 30 50

29 38 12 48 39 55

Output

Explanation :

There are 3 employees


with id 1, 3, 4 whose
distance from the office
lies within the given
range sum of the id’s is
8.

int employeeID (int len,


int start, int end, int
*arr)
{

for (i = 0; i < len;


i++)
{
if (arr[i] > start ||
arr[i] < end)
​ {
flag = 1;
}
else
​ {
flag = -1;
}

if (flag == -1)
​ {
s = s + i;
}
}
return s;
}

20. Function/method int securityKey (char https://prepinsta.com/


secretKey ​accepts a *a) dxc/automata-fix-que
single argument- arr​​, a { stions-and-answers/#
string. It returns an int i, j, len, count = 0;
integer representing the len = strlen (a);
count of all characters
in it without for (i = 0; i < len;
duplicates(length of i++)
string after removing {
duplicates) int flag = 1;
for (j = i + 1; j <
arr=5435436789 len; j++)
​ {
function /method will if (a[i] == a[j])
return 7. ​ {
Function/method flag = 0;
compiles successfully break;
but fails to return the }
desired result for }
some/all cases due to if (flag == 1)
incorrect ​ {
implementation. Your count++;
task is to debug the }
code so that it passes all }
test cases. return count;
}
Example

Input

5435436789

Output

Explanation:
The repeated digits in
the data are 5,4 and 3.
So, the security key is 7
which is the length of
the string after
removing duplicates.

int securityKey (char


*a)
{

int i, j, len, count = 0;


len = strlen (a);
for (i = 0; i < len;
i++)
{
int flag = 1;
for (j = 0; j < len;
j++)
​ {
if (a[i] == a[j])
​ {
break;
}
}
if (flag == 1)
​ {
count++;
}
}
return count;
}

21 Function/method int energyCal (int https://prepinsta.com/


energyCal ​accepts two numOfChem, int dxc/automata-fix-que
arguments-len​​, an *energy) stions-and-answers/#
integer representing the {
length of input list.
energy,​a list of int numOfChem,
integers. It returns an energy[100], i, j, result,
integer representing the temp;
sum of elements whose for (i = 0; i <
product is maximum numOfChem; i++)
for example len = 7, {
energy= [9 -3 8 -6 -7 8 for (j = i + 1; j <
10] numOfChem; j++)
​ {
function /method will if (energy[i] >
return 19 energy[j])
function/method ​ {
compiles successfully temp =
but fails to return the energy[i];
desired result for energy[i] =
some/all cases due to energy[j];
incorrect energy[j] =
implementation. Your temp;
task is to debug the }
code so that it passes all }
test cases. }
result =
Example energy[numOfChem -
1] +
Input energy[numOfChem -
2];
7 return result;
}
9 -3 8 -6 -7 8 10

Output

19

Explanation

The maximum product


of the energies is 90 i.e
9*10

So the sum of energy of


chemicals is 19.

int energyCal (int


numOfChem, int
*energy)
{

int numOfChem,
energy[100], i, j, result,
temp;
for (i = 0; i <
numOfChem; i++)
{
for (j = i + 1; j <
numOfChem + 1; j++)
​ {
if (energy[i] <=
energy[j])
​ {
temp =
energy[i];
energy[i] =
energy[j];
energy[j] =
temp;
}
}
}
result =
energy[numOfChem -
1] +
energy[numOfChem -
2];
return result;
}

22. Function/method int energyCal (int https://prepinsta.com/


energyCal ​accepts two numOfChem, int dxc/automata-fix-que
arguments-len​​, an *energy) stions-and-answers/#
integer representing the {
length of input list.
energy,​a list of int numOfChem,
integers. It returns an energy[100], i, j, result,
integer representing the temp;
sum of elements whose for (i = 0; i <
product is maximum numOfChem; i++)
for example len = 7, {
energy= [9 -3 8 -6 -7 8 for (j = i + 1; j <
10] numOfChem; j++)
​ {
function /method will if (energy[i] >
return 19 energy[j])
function/method ​ {
compiles successfully temp =
but fails to return the energy[i];
desired result for energy[i] =
some/all cases due to energy[j];
incorrect energy[j] =
implementation. Your temp;
task is to debug the }
code so that it passes all }
test cases. }
result =
Example energy[numOfChem -
1] +
Input energy[numOfChem -
2];
return result;
7 }

9 -3 8 -6 -7 8 10

Output

19

Explanation

The maximum product


of the energies is 90 i.e
9*10

So the sum of energy of


chemicals is 19.

int energyCal (int


numOfChem, int
*energy)
{

int numOfChem,
energy[100], i, j, result,
temp;
for (i = 0; i <
numOfChem; i++)
{
for (j = i + 1; j <
numOfChem + 1; j++)
​ {
if (energy[i] <=
energy[j])
​ {
temp =
energy[i];
energy[i] =
energy[j];
energy[j] =
temp;
}
}
}
result =
energy[numOfChem -
1] +
energy[numOfChem -
2];
return result;
}
23. Function/method int nthFib () https://prepinsta.com/
nthFib ​accepts single { dxc/automata-fix-que
argument-num​​, an int a = 0; stions-and-answers/#
integer representing int b = 1;
number. for example int c = 1;
num=9 int num, i;

function /method will for (i = 2; i <= num;


return 34 i++)
function/method {
compiles successfully c = a + b;
but fails to return the a = b;
desired result for b = c;
some/all cases due to }
incorrect return c;
implementation. Your }
task is to debug the
code so that it passes all
test cases.

Example

Input

Output

21

Explanation:

The sequence generated


by the system will be 1,
1, 2, 3, 5, 8, 13, 21. The
8th number generated
from this series will be
21

int nthFib ()
{
int a = 0;
int b = 1;
int c = 1;
int num, i;

for (i = 0; i <= num;


i++)
{
c = a + b;
a = b;
b = c;
}
return a + b;
}

24. The​function int * studentSort (int https://prepinsta.com/


studentSort(int​*arr, int arr[], int len) dxc/automata-fix-que
len) accepts​an integer { stions-and-answers/#
array arr(which is
heights of students) of int small, pos, i, j,
length len as an input temp;
and performs an in for (i = 0; i < len;
place sort operations on i++)
it. The function is {
expected to return the for (j = 0; j < len;
input array sorted in j++)
descending order of ​ {
their heights, but temp = 0;
instead, it returns the if (arr[i] > arr[j])
array sorted in ​ {
ascending order due to temp = arr[i];
a bug in the code. arr[i] = arr[j];
arr[j] = temp;
Your task is to debug }
the program to pass all }
test cases. }
return arr;
int * studentSort (int }
arr[], int len)
{

int small, pos, i, j,


temp;
for (i = 0; i < len;
i++)
{
for (j = 0; j < len;
j++)
​ {
temp = 0;
if (arr[i] <=
arr[j])
​ {
temp = arr[j];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}

25. The​function https://prepinsta.com/


patternPrint(int​num) dxc/automata-fix-que
​prints even or odd stions-and-answers/#
numbers based on the
values of the input
arguments num(num >=
0).
void printPattern (int
If the input number num)
num is even, the {
function is expected to int i, print = 0;
print the even whole if (num % 2 == 0)
numbers upto num and {
in case it is odd, is print = 0;
expected to print the for (i = 0; print <=
odd numbers upto num; i++)
num(inclusively). ​ {
cout<<print;
For example given print += 2;
input 6, the function }
prints the string “0 2 4 }
6”(without quotes). else
{
The function compiles print = 1;
successfully but fails to for (i = 0; print <=
print the desired result num; i++)
due to logical errors. ​ {
cout<< print;
Your task is to debug print += 2;
the program to pass all }
the test cases. }
}
Test Cases:

Test Case 1:

Input:

23

Expected Return Value:

1 3 5 7 9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45

Test Case 2:
Input:

14

Expected Return Value:

0 2 4 6 8 10 12 14 16
18 20 22 24 26

void printPattern (int


num)
{

int i, print = 0;
if (num / 2 == 0)
{
print = 0;
for (i = 0; i <=
num; i++)
​ {
cout<<print;
}
}
else
{
print = 1;
for (i = 0; i <=
num; i++)
​ {
cout<< print;
}
}
}

26. The function void printTable (int https://prepinsta.com/


printTable(int num) ​is num) dxc/automata-fix-que
supposed to print the { stions-and-answers/#
first twenty multiples of int value = 0;
the multiplication table for (int i = 1; i <= 20;
of the input number i++)
num​ ​. {
value = num * i;
The function compiles cout<<value;
fine but fails to return }
the desired result for }
some cases.
Your task is to fix the
program so that it
passes all the test cases.

Test cases:

TestCase 1:

Input:

Expected return value:

6 12 18 24 30 36 42
48 57 60 66 72 78 84
90 96 102 108 114 120

TestCase 2:

Input:

Expected return value:

0 0 0 0 0 0 0 0 0 0
0000000000

void printTable (int


num)
{
int value = 0;
for (int i = 0; i < 10;
i++)
{
value = num *
num;
cout<<value;
}
}

27. The function/method float allExponent (int https://prepinsta.com/


allExponent returns a baseValue, int dxc/automata-fix-que
real number exponentValue) stions-and-answers/#
representing the result {
of exponentiation of float res = 1;
base raised to power if (exponentValue <
exponent for all input 0)
values. {
The function/method res = (float)
allExponent accepts negativeExponent
two arguments – (baseValue,
baseValue, an integer exponentValue);
representing the base // is to find
and exponentValue, and exponents of negative
integer representing the numbers
exponent. }
else
The incomplete code in {
the function/method res = (float) 1 /
allExponent works only (negativeExponent
for negative values of (baseValue,
the exponent. You must exponentValue));
complete the code and ​ // find negative
make it work for exponents and then find
positive values of reciprocals of it to get
exponent as well. positive exponent
}
Another function return res;
negativeExponent uses }
an efficient way for
exponentiation but
accepts only negative
exponent values. You
are supposed to use this
function/method to
complete the code in
allExponent
function/method.

float allExponent (int


baseValue, int
exponentValue)
{
float res = 1;
if (exponentValue <
0)
{
res = (float)
negativeExponent
(baseValue,
exponentValue);
}
else
{
​ // write your
code for negative value
}
return res;
}

28. The function/method int https://prepinsta.com/


sameOddElementCount sameOddElementCount dxc/automata-fix-que
returns an integer (int size, int *inputList) stions-and-answers/#
representing the {
number of elements of int i, count = 0;
the input list which are for (i = 1; i < size;
odd numbers and equal i++)
to the elements to its {
left. For example, if the if ((inputList[i] % 2
input list is == 1) && (inputList[i]
[1,3,3,4,5,5,9,9,10,11] == inputList[i - 1]))
then the count++;
function/method should }
return the output ‘3’ as return count;
it has three similar }
groups i.e. {3,3},
{5,5}, {9,9}.​

The function/method
sameOddElementCount
accepts two arguments
– size, and integer
representing the size of
the input list and
inputList, a list of
integers representing
the input list.

The function/Method
compiles successfully
but fails to return the
desired result for some
test cases due to
incorrect
implementation of the
function/method
sameOddElementCount
. Your task is to fix the
code so that it passes all
the test cases.

Test Case 1:

Input :

11
[1, 5, 5, 2, 2, 7,7, 8, 6
,6, 9, 10]

Expected Return Value

Test Case 1:

Input :

[13, 12, 12, 13, 14]

Expected Return Value

int
sameOddElementCount
(int size, int *inputList)
{

int i, count = 0;
for (i = 1; i < size - 1;
i++)
{
if ((inputList[i] % 2
== 0) && (inputList[i]
== inputList[i--]))
count++;
}
return count;
}
29. The function https://prepinsta.com/
binarySearch(int*​ dxc/automata-fix-que
arr,int len, int target) stions-and-answers/#
performs the binary
search algorithm to
look for an element
target​in the input array
arr​of length len​​. In
case it is found the int binarySearch (int
function returns the *ar, int len, int target)
index of target​​in arr​​ {
and returns a-1 if not
found. int lo = 0, hi = len;
while (lo <= hi)
The function works {
seemingly well but int mid = (lo + hi) /
goes into an infinite 2;
loop for some test if (ar[mid] ==
cases. target)
​ {
Your task is to fix the return mid;
program so that it }
passes all the test cases. else
​ {
Note: If there is a ​Time if (ar[mid] <
limit exceeded error,​ it target)
can be due to an infinite ​ {
loop.​ lo = mid;
}
Test Cases: ​ else
​ {
TestCase 1: hi = mid - 1;
}
Input: }
}
[0 , 2 , 3 , 4 , 5, 6 , 7 , return -1;
8] , 8 , 4 }
Expected Return Value:​

TestCase 2:

Input:

[2 , 3],2,3

Expected Return Value:


1

int binarySearch (int


*ar, int len, int target)
{
int lo = 0, hi = len;
while (lo <= hi)
{
int mid = (lo + hi);
if (ar[mid] ==
target)
​ {
return mid;
}
else
​ {
if (ar[mid] <
target)
​ {
lo = lo - 1;
}
​ else
​ {
hi = mid - 1;
}
}
}
return -1;
}

30. Fix Syntax Error #include <iostream> https://faceprep.in/arti


cle/amcat-automata-fi
#include n int main() x-questions-with-ans
{ wers-face-prep/
int main() int x = 1; // Changed
from float to int, as
{ float x = 1.1; switch only works with
integral types
switch (x)
switch (x)
{ {
case 1:
case 1: std::cout std::cout <<
<< "Choice is 1"; "Choice is 1";
break;
break; default:
std::cout <<
"Invalid choice";
break;
default: std::cout }
<< "Invalid choice";
return 0;
break; }

return 0;

31. Fix Logical Error: int main() { ttps://faceprep.in/artic


int i, j, n = 5; le/amcat-automata-fix
void main() { for(i = 1; i < n; i++) -questions-with-answ
// Loop from 1 to 4 ers-face-prep/
int i, j, n = 5; {
for(j = i; j < n;
for(i = 1; i < n; i++) j++) // Remove the
semicolon here
{ {
cout << i; //
for(j = i; j < n; Print 'i' inside the loop
j++); }
cout << "\n"; //
{ Print a new line after
inner loop
cout<< i; }
return 0;
} }
cout<<”\n”;

32. Complete Code With int left_side_sum(int ttps://faceprep.in/artic


Function Reuse a[], int n, int idx) { le/amcat-automata-fix
int sum = 0; -questions-with-answ
for(int i = 0; i < idx; ers-face-prep/
i++) {
sum += a[i];
}
return sum;
}

int right_side_sum(int
a[], int n, int idx) {
int sum = 0;
Problem: Find the for(int i = idx + 1; i <
index of the n; i++) {
equilibrium element in sum += a[i];
an array. An }
equilibrium element is return sum;
one where the sum of }
all elements on its left
equals the sum on its int
right. Example: For findEquilibriumIndex(i
array a[] = {1, 2, 3, 4, nt a[], int n) {
3, 3}, the equilibrium for(int i = 0; i < n;
element is 4 because 1 i++) {
+ 2 + 3 = 3 + 3. if(left_side_sum(a,
n, i) ==
Code Template: right_side_sum(a, n, i))
{
#include <iostream> return i;
}
using namespace std;
}
int left_side_sum(int return -1;
a[], int n, int idx); }

int right_side_sum(int
a[], int n, int idx);
int
findEquilibriumIndex(i
nt a[], int n);
int main() {
int a[10], n, i;
cin >> n;
for(i = 0; i < n; i++)
{
cin >> a[i];
}
int equiIndex =
findEquilibriumIndex(a
, n);
if(equiIndex != -1) {
cout <<
a[equiIndex];
}
return 0;
}

33. Suppose a circular Answer: Option A https://gateoverflow.in


queue of capacity (n – Explanation: /1756/gate-cse-2012-
1) elements is Suppose we start question-35
implemented with an filling the queue. Let
array of n elements. the maxQueueSize (
Assume that the Capacity of the Queue)
insertion and deletion is 4. So the size of the
operation are carried array which is used to
out using REAR and implement this circular
FRONT as array index queue is 5, which is n.
variables, respectively. In the begining when
the queue is empty,
Initially, REAR = FRONT and REAR
FRONT = 0. The point to 0 index in the
conditions to detect array. REAR represents
queue full and queue insertion at the REAR
empty are index. FRONT
represents deletion
A. Full: (REAR+1) from the FRONT index.
mod n == FRONT,
empty: REAR == enqueue("a"); REAR =
FRONT (REAR+1)%5; (
FRONT = 0, REAR =
B. Full: (REAR+1) 1)
mod n == FRONT,
empty: (FRONT+1) enqueue("b"); REAR =
mod n == REAR (REAR+1)%5; (
FRONT = 0, REAR =
C. Full: REAR == 2)
FRONT, empty:
(REAR+1) mod n == enqueue("c"); REAR =
FRONT (REAR+1)%5; (
FRONT = 0, REAR =
D. Full: (FRONT+1) 3)
mod n == REAR,
empty: REAR == enqueue("d"); REAR =
FRONT (REAR+1)%5; (
FRONT = 0, REAR =
4)
Now the queue size is
4 which is equal to the
maxQueueSize.

Hence overflow
condition is reached.
Now, we can check for
the conditions. When
Queue Full :(
REAR+1)%n =
(4+1)%5 = 0 FRONT is
also 0.Hence ( REAR +
1 ) %n is equal to
FRONT.

When Queue Empty


:REAR was equal to
FRONT when empty (
because in the starting
before filling the queue
FRONT = REAR = 0 )
Hence Option A is
correct.

34. Which of the following Answer: Option D https://brainly.in/quest


is true about linked list Explanation: ion/29438514
implementation of To keep the Last In
stack? First Out order, a stack
can be implemented
A. In push operation, if using linked list in two
new nodes are inserted ways: a) In push
at the beginning of operation, if new nodes
linked list, then in pop are inserted at the
operation, nodes must beginning of linked list,
be removed from end. then in pop operation,
nodes must be removed
B. In push operation, if from beginning. b) In
new nodes are inserted push operation, if new
at the end, then in pop nodes are inserted at the
operation, nodes must end of linked list, then
be removed from the in pop operation, nodes
beginning. must be removed from
end.
C. Both of the above

D. None of the above


35. Priya has a box that Answer: Option D https://m4maths.com/
looks like a stack and 166044-Priya-has-a-b
she does the following To determine the final ox-that-looks-like-a-st
operations on empty state of the stack after ack-and-she-does-th
box PUSH(8) PUSH(7) performing the given e-following-operation
POP PUSH(1) operations, let's go s-on-empty-box-PUS
PUSH(3) through each operation H-8.html
step by step:
A. 31_8

B. 8_1_7 1.​ PUSH(8): The


stack now
C. 8_1_ contains [8].
2.​ PUSH(7): The
D. None of these stack now
contains [8, 7].
3.​ POP: This
operation
removes the top
element (7)
from the stack.
The stack now
contains [8].
4.​ PUSH(1): The
stack now
contains [8, 1].
5.​ PUSH(3): The
stack now
contains [8, 1,
3].

After performing all the


operations, the final
state of the stack is [8,
1, 3], with 3 being the
top element.
36. The function/method int findMaxElement(int https://codewindow.in
findMaxElement return len1, int* arr1, int len2, /automata-fixing-3/#g
an integer representing int* arr2) { oogle_vignette
the largest element in // Sort both arrays
the given two input arr1 =
lists. The sortArray(len1, arr1);
function/method arr2 =
findMaxElement sortArray(len2, arr2);
accepts four arguments
- len1, an integer // Get the maximum
representing the length elements from both
of the first list, arr1, a sorted arrays
list of integers int max1 = arr1[len1
representing the first - 1];
input list, len2, an int max2 = arr2[len2
integer representing the - 1];
length of the second
input list and arr2, a list // Return the
of integers representing maximum of the two
the second input list, return (max1 >
respectively. Another max2) ? max1 : max2;
function/method }
sortArray accepts two
arguments - len, an
integer representing the
length of the list and
arr, a list of integers,
respectively and return
a list sorted ascending
order. Your task is to
use the function/method
sortArray to complete
the code in
findMaxElement so that
it passes all the test
cases​
// You can print the
values to stdout for
debugging using
namespace std;

int* sortArray(int len,


int* arr)

int i=0,j=0,temp=0;

for(i=0;i<len;i++)
{ for(j=i+1;j<len;j++)

if(arr[i]>arr[j])

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

}}}

return arr;

int findMaxElement(int
len1, int* arr1, int len2,
int* arr2)

// write your code here

}
37. The function/method https://www.scribd.co
countElement returns There are a few syntax m/document/5139392
the number of elements errors in the given C++ 70/5-6075729976089
in the input list arr code: 379287
which are greater than
twice the input number 1.​ The for loop
K. The function/method has incorrect
countElement accepts syntax:​
three arguments - size,
an integer representing ○​ It
the size of the input list, should
numK, an integer use
representing the input semicol
number K and ons (;)
inputList, a list of instead
integers. The of
function/method comma
compiles s (,).​
unsuccessfully due to
syntactical error. Your 2.​The condition
task is to fix the code so inside the if
that it passes all the test statement does
cases.​ not correctly
// You can print the check for
values to stdout for numbers
debugging greater than
twice numK.​
using namespace std;
○​ It
int countElement(int should
size, int numK, int be
*inputList) inputLi
st[i] >
{ 2*
numK.
int i,count=0;
using namespace std;
for(int i=0,i<size,i++)
int countElement(int
{ size, int numK, int
*inputList)
if(inputList[i]>numK)
{
count+=1;
int count = 0;
}
for (int i = 0; i < size;
return count; i++) // Corrected loop
syntax
} {

if (inputList[i] > 2
* numK) // Fixed
condition

count++;

return count;

}
38. The function/method https://www.scribd.co
arrayReverse modifies m/document/5139392
the input list by 70/5-6075729976089
reversing its element using namespace std; 379287
The function/method
arrayReverse accepts void arrayReverse(int
two arguments - len, an len, int* arr) {
integer representing the int temp;
length of the list and for (int i = 0; i < len /
arr, list of integers 2; i++) { // Fix loop
representing the input condition
list, respectively. For temp = arr[i];
example, if the input arr[i] = arr[len - i -
list arr is {20 30 10 40 1]; // Corrected index
50}, the for swapping
function/method is arr[len - i - 1] =
supposed to print {50 temp;
40 10 30 20}. The }
function/method }
arrayReverse compiles
successfully but fails to
get the desired result
for some test cases due
to logical errors. Your
task is to fix the code so
that it passes all the test
cases.​

// You can print the


values to stdout for
debugging

void arrayReverse(int
len, int* arr)

int i, temp,
originalLen=len;
for(i=0;i<=originalLen/
2;i++)

temp = arr[len-1];

arr[len-1] = arr[i];
arr[i] = temp;

len =len-1;

39. Find the logical/syntax class Base { https://www.ibm.com/


error in the below code. protected: // Changed docs/en/i/7.3?topic=o
private to protected so nly-access-control-ba
#include <iostream> ​ Derived can access x se-class-members-c
using namespace std; int x;
Class Base{ public:
Private: Base() { x = 10; }
int x; };
Public:
Base() class Derived : public
{x=10;} Base {
};​ public:
Class Derived : public void show() {
Base { cout << x; }
public:​ };
void show()
{ cout<<x; int main() {
}}; Derived d;
int main() d.show();
{ return 0;
Derived d; }
d.show();​
return 0;​
}​

40. Find the logical/syntax class A { https://www.sanfound


error in the below code. public: ry.com/cplusplus-pro
#include <iostream>​ void show() { gramming-questions-
using namespace std;​ cout << "A"; answers-string-1/
class A {​ }
public:​ };
void show()
{ class B {
cout <<"A"; public:
}};​ void show() {
class B{ cout << "B";
public: }
void show() };
{
cout <<"B";
}}; class C : public A,
class C : public A, public B {}; // Added
public B {};​ missing semicolon
int main() {
C obj; int main()
obj.show(); { C obj;
return 0;
} // To avoid
ambiguity, explicitly
specify which show() to
call
obj.A::show(); //
Calls show() from class
A
obj.B::show(); //
Calls show() from class
B

return 0;
}

41. Find the logical/syntax #include <iostream> https://www.sanfound


error in the below code. #include <cstring> // ry.com/cplusplus-pro
#include <iostream>​ Required for strcpy() gramming-questions-
using namespace std;​ using namespace std; answers-string-1/
int main()
{ int main() {
char str1[]="Hello"; char str1[] = "Hello";
char str2[]="World"; char str2[] = "World";
str1=str2;
cout<<str1; strcpy(str1, str2); //
return 0; Correct way to copy
} string contents

cout << str1;


return 0;
}

Explanation:
○​ In C++,
you
cannot
assign
one
charact
er array
to
another
using
=.​

○​ Strings
in C++
are
stored
as
arrays,
and
arrays
do not
support
assign
ment.​

○​ Solutio
n: Use
strcpy()
from
<cstrin
g> to
copy
string
content
s.​

42. Find the logical/syntax int main() { Generative code


error in the below code. int arr[3][3] = { {1, 2,
#include <iostream>​ 3}, {4, 5, 6}, {7, 8, 9}
using namespace std;​ };
int main()
{ int* ptr = arr[1]; //
Correct: Points to the
first element of the
second row
int
arr[3][3]={{1,2,3},{4,5, cout << *ptr; //
6},{7,8,9}}; Dereferencing prints 4
(first element of second
int* ptr=(int*)arr[1][0]; row)

cout<<*ptr; return 0;
}
return 0;

43. Find the logical/syntax #include <iostream> https://stackoverflow.


error in the below code. using namespace std; com/questions/35354
#include <iostream>​ 003/program-to-find-t
using namespace std;​ int factorial(int n) he-factorial-of-numbe
int factorial(int n) if (n == 1) r-and-to-give-error-m
{ return 1; essage-for-negative-i
if(n==1) return n * factorial(n #:~:text=Add%20brac
- 1); // Fixed recursion es%20for%20your%2
return 1; issue 0else,0
}
Return n* factorial(n
--); int main() { // Fixed
`Int` → `int`
} cout << factorial(5);
return 0;
int main(){ }

cout<<factorial(5); Explanation:
return 0; Incorrect Recursive
Call: factorial(n--)
}
●​ Problem: n--
passes n first,
then
decrements it
after the
function call.​

●​ This leads to
infinite
recursion and
stack overflow.​
●​ Solution: Use
factorial(n - 1)
instead.

44. Fix the Syntax Error in #include <iostream> https://www.wscubete


Stack Implementation using namespace std; ch.com/resources/ds
a/stack-data-structure
#include <iostream> class Stack {
private:
using namespace std; int arr[5];
int top;
class Stack {
public:
private: Stack() { top = -1;
}
int arr[5];
void push(int val)
int top; {
if (top == 4) { //
public: Fix: Change top == 5 to
top == 4 (valid indices
Stack() { top = -1; are 0 to 4)
} cout <<
"Stack Overflow\n";
void push(int val)
return;
{
}
arr[++top] =
if (top == 5) {
val; // Fix: Increment
top first before
cout <<
assignment
"Stack Overflow\n";
}
return;
int pop() {
} if (top == -1) {
cout <<
top++; "Stack Underflow\n";
return -1; //
arr[top] = val; Fix: Return a valid
integer instead of
} nothing
}
int pop() { return arr[top--];
// Fix: Decrement top
if (top == -1) { after returning value
}
cout <<
"Stack Underflow\n"; void display() {
if (top == -1) {
return; cout <<
"Stack is empty\n";
} return;
}
return arr[top--]; for (int i = top; i
>= 0; i--)
} cout << arr[i]
<< " ";
void display() { cout << endl;
}
if (top == -1) { };
cout << int main() {
"Stack is empty\n"; Stack s;
s.push(10);
return; s.push(20);
s.push(30);
} cout << "Popped
element: " << s.pop()
for (int i = top; i
<< endl;
>= 0; i--)
s.display();
return 0;
cout << arr[i]
}
<< " ";

cout << endl;

};

int main() {

Stack s;

s.push(10);

s.push(20);

s.push(30);

cout << "Popped


element: " << s.pop()
<< endl;

s.display();

return 0;

}
45. Fix Logical Error in #include <iostream> https://www.hackerea
Stack Using STL #include <stack> rth.com/practice/note
using namespace std; s/stacks-and-queues/
#include <iostream>
int main() {
#include <stack> stack<int> s;
s.push(5);
using namespace std; s.push(10);
s.push(15);
int main() {
cout << "Top
stack<int> s; element: " << s.top()
<< endl;
s.push(5);
// Pop elements only
s.push(10); if the stack is not empty
while (!s.empty()) {
s.push(15); s.pop();
}
cout << "Top
element: " << s.top()
if (!s.empty()) {
<< endl;
cout << "Stack is
not empty\n";
s.pop();
cout << "Top
element: " << s.top()
s.pop();
<< endl; // Safe to
s.pop(); access top
} else {
s.pop(); // Error: cout << "Stack is
Extra pop() call empty\n";
}
if (!s.empty())
return 0;
cout << "Stack is }
not empty\n";

else

cout << "Stack is


empty\n";

cout << "Top


element: " << s.top()
<< endl; // Error:
Accessing top() on
empty stack

return 0;
}

Expected Output:
Top element: 15

Stack is empty

46. #include <iostream> https://stackoverflow.


Problem Statement: #include <stack> com/questions/62278
using namespace std; 018/reversing-string-
The given program tries using-stack-static-arr
to reverse a string using string ay-in-c
a stack but has syntax reverseString(string str)
and logical errors. Fix { // Change return type
the errors and ensure it to string
correctly reverses the stack<char> s;
input string. for (char ch : str) //
Use range-based for
#include <iostream> loop for correctness
s.push(ch);
#include <stack>
string reversed = "";
using namespace std; while (!s.empty()) {
reversed +=
void s.top();
reverseString(string str) s.pop();
{ }
stack<char> s; return reversed; //
Return the reversed
for (int i = 0; i <= string
str.length(); i++) // }
Error in loop condition
int main() {
s.push(str[i]);
string input =
"ENGINEER";
cout << "Reversed
cout << "Reversed
string: ";
string: " <<
reverseString(input) <<
while (!s.empty()) {
endl; // Correct function
cout << s.top(); call
return 0;
s.pop(); }

}
return str; // Error:
Returning string in void
function

int main() {

string input =
"ENGINEER";

cout <<
reverseString(input); //
Error: Calling void
function in cout

return 0;

Expected Output:

Reversed
string:REENIGNE

47. #include <iostream> Generative Ai code


Problem Statement: using namespace std;

The following C++ class CircularQueue {


code attempts to private:
implement a Circular int arr[5];
Queue but has logical int front, rear, size;
errors. Fix the errors to
make the program run public:
correctly. CircularQueue() {
front = rear = -1;
#include <iostream> size = 5;
}
using namespace std;
void enqueue(int val)
class CircularQueue { {
if ((rear + 1) %
private: size == front) {
int arr[5]; cout << "Queue
Overflow\n";
int front, rear, size; return;
}
public: if (front == -1)
front = 0;
CircularQueue() { rear = (rear + 1) %
size;
front = rear = -1; arr[rear] = val;
}
size = 5;
int dequeue() {
} if (front == -1) {
cout << "Queue
void enqueue(int val) Underflow\n";
{ return -1; // Fix:
Return a valid integer
if ((rear + 1) % instead of nothing
size == front) { }
int item =
cout << "Queue
arr[front];
Overflow\n";
if (front == rear)
// Queue becomes
return;
empty
front = rear =
}
-1;
if (front == -1) else
front = 0; front = (front +
1) % size;
rear = (rear + 1) % return item;
size; }

arr[rear] = val; void display() {


if (front == -1) {
} cout << "Queue
is empty\n";
return;
}
int dequeue() { int i = front;
while (true) {
if (front == -1) { cout << arr[i]
<< " ";
cout << "Queue if (i == rear)
Underflow\n"; break; // Fix: Ensure
last element is printed
return; i = (i + 1) %
size;
} }
cout << endl;
}
int item = };
arr[front];
int main() {
if (front == rear) CircularQueue cq;
// Queue becomes cq.enqueue(10);
empty cq.enqueue(20);
cq.enqueue(30);
front = rear = cq.enqueue(40);
-1; cq.enqueue(50); //
Should show "Queue
else Overflow"
cout << "Dequeued:
front = (front + " << cq.dequeue() <<
1) % size; endl;
cq.display();
return item; return 0;
}
}

void display() {

if (front == -1) {

cout << "Queue


is empty\n";

return;

for (int i = front; i


!= rear; i = (i + 1) %
size)

cout << arr[i]


<< " ";

cout << arr[rear]


<< endl; // Error: Edge
case missing

};

int main() {

CircularQueue cq;

cq.enqueue(10);
cq.enqueue(20);

cq.enqueue(30);

cq.enqueue(40);

cq.enqueue(50); //
Should show "Queue
Overflow"

cout << "Dequeued:


" << cq.dequeue() <<
endl;

cq.display();

return 0;

Expected Output:

Queue Overflow

Dequeued: 10

20 30 40 50

48. #include <iostream> Generative Ai code


Problem Statement: #include <queue>
using namespace std;
The given C++ code
attempts to implement a int main() {
queue using STL queue<int> q;
(Standard Template q.push(5);
Library) but has logical q.push(10);
and syntax errors. Fix q.push(15);
them and ensure the
program runs correctly. cout << "Front
element: " << q.front()
#include <iostream> << endl;
q.pop();
#include <queue> q.pop();
q.pop();
using namespace std;
if (!q.empty())
int main() { cout << "Queue is
not empty\n";
queue<int> q; else
q.push(5); cout << "Queue is
empty\n";
q.push(10);
if (!q.empty()) // Fix:
q.push(15); Check before accessing
front()
cout << "Front
element: " << q.front()
cout << "Front << endl;
element: " << q.front()
<< endl; return 0;
}
q.pop();

q.pop();

q.pop();

q.pop(); // Error:
Extra pop() call

if (!q.empty())

cout << "Queue is


not empty\n";

else

cout << "Queue is


empty\n";

cout << "Front


element: " << q.front()
<< endl; // Error:
Accessing front() on
empty queue

return 0;

Expected Output:
Front element: 5

Queue is empty
49. #include <iostream>
Problem Statement: using namespace std;

The following code class Node { https://www.naukri.co


attempts to delete a public: m/code360/library/del
node from a singly int data; eting-a-node-in-a-link
linked list. However, it Node* next; ed-list-in-cpp
contains logical errors. Node(int val) {
Fix the errors and make data = val;
it functional. next = NULL;
#include <iostream> }
};
using namespace std;
class LinkedList {
class Node { private:
Node* head;
public:
public:
int data; LinkedList() {
head = NULL; }
Node* next;
void
Node(int val) { insertAtEnd(int val) {
Node*
data = val; newNode = new
Node(val);
next = NULL; if (head ==
NULL)
} head =
newNode;
}; else {
Node* temp
class LinkedList { = head;
while
private: (temp->next != NULL)
temp =
Node* head;
temp->next;
temp->next =
public:
newNode;
}
LinkedList() {
}
head = NULL; }

void void
insertAtEnd(int val) { deleteNode(int val) {
if (head ==
Node* NULL) {
newNode = new cout << "List
Node(val); is empty\n";
return;
}
if (head == Node* temp =
NULL) head;
Node* prev =
head = NULL;
newNode;
if (temp->data
else { == val) {
head =
Node* temp temp->next; // Fix:
= head; Assignment instead of
comparison
while delete temp;
(temp->next != NULL) return;
}
temp =
temp->next; while (temp !=
NULL && temp->data
temp->next = != val) {
newNode; prev = temp;
temp =
} temp->next;
}
}
if (temp ==
void deleteNode(int
NULL) {
val) {
cout <<
"Element not found\n";
if (head ==
return;
NULL) {
}
cout << "List
prev->next =
is empty\n";
temp->next; // Fix:
return; Assignment instead of
comparison
} delete temp;
}
Node* temp =
head; void display() {
Node* temp =
Node* prev = head;
NULL; while (temp !=
NULL) {
if (temp->data cout <<
== val) { temp->data << " ";
temp =
head == temp->next;
temp->next; // Error: }
Should be assignment, cout << endl;
not comparison }
};
delete temp;
int main() {
return; LinkedList list;
list.insertAtEnd(10);
} list.insertAtEnd(20);
list.insertAtEnd(30);
while (temp != list.deleteNode(20);
NULL && temp->data list.display();
!= val) { return 0;
}
prev = temp;

temp =
temp->next;

if (temp ==
NULL) {

cout <<
"Element not found\n";

return;

prev->next ==
temp->next; // Error:
Should be assignment,
not comparison

delete temp;

void display() {

Node* temp =
head;

while (temp !=
NULL) {

cout <<
temp->data << " ";
temp =
temp->next;

cout << endl;

};

int main() {

LinkedList list;

list.insertAtEnd(10);

list.insertAtEnd(20);

list.insertAtEnd(30);

list.deleteNode(20);

list.display();

return 0;

Expected Output:
10 30

50. #include <iostream> https://gist.github.co


Problem Statement: #include <stack> m/vnkdj5/0d63e4dd0
using namespace std; 542978793a2ad7d8a
The following C++ 788972
code attempts to string
convert a Postfix postfixToInfix(string
Expression to Infix, but exp) {
contains syntax and stack<string> s;
logical errors. Fix them
so the conversion for (int i = 0; i <
works correctly. exp.length(); i++) { //
Fix: Correct loop
#include <iostream> condition
char ch = exp[i];
#include <stack>
if (isalnum(ch))
using namespace std;
string s.push(string(1,
postfixToInfix(string ch)); // Fix: Proper
exp) { conversion to string
else {
stack<string> s; if (s.size() < 2) {
cout <<
for (int i = 0; i <= "Invalid postfix
exp.length(); i++) { // expression\n";
Error: Wrong loop return "";
condition }
string val1 =
char ch = exp[i]; s.top();
s.pop();
if (isalnum(ch)) string val2 =
s.top();
s.push(string(1, s.pop();
ch)); // Error: Incorrect string temp =
conversion to string "(" + val2 + ch + val1 +
")"; // Fix: Correct
else { operand order
s.push(temp);
string val1 = }
s.top(); }
return s.top();
s.pop(); }
string val2 =
int main() {
s.top();
string expr =
"ab+c*";
s.pop();
cout << "Infix
Expression: " <<
string temp =
postfixToInfix(expr) <<
"(" + val2 + ch + val1 +
endl;
")"; // Error: Wrong
return 0;
order of operands
}
s.push(temp);

return s.top();

int main() {

string expr =
"ab+c*";
cout << "Infix
Expression: " <<
postfixToInfix(expr) <<
endl;

return 0;

Expected Output:
Infix Expression:
((a+b)*c)

You might also like