This debug exercise contains topics from both basic mathematics and pointers.

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.

void SieveOfEratosthenes(int n) 
{
    vector<bool> prime(n+1, false);
  
    for (int p = 2; p * p <= n; p++) {
            for (int i = p * p; i <= n; i += p) 
                prime[i] = true; 
        } 
    } 
  
    for (int p = 0; p <= n; p++) 
        if (prime[p]) 
            cout << p << " "; 
}
  1. Debug the code.
void fillPrimes(vector<int>& prime, int high)
{
    vector<bool> ck(high+1, true);
    for (int i = 2; (i * i) <= high; i++) {
        if (ck[i] == true) {
            for (int j = i * i; j <= sqrt(high); j = j + i) {
                ck[j] = false;
            }
        }
    }
    for (int i = 2; i * i <= high; i++) {
        if (ck[i] == true) {
            prime.push_back(i);
        }
    }
}

void segmentedSieve(int low, int high)
{
    if (low<2 and high>=2){
        low = 2;
    }
    vector<bool> prime(high-low+1, true);
    vector<int> chprime;
    fillPrimes(chprime, high);
    for (int i : chprime) {
        int lower = (low / i);
        if (lower <= 1) {
            lower = i + i;
        }
        else if (low % i) {
            lower = (lower * i) + i;
        }
        else {
            lower = (lower * i);
        }
        for (int j = lower; j <= high; j = j + i) {
            prime[j] = false;
        }
    }
   
    for (int i = low; i <= high; i++) {
        if (prime[i] == true) {
            cout << (i) << " ";
        }
    }
}
  1. Debug the code.
bool isPrime(int n)
{
    if (n == 1)
        return false;
 
    for (int i = 2; i <= n / 2; i++)
        if (n % i)
            return false;
 
    return true;
}
  1. Debug the code. In this question, if there is no error, remove the bad practices.
int main(){
	int* ptr;
	int a = 5;
	ptr = &a;
	cout << *ptr << endl;
	return 0;
}
  1. *Debug the code. You have to make value of q = 6.
#include <iostream>
using namespace std;

int main(){
    int p = 5;
    int const *q = &p;
    *q++;
    cout << p << endl;
    return 0;
}
  1. Debug the code. Output should be 100 and 104.
int a = 100;
int *p = &a;
int **q = &p;
int b = ++(**q) + 4;
cout << a << " " << b << endl;

solution-1.txt

solution-2.txt

solution-3.txt

solution-4.txt

solution-5.txt

solution-6.txt