disclaimer: i am in 8th grade in school and we are learning the ancient and dead TURBO c++ as our first programming language. I have written around 50 simpler programs so far. here is the most intresting on i am working on. i was writing a program to find sum of n natural number using classes and trying to make it 'failsafe'. i am not getting the desired result. i am getting no errors and warnings from the compiler. i am learning programming to understand logic and think like a programmer. Please do not judge me for using Turbo C++ i cannot do anything about it. I promise once i grow up then i will learn RUST.
here is my code:
#include<iostream.h>
#include<conio.h>
class summer
{
int n,s;
public:
int get();
void calc();
void show();
void define();
};
int summer::get()
{
cout<<"Enter a Natural Number: ";
cin>>n;
return n;
}
void summer::calc()
{
for(int i=1;i<=n;i++)
{
s=s+i;
}
}
void summer::show()
{
cout<<"Sum of all natural Numbers till "<<n<<" is "<<s;
}
void summer::define()
{
cout<<"\n\nA natural Number is a non decimal and non fractional number greater than 0";
}
void main()
{
clrscr();
summer obj;
int ch=obj.get();
if(ch>0)
{
obj.calc();
obj.show();
}
else
{
cout<<ch<<" is not a natural number";
obj.define();
}
getch();
}
cannot copy paste the output screen. please understand. i input 5 and get output as 7888
The problem is that the data member
shas not been initialized and you're using that uninitialized data member which leads to undefined behavior.So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Solution
Since you're using Turbo, you can solve the problem by adding a parameterized constructor that initializes both the data members
nandsto0as shown below:The output of the modified program can be seen here.
Some of the changes i made include:
nandsto0using constructor initializer list.nandsto be of typeunsigned int.1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.