NOTE: The code snippet given may be incomplete or have compile time, runtime or logical errors.

How to attempt Debugging Exercise?

  1. Copy the code to your code editor (e.g. VS Code).

  2. Add relevant header files like “#include <iostream>” etc.

  3. Run the code.

  4. You will notice the expected output is not printing at the console.

  5. Apply your smart coder mind to Debug the code.

  6. Warning: Only see the solution after you have tried enough.

  7. Debug the code. Sum of array.

#include<iostream>
using namespace std;

int main(){
    int n, sum;
    cin >> n;
    int input[n];
    for(int i=0;i<n;i++){
        cin >> input[0];
    }
     for(int i=0; i<n; i++){
         sum = sum + input[i];
     }
    cout << sum << endl;
    return 0;
}
  1. Debug the code. Linear Search.
void linearSearch(int arr[], int n ,int val){
    for(int i=0;i<n;i++){
        if(arr[i]==val){
            return;
        }
    }
    return;
}
  1. Debug the code. Your task is to populate the array using the integer values in the range 1 to N (both inclusive) in the order - 1,3,5,.......,6,4,2.
void populate(int arr[],int n){
    int j=0;
    for(int i=0; i < n; i = i + 2){
        arr[n-j] = i+2;
        arr[j] = i+1;
        j++;
    }
}
  1. Debug the code.
void swapAlternate(int arr[],int size){
    for(int i=0;i<size-1;i=i+2){
        int temp = arr[i];
        arr[i+1] = arr[i];
        arr[i] = temp;
    }
}
  1. Debug the code. List all pairs in array that sums to X.
int pairSumToX(int input[], int size, int x){
	int pairs = 0;
	for(int i=0; i<size; i++){
		for(int j=i; j<size; j++){
			if(input[i] + input[j] == x) pairs++;
		}
	}
	return pairs;
}
  1. Debug the code. List all triplets in array that sums to X.
int tripletSumToX(int input[], int size, int x){
	int triplets = 0;
	for(int i=0; i<size; i++){
		for(int j=i; j<size; j++){
			for(int k=j; k<size; k++){
				if(input[i] + input[j] + input[k] == x) triplets++;
			}
		}
	}
	return triplets;
}
  1. Debug the code. Sort 0s and 1s
void sort0sand1s(int input[], int size){
	int nextZero = 0;
	for(int i=0; i<size; i++){
		if(input[nextZero] == 0){
			int temp = input[nextZero];
			input[nextZero] = input[i];
			input[i] = temp;
		}
	}
}

solution-1.txt

solution-2.txt

solution-3.txt

solution-4.txt

solution-5.txt

solution-6.txt

solution-7.txt