Converting Flowcharts into C++

  1. General tips
    1. All variables used in a flowchart must be "declared" at the top of main
    2. Our flowcharts have all been working with integers, so use the data type int in your programs
      int x, y;
      
    3. C++ comparison/relational operators

      C++ Meaning
      < less than
      <= less than or equal to
      > greater than
      >= greater than or equal to
      == equals
      != not equals
    4. To calculate the remainder of X / Y, use the mod operator (%)
      // r is the remainder of x / y
      r = x % y;
      
      cout << 5 % 2;  // 1
      cout << 2 % 5;  // 2
      
  2. if-then-else
    if-then-else structure
    if (a < 10)
    {
    	b = 2;
    }
    else
    {
    	b = 10;
    }
    
  3. if-then
    if-then structure
    if (a < 10)
    {
    	b = 2;
    }
    
    1. The "yes" response must go to the process, and "no" must skip it
  4. Pre-test loop
    pre-test structure
    c = 1;
    while (c <= 5)
    {
    	cout << c;
    	c = c + 1;
    }
    
    1. The "yes" response must go into the loop, and "no" must leave it
  5. Post-test loop
    post-test structure
    c = 1;
    do
    {
    	cout << c;
    	c = c + 1;
    } while (c <= 5);
    
    1. The "yes" response must go into the loop, and "no" must leave it
    2. Don't forget the semicolon!
  6. Asking the "opposite" question
    Example if-then structure
    if (x <= y)
    {
    	cout << x;
    	x = x - 1;
    }
    
    1. Since "yes" must go to the process and "no" skip it, you must ask the opposite question to convert into C++
    2. > ↔ <=
      < ↔ >=
      == ↔ !=
  7. Practice: Perfect Number flowchart
    Perfect number flowchart Show/hide solution
    #include <iostream>
    using namespace std;
    
    void main()
    {
    	int n, t, d;
    	
    	cout << "Enter a number: ";
    	cin >> n;
    	
    	t = 0;
    	d = 1;
    	
    	while (d <= n/2)
    	{
    		if (n % d == 0)
    		{
    			t = t + d;
    		}
    		
    		d = d + 1;
    	}
    	
    	if (t == n)
    	{
    		cout << n << " is perfect.";
    	}
    	else
    	{
    		cout << n << " is NOT perfect.";
    	}
    }