In: Computer Science
Trace this code:
1)
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v);
};
Test::Test(int v) {
value = v;
}
int main() {
Test t[100];
return 0;
}
===================================================================
2)
#include <iostream>
using namespace std;
int main()
{
int i, j;
for (i = 1; i <= 3; i++)
{
//print * equal to row number
for (j = 1; j <= i; j++)
{
cout << "* ";
}
cout << "\n";
}
system("pause");
return 0;
1)
Note:- In main() the first statement should be Test t(100); not Test t[100];
If it is Test t[100] then the program will return compile time error.
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v);
};
Test::Test(int v) { // definition of Test() which is a Test class
method
value = v; // cout<<value; => it prints value 100 that is
passed from main()
}
int main() {
Test t(100);
return 0;
}
Here, In this code a class named Test is declared and an integer value and a public function Test() with parameter integer value are declared. In main() we pass a value of 100 by creating object for Test class. So the value attribute in Test class is assigned a value of 100.
2) #include <iostream>
using namespace std;
int main()
{
int i, j;
for (i = 1; i <= 3; i++){
for (j = 1; j <= i; j++){
cout << "*
";
}
cout << "\n";
}
system("pause"); // It tells the operating system to
pause program and waits until it is terminated manually.
return 0;
}
Tracing:- for i=1 => j=1 => only one * is printed and enters next line.
for i=2 => j=1,2 => two * ' s separated by space are printed and enters next line.
for i=3 => j=1,2,3 => three * ' s separated by space are printed and enters next line.
So the output will be
*
* *
* * *