Debugging Exercise
Debugging Exercise
DEBUGGING EXERCISE
Q1. Check for syntax error/ logical error and correct the error to get the
desired output.
The function palindrome(int number) checks whether the number entered
by the user is palindrome or not.A palindrome number is a number which
remains the same when its digits are reversed
The function palindrome(int number) accepts a single argument, and print
whether the number is palindrome or not.
The function palindrome(int number) compiles successfully but fails to get
the desired results for some test cases due to logical errors. Your task is to fix
the code, so that it passess all the test cases
void palindrome(int number)
{
int rev = 0,store, n1,left;
n1=number;
store= number;
while (number > 0)
{
left= number/10;
rev = rev + 10 * left;
number=number%10;
}
if(n1==rev)
printf("Number %d is Palindrome number",n1);
else
printf("it is not a Palindrome number");
}
2
Corrected Code
void palindrome(int number)
{
int rev = 0,store, n1,left;
n1=number;
store= number;
while (number > 0)
{
left= number%10; //these are the correct lines
rev = rev * 10 + left; //these are the correct lines
number=number/10; //these are the correct lines
}
if(n1==rev)
printf("Number %d is Palindrome number",n1);
else
printf("it is not a Palindrome number");
}
Q2. Check for syntax error/logical error and correct the error to get the
desired output.
The function search(int a[ ], int start, int last, int item) searches a certain
value entered by the user in the entered array.
• For example – If the entered array is arr{1,2,3,4,5}, and the entered
value is 2, then the output will be, item found at location 2. And if the
entered value is 6, then the output will be item not found.
The function search(int a[ ], int start, int last, int item) accepts 4 inputs, that
are – int a [ ] which represents the array, start which represents the start of
the array, last which represents the last element of the list, and item that
represents the .
3
The function search(int a[ ], int start, int last, int item) compiles successfully
but fails to get the desired results for some test cases due to logical errors.
Your task is to fix the code, so that it passes all the test cases
int Search(int a[], int start, int last, int item)
{
int mid;
if(last >= start)
{
mid = (start + last)/2;
if(a[mid] == item){
return mid+1;
}
else if(a[mid] < item){
return Search(a,start,mid+1,item);
}
else{
return Search(a,mid-1,last,item);
}
}
return -1;
Corrected Code
int Search(int a[], int start, int last, int item)
{
int mid;
if(last >= start)
{
mid = (start + last)/2;
4
if(a[mid] == item){
return mid+1;
}
else if(a[mid] < item){
return Search(a,mid+1,last,item); // This line is correct.
}
else{
return Search(a,start,mid-1,item); // This line is correct.
}
}
return -1;
}
Q3. Problem Statement – :
Check for syntax error/ logical error and correct the error to get the desired
output.
The following code snippet converts a binary decimal into a decimal number.
• For example– If the user enters a number 1001, than the output will be
9
The code snippets accepts a single argument – num representing the number
entered by the user.
The code snippet compiles successfully but fails to get the desired results for
some test cases due to logical errors. Your task is to fix the code, so that it
passess all the test cases
def main():
num = int(input("Insert a binary num (1s and 0s) \n"))
binary_val = num
decimal_val = 0
base = 1
5
Check for syntax error/ logical error and correct the error to get the desired
output.
The following code snippet to Check whether a given year is leap year or not.
For example –
• If the user enters the year 2020 , then the output will be ” 2020 is a
Leap Year “.
• If the user enters the year 2025 , then the output will be ” 2025 is not a
Leap Year “.
The code snippets accept a single argument – year representing the number
entered by the user.
The code snippet compiles successfully but fails to get the desired results for
some test cases due to logical errors. Your task is to fix the code so that it
passes all the test cases
def main():
year = int(input())
if year % 200 == 0:
print(f"{year} is a Leap Year")
elif year % 4 == 0 and year % 200 != 0:
print(f"{year} is a Leap Year")
else:
print(f"{year} is not a Leap Year")
if __name__ == "__main__":
main()
Corrected Code
def main():
year = int(input())
7
if __name__ == "__main__":
main()
Q5. Find if there is any bug in following code snippet
public class Main {
void main(String[] args) {
char Number = 19;
System.out.println(Number)
}
}
Correct Code
public class Main {
public static void main(String[] args) {
int Number = 19;
System.out.println(Number);
}
}
Q6. Find the errors
class manas {
public static void main(String[] args) {
8
int a, b;
Scanner scanner = new Scanner(System.in);
a = Scanner.nextInt();
b = Scanner.nextInt();
/*
if (b == 0) {
System.out.println("infinity");
return;
}
*/
System.out.println(a / b);
}
}
Correct code
class manas {
public static void main(String[] args) {
int a, b;
Scanner scanner = new Scanner(System.in);
a = scanner.nextInt();
b = scanner.nextInt();
if (b == 0) {
System.out.println("infinity");
return;
}
System.out.println(a / b);
9
}
}
Q7. Find if the code for BFS is correct, if not find the corrections.
void BFS(s) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList();
visited = true;
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next;
if (!visited[n]) {
visited[n] = true;
queue.add();
}
}
}
}
Corrected Code:
void BFS(int s) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList();
visited[s] = true;
10
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
Q8. # Program to convert temperature in celsius to fahrenheit
#Find the bugs
# change this value for a different result
celsius = 37.5;
# calculate fahrenheit
fahrenheit = (celsius - 32) / 1.8
print('%0.1f degree Celsius is equal to x degree Fahrenheit'
%(celsius,fahrenheit))
Corrected Code
celsius = 37.5
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit'
%(celsius,fahrenheit))
11
Q9. To print the Full Pyramid of Numbers, state the possible corrections
1
232
34543
4567654
567898765
Source Code
rows = int(input("Enter number of rows: "))
k=0
count=0
count1=0
for i in range(1, (rows-i)+1):
for space in range(1, rows+1):
print(" ", end="")
count+=1
while k!= (i+k-(2*count1)):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print((2*i)-1, end=" ")
k += 1
count1 = count = k = 0
print()
Corrected Code
12
if (str[i] == checkCharacter)
{
count;
}
}
cout << Number of << checkCharacter << = << count;
return 0;
}
Corrected Code
int main()
{
string str = "C++ Programming is awesome";
char checkCharacter = 'a';
int count = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == checkCharacter)
{
++ count;
}
}
cout << "Number of " << checkCharacter << " = " << count;
return 0;
}
Q11. void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME
*difference){
if(t2.seconds > t1.seconds)
14
{
--t1.minutes;
t1.seconds -= 60;
}
difference.seconds = t1.seconds - t2.seconds;
if(t2.minutes > t1.minutes)
{
--t1.hours;
t1.minutes -= 60;
}
difference.minutes = t1.minutes-t2.minutes;
difference.hours = t1.hours-t2.hours;
}
Corrected Code
void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME
*difference){
t1.minutes += 60;
}
difference->minutes = t1.minutes-t2.minutes;
difference->hours = t1.hours-t2.hours;
}
Q12. Find the errors in Program to Computer Power Using Recursion
#include <iostream>
int main()
{
int base, powerRaised, result;
cout << "Enter base number: ";
cin >> base;
Corrected Code
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
int base, powerRaised, result;
cout << "Enter base number: ";
cin >> base;
double len;
double hgt;
// parameterized constructor to initialize variables
Wall(double len, double hgt)
: length{len}
, height{hgt} {
}
public:
double calculateArea() {
return length * height;
}
};
int main() {
// create object and initialize data members
Wall wall1(10.5);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1->calculateArea() << endl;
cout << "Area of Wall 2: " << wall2->calculateArea();
return 0;
}
Corrected Code
class Wall {
private:
double length;
double height;
18
public:
Wall(double len, double hgt)
: length{len}
, height{hgt} {
}
double calculateArea() {
return length * height;
}
};
int main() {
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();
return 0;
}
Q14. // program to shuffle the deck of cards
//find the bugs present
// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
"Ace",
"2",
"3",
"4",
"5",
19
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
];
// empty array to contain cards
let deck = [];
// create a deck of cards
for (int i = 0; i < suits.length; i) {
for (int x = 0; x < values.length; x) {
let card = { Value: values[x], Suit: suits[i] };
deck.push(card);
}
}
// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
deck[i] = deck[j];
temp = deck[i];
deck[j] = temp;
}
console.log('The first five cards are:');
20
// display 5 results
for (let i = 0; i < 5; i++) {
console.log(`{deck[i].Value} of {deck[i].Suit}`)
}
Corrected Code
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [ "Ace", "2", "3", "4", "5", "6", “7", "8", "9", "10", "Jack",
“Queen", "King"];
let deck = [];
for (let i = 0; i < suits.length; i++) {
for (let x = 0; x < values.length; x++) {
let card = { Value: values[x], Suit: suits[i] };
deck.push(card);
}
}
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
console.log('The first five cards are:');
for (let i = 0; i < 5; i++) {
console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}
Q15. // program to check if a key exists
//check for all the bugs present
21
const person = {
id= 1,
name= 'John',
age= 23
}