C++ is a direct descendant of C that retains almost all of C as a subset. C++ provides stronger type
checking than C and directly supports a wider range of programming styles than C. C++ is "a better C"
in the sense that it supports the styles of programming done using C with better type checking and more
notational support (without loss of efficiency). In the same sense, ANSI C is a better C than K&R C.
In addition, C++ supports data abstraction,
object-oriented programming,
and generic programming. Programs could not be expressed better in C than
in C++, such a program could not exist, because every construct in C has an obvious C++ equivalent.
However, there's still a few that exist in a few environments where the support for C++ is so weak
that there is an advantage to using C instead, but there aren't too many of those C compilers left.
C++ while loop - User enters in the number of times
Compiler (Visual Studio) showing C++ Source Code:
// - Use a while loop. User enters in the amount of times.#include<iostream>using namespace std;
int main()
{
int counter = 0; // Initialize counter to 0.int numTimes = 0; // Variable for user to enter the amount of times.
cout << "How many times do you want to see Einstein?: ";
cin >> numTimes; // This is how many times the loop repeats.
cout << "\n";
while (counter < numTimes) // Counter is less than the users input.
{
cout << "Einstein!\n";
counter++; // Increment the counter for each loop.
}
cout << "\n";
return 0;
}
/*===============================[output]====================================
How many times do you want to see Einstein?: 6
Einstein!
Einstein!
Einstein!
Einstein!
Einstein!
Einstein!
Press any key to continue . . .
=============================================================================*/
Adding numbers and averaging them
Example C++ Source Code:
Adding numbers and averaging them C++ source code:Example