0

What is a better way to trace a code variables instead of using printf all the time which makes it pain to trace loops in terminal window ?

So for example the following code


// C++ Program to print all prime factors 
// of a number using nested loop 
  
#include <bits/stdc++.h> 
using namespace std; 
  
// A function to print all prime factors of a given number n 
void primeFactors(int n) 
{ 
    // Print the number of 2s that divide n 
    while (n % 2 == 0) { 
        cout << 2; 
        n = n / 2; 
    } 
  
    // n must be odd at this point. So we can skip 
    // one element (Note i = i +2) 
    for (int i = 3; i <= sqrt(n); i = i + 2) { 
        // While i divides n, print i and divide n 
        while (n % i == 0) { 
            cout << i; 
            n = n / i; 
        } 
    } 
  
    // This condition is to handle the case when n 
    // is a prime number greater than 2 
    if (n > 2) 
        cout << n; 
} 
  
/* Driver program to test above function */
int main() 
{ 
    int n = 315; 
    primeFactors(n); 
    return 0; 
} 

I want to keep track of what's happening in each loop to the variables like:

PrimeFactors(315)
while(315%2==0) false skipped
    for loop [i = 3] 
       while(315%3==0) [false skip]
    for loop [i=5]
...
CR77BRA
  • 11
  • 2
  • 1
    Most modern IDEs provide breakpoints to debug your source one line at a time. – D-RAJ Feb 15 '21 at 19:04
  • I'm not entirely sure what you are asking, but it seeme like you want [a debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – churill Feb 15 '21 at 19:06
  • And the suggestion to use a debugger means you learn how to get it to execute a single line at a time and you examine the variables at each step and not just run your code in the debugger. – drescherjm Feb 15 '21 at 19:12
  • Debuggers also have the ability to set conditional break points to have the code stop executing on some code line when some variable has some value. After it stops you can inspect the variables and execute the code line by line to see what your algorithm is doing. – drescherjm Feb 15 '21 at 19:22
  • I have tried using the debugger of the VSCode but it says it cannot find the libraries I added externally, do I need to add them to the g++ ? – CR77BRA Feb 16 '21 at 09:22

0 Answers0