am interested in C++ and am trying to learn as much as i can but i don't know how write a function that uses a loop in C++ code.
Say for example i want to write a function that uses a loop to find the sum of the squares of all integers between 1 and n. How would the function look like in C++ code? (if possible include the function prototype, declaration and definition)
How are loops used in C++ functions?
You need to use a for loop.
The syntax is:
for ( %26lt;var%26gt; = %26lt;intial value%26gt;; %26lt;condition%26gt;; %26lt;increment / decrement expression)
{
do_some_function(%26lt;var%26gt;)
}
The commands contained within the curly brackets are executed until the condition is no longer true.
e.g to loop an integer variable from 1 to 10:
int i;
for (i=1;i%26lt;11;i++)
{
cout %26lt;%26lt; "Number: "%26lt;%26lt; i %26lt;%26lt; endl;
}
This will output :
Number: 1
Number: 2
Number: 3
Number: 4
......etc
Number: 10
Reply:you can use a for loop or an while loop. i have attached a sample code for the for loop
#include %26lt;cstdlib%26gt;
#include %26lt;iostream%26gt;
using namespace std;
int main(int argc, char *argv[])
{
int i,n;
int square, sum;
cout%26lt;%26lt;"enter the number"%26lt;%26lt;endl;
cin%26gt;%26gt;n;
for (i = 0; i %26lt;=n; i++)
{
square = i*i;
sum = sum +square;
}
cout%26lt;%26lt;"the answer is "%26lt;%26lt;sum%26lt;%26lt;endl;
system("pause");
}
you can replace for with while; for example use, while (i%26lt;=n)
but then u have to increment using i++ within the loop.
Happy Coding!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment