Site icon TestingDocs.com

Display a table of values in C++ program

Introduction

In this post, we will see how to display a neat table of values in the C++ program. Displaying a table of data is a very common activity when performing numeric computations.

In C++ we can manipulate the I/O stream using iomanip library.

#include <iomanip>

 

C++ program

/*************************************** 
*Table of values demo C++ program.
**************************************/
#include<iostream> #include<iomanip> #include<math.h>

using namespace std; // Main method int main() { double n=1; int colWidth=15; //table header cout << setfill('*') << setw(3*colWidth) << "*" << endl; cout << setfill(' ') << fixed; cout << setw(colWidth) << "n" << setw(colWidth) << "log" << setw(colWidth) <<
"square root" << endl; cout << setfill('*') << setw(3*colWidth) << "*" << endl; cout << setfill(' ') << fixed; // create table of data while (n < 1000) { cout << setprecision(0) << setw(colWidth) << n << setprecision(4) <<
setw(colWidth)
<< log10(n) << setw(colWidth) << sqrt(n) << endl; if(n < 10) { n++; } else if ( n< 100) { n += 10; } else { n *= 10; } } cout << setfill('*') &lt;< setw(3*colWidth) << "*" << endl; return 0; }

Program Output

 

table of values c++ program

 

The loop used in the program is a while loop. while loop is a repetitive structure. The while loop is used to execute a group of statements repeatedly in the C++ program until the loop condition is true.

while (n < 1000){

}

The loop condition is n < 1000

Functions used

Each row in the table displays three values. n, the logarithm of n to base 10 and the square root of n.
n, log10(n), sqrt(n)

The functions used in the program are math library functions to compute log base 10, square root of the number. To use these function in the program we need to include the header file.

#include<math.h>

 

setw() sets the field width. setfill() sets the fill character.

Code::Blocks IDE

The IDE used in the program is Code:: Blocks. To download and install Code Blocks follow the link:

https://www.testingdocs.com/download-and-install-codeblocks/

For more information on Code Blocks IDE, visit the official website of Code blocks IDE:
http://www.codeblocks.org/

Exit mobile version