C++ Programming/Exercises/Iterations

From Wikibooks, open books for an open world
Jump to: navigation, search

Contents

[edit] Iterations

Solutions requirements

Solutions must:

  • Use only standard C++.
  • Be compilable.
  • Be in accordance to general coding practices. (no esoteric demonstrations are required)

and should:

  • Handle error situations, even if behavior is not defined. Acceptable default is simply reporting an "Error".
  • Be internally consistent in relation to the adopted coding-style.
  • Be as simple as possible on to the point (use the minimum required variables and function calls/classes and reduces convoluted I/O handling).

Please do not add solutions that are 99% similar to another that is already present, if it is an improvement just add it to the existing solution.

Note:
Revisers are not required to provide commentary on the errors only to tag the exercise as failing the requested function. Use the talk page to clarify any issues or help submitters if the issue are purely logical, report to the book text otherwise. Fixing failed attempts should be proposed as an extended exercise whenever possible.

[edit] EXERCISE 1

Write a program that asks the user to type an integer and writes "YOU WIN" if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE".

Solution

C style solution

#include <stdio.h>
 
int main()
{
    int a;
    printf("Integer: ");
    scanf("%d", &a);
    if((a > 55) && (a < 79))
    {
        printf("YOU WIN\n");
    }
    else
    {
        printf("YOU LOSE\n");
    }
    return 0;
}




#include<iostream>
using namespace std;
 
int main() 
{
   int value;
   cout << "please enter any integer : ";
   cin >> value;
   if ( (value >= 56) && (value <= 78) )
      cout << "YOU WIN" << endl;
   else
      cout << "YOU LOSE" << endl;
}


Failed solutions (correct them as an extra exercise)
#include <iostream>
using namespace std;
 
int main()
{
    int input = 0;
    cin >> input;
      if(input <= 56 || input >= 78)
 
         cout << "you Loose" << endl;
 
      else
 
    cout << "you Win" << endl;
 
    system("PAUSE");     
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)

/*
EXERCISE 1
Write a program that asks the user to type an integer and writes "YOU WIN" 
if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE".
*/
 
#include <iostream>
using namespace std;
 
void main() {
        int num;
        char again = 'y';
        while (again == 'y') {
                cout << "Please enter a number from 1 - 100: ";
                cin >> num;
                if (num >= 56 && num <= 78) {
                        cout << "Congratulations you win.\n";
                        again == 'n';
                }else {
                        cout << "You lose, try again ? [y][n]: ";
                        cin >> again;
                }
        }
        system("PAUSE");
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)

//By: William Malina
#include <iostream>
using namespace std;
int main()
{
    cout<<"Please type a random number : ";
    int num;
    cin>>num;
    if (num<=78&&num>=56)
       cout<<"You win congrats!"<<endl;
    else{
         while (num>78 || num<56){
               cout<<"You lose!!!"<<endl;
               cout<<"Try again: ";
               cin>>num;
         }
    }
    std::cin.ignore();
    cout<<"You win congrats!"<<endl;
    cout<<"Press Enter to exit...";
    std::cin.get();
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)

//Altenate Solution by Nathaniel Demandaco
#include<iostream>
using namespace std;
 
int main(){
   int bet;
   char choice;
 start:
   cout<<"enter you bet: ";
   cin>>bet;
   if ((bet>=56)&&(bet<=78)){
      cout<<"YOU WIN\n";
   }
   else
      cout<<"YOU LOSE\n";
      cout<<"Try again? [y][n]";
      cin>>choice;
      if ((choice=='y')||(choice=='Y')){
         goto start;
      }
      else
         goto end;
 end:
   return 0;
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)

#include<iostream>
using namespace std;
 
int main(){
    int input;
    cout << "enter a number through 1-100\n";
    cin>> input;
    if( input <=58 || input >=78){
        cout<< "YOU LOSE"<<endl;
        }
        else{
             cout<<"YOU WIN"<<endl;
 
             }
        cin.get();
    ~input;
 
        return main();
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)


[edit] EXERCISE 2

Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.

Solution
#include <iostream>
using namespace std;
 
int main() {
    // Input and loop defined, only adds if input is correct.
    for (short int i=8, input; i <= 23; i+=(i == input) ) {
        cout << "Enter the number " << i << ": ";
        cin >> input;
    }
 
    return(0);
}
//alternate solution by Nathaniel Demandaco
 
#include<iostream>
using namespace std;
 
int main(){
    int num;
    cout<<"Type all numbers from 8 to 23\n";
    cout<<"start now: ";
    for(int i=8;i<=23;){
        cin>>num;
        cout<<"next: ";
        if (num!=i){
           cout<<"Invalid number, next is: "<<i<<endl;
           cout<<"next: ";
        }
        else
           i++;
    }
    cout<<"Congratulations!!\n";
return 0;
}
#include<iostream.h>
#include<conio.h>
//Write a program that asks the user to type all the integers between 8 and 23 
//(both included) using a for loop.
int main()
{
  int a,b;
start: 
cout<<"\nEnter numbers from 8-23";
  cin>>b;
  if((b<8)||(b>23))
  {
  cout<<"invalid";
  goto start;
}
  else
  {
  for(a=8;a<23;a++) 
  {
   cin>>b;
   if(b>23)
   {cout<<"\nExceeds required input";
   goto start;
}
 
}}
getch();
return 0;
}
#include <iostream>
using namespace std;
 
int main()
{
    int typedInt = 0;
    cout << "Type all numbers between 8 and 23: " << endl;
    for(int i = 8; i <= 23; i++)
    {
            cin >> typedInt;
            if (typedInt != i)
            {
               cout << "You Missed the sequence the next number was " << i << endl; 
               --i;            
            }
    }    
}
/*EXERCISE 2
~asdfk
Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.
*/
 
#include <iostream>
using namespace std;
 
void main() {
        int num, next(8);
        for (; next < 25;) {
                cout << "Please enter a number: ";
                cin >> num;
                if (num == next) {
                        next++;
                }else {
                        cout << "Wrong input, actual number: " << next << endl;
                        system("pause");
                        return;
                }
        }
        cout << "Congratulations\n";
        system("pause");
}
//To the point answer, provided by the Persian Sphinx
//Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.
#include<iostream>
using namespace std;
int main(){
        int x, i;
                for(i=8;i<=23;i++){
                        cout<<"Type in the integer '";
                        cout<<i;
                        cout<<"'"<<endl;
                        cin>>x;
        }
                return 0;
}

Alternate solution

#include <iostream>
 
using std::endl;
using std::cout;
using std::cin;
 
int main()
{
        int i=0;
        int askNum =0;
 
        for(int i=8; i <= 23 ; i++)
        {
goUp:
                cout << endl;
                cout << "Type the any Integer between 8 to 23 to proceed ; Current Iteration :" << i << endl;
                cin >> askNum;
 
                if(8 <= askNum && 23 >= askNum)
                {
                        cout << "Typed Number : " << askNum << endl; 
                }else{
                        cout << "You typed a wrong number repeat again" << endl;
                        goto goUp;
                }
 
        }
 
 
        cin >> i;
        return 0;
}

Solution in C

#include <stdio.h>
 
#define MIN_VALUE 8
#define MAX_VALUE 23
 
int main(int argc, char *argv[])
{
  int i;
  int value;
 
 start:
 
  printf("Please input all the numbers from %d to %d (%d and %d included)\n",
         MIN_VALUE, MAX_VALUE, MIN_VALUE, MAX_VALUE);
 
  for(i = MIN_VALUE; (i >= MIN_VALUE) && (i <= MAX_VALUE); i++){
    scanf("%d", &value);
    if(value != i){
      printf("The number was %d... You failed!\n", i);
      goto start;
    }
  }
 
  printf("Congratulations!\n");
 
  return 0;
}


Failed solutions (correct them as an extra exercise)
#include <iostream>
using namespace std;
 
int main()
{
  int a = 8;
  int number;
  cout << "Enter all the numbers from 8 - 23.\n";
  for(; a < 24;)
  {
    cin >> number; 
    if(number == a)
    {
      a++; 
      cout << "Next number:\n";
    }
    else
      cout << "?";
  }
   return 0;
}

This program fails to comply fully with the requirements. (please correct this as an extra exercise)

/*EXERCISE 2
Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop. */
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
 
int main(){
 
        cout << "Insert numbers from 8 to 23, both included.\n";
        for (int i = 8; i <= 23; ++i){
                string suffix;
                if (i == 8)
                        suffix.assign("st");
                else if (i == 9)
                        suffix.assign("nd");
                else if (i == 10)
                        suffix.assign("rd");
                else
                        suffix.assign("th");
 
                cout << "Insert the " << i - 7 << suffix << " number.\n";
                int inp;
                cin >> inp;
                if (inp != i){
                        do {
                                cout << "Wrong answer, you must enter: " << i << "\n";
                                cin >> inp;
                        } while (inp != i);
                }else{}
        }
        cout << "You did it!\n";
        system("pause");
}


[edit] EXERCISE 3

Same exercise but you must use a while.

Solution
#include <iostream>
using namespace std;
 
int main() {
    short int input, i(8); // Input and loop variables.
 
    while (i <= 23) {
        cout << "Enter the number " << i << ": ";
        cin >> input;
        i += (input == i); // Only add to the loop if input is correct
    }
 
    return(0);
}

A solution that uses input from the user could be

#include<iostream>
#include<conio.h>
 
//Write a program that asks the user to type all the integers between 8 and 23 (both included) using a while loop.@@@ By Hamid N
using namespace std;
 
void main()
{
        unsigned int num[30];
        int i=8;
 
 
        cout<<" dear user type every integer between 8 and 23"<<endl<<"start now :"<<endl;
        cin>>num[8];
        do{
 
                if(num[i]!=8 && num[i]!=i)
                {
                        cout<<"\n\n\n the enteger must begin from 8 and accending !  ERROR !";
                        break;
                }
                cout<<"\n\n you entered :"<<num[i];
                cout<<"\n\n\n\n next :";
                i++;
                cin>>num[i];
 
        }while(num[i]>=8 && num[i]<=23);
        cout<<"\n\n\n\nPress any key to exit .. .. ..";
        getch();
}
}

Alternate solution

//alternate solution by Nathaniel Demandaco
 
#include<iostream>
using namespace std;
 
int main(){
    int num, i=8;
    cout<<"Type all numbers from 8 to 23\n";
    cout<<"start now: ";
    while (i<=23){
        cin>>num;
        cout<<"next: ";
        if (num!=i){
           cout<<"Invalid number, next is: "<<i<<endl;
           cout<<"next: ";
        }
        else
           i++;
    }
    cout<<"Congratulations!!\n";
return 0;
}
#include<iostream.h>
#include<conio.h>
//Write a program that asks the user to type all the integers between 8 and 23 
//(both included) using while.
int main()
{
    int a,b;
start: 
cout<<"\nEnter numbers from 8-23";
  cin>>b;
  while(b>=8&&b<=23)
  {
  cout<<b;
}
getch();
return 0;
}
#include <iostream>
using namespace std;
 
int main()
{
    int typedInt = 0;
    int i = 8;
    cout << "Enter the numbers between 8 and 23: " << endl;
    while(i <= 23)
    {
       cin >> typedInt;
       if(typedInt != i)
       {
          cout << "You missed a number in the sequence " << i << endl;            
       }
       else
       {
          i++;
       }
    }    
}
/*EXERCISE 3
~asdfk
Write a program that asks the user to type all the integers between 8 and 23 (both included) using a "while" loop.
*/
 
#include <iostream>
using namespace std;
 
void main() {
        int num, next(8);
        while (next < 25) {
                cout << "Please enter a number: ";
                cin >> num;
                if (num == next) {
                        next++;
                }else {
                        cout << "Wrong input, actual number: " << next << endl;
                        system("pause");
                        return;
                }
        }
        cout << "Congratulations\n";
        system("pause");
}


[edit] EXERCISE 4

Write a program that asks the user to type 10 integers and writes the sum of these integers.

Solution
#include <iostream>
 
using namespace std;
 
int main()
{
    int sum=0;
    int temp=0;
 
    cout << "Enter 10 integers and i will write the sum of them.\n";
 
    for (int loop=1; loop<=10; loop++)
    {
        cout << "Integer #" << loop << ": ";
        cin >> temp;
        sum += temp;
    }
 
    cout << "The sum of all the integers entered is " << sum << ".";
}
/* A program to sum 10 integers using a loop */
 
#include <iostream>
using namespace std;
 
int main()
{
    //Define variables
    int i = 1;              //Counter
    int n = 0;              //Sum
    int temp;               //Input store
 
    cout << "This program sums ten user entered integers\n\n";
 
    for (i = 1 ; i <= 10 ; i++) {
        cout << "Type integer " << i << ": ";
        cin >> temp;
        n = n + temp;
    }
 
    cout << "\nThe sum of the integers is: " << n << endl;
 
    return 0;
}
//alternate solution by Nathaniel Demandaco
 
#include<iostream>
using namespace std;
 
int main(){
    int input,temp=0;
    cout<<"this program will add ten numbers you input.\n";
    for(int i=1;i<=10;i++){
        cout<<i<<": ";
        cin>>input;
        temp=temp+input;
    }
    cout<<"the sum of 10 numbers is: "<<temp<<endl;
    return 0;
}
#include<iostream>
using namespace std;
 
int main()
{
int i,s=0,x;
 
for(i=0;i<10;i++)
        {
        cout<<"Type an integer: ";cin>>x;
        s=s+x;
        }
 
cout<<"The sum is : "<<s<<endl;
 
return 0;
}

The solution in C.

#include <stdio.h>
 
int main()
{
        int i, num, sum = 0;
 
        for(i = 0; i<10; i++)
        {
                printf("Integer: ");
                scanf("%d", &num);
                sum += num;
        }
 
        printf("The sum is %d\n", sum);
        return 0;
}

A possible solution using an array.

#include <iostream>
using namespace std;
 
int main()
{
        int numbers[10], total=0;
        cout << "Please enter 10 integers. " << endl;
        for ( int n=0,c=1; n<10; n++ ) {
                cout << c << ". ";
                cin >> numbers[n];
                c++;
                total+=numbers[n];
        }
        cout << endl << "Total = " << total;
        return 0;
}
#include <iostream>
using namespace std;
 
int main()
{
      int countingSum = 0;
      int currentNum = 0;
      cout << "Type any 10 numbers and ill add them up for you..." << endl;
      for(int i = 0; i < 10; i++)
      {
              cin >> currentNum;
              countingSum += currentNum;              
      }
      cout << "Total: " << countingSum << endl;
      system("pause");
}
/*EXERCISE 4
Write a program that asks the user to type 10 integers and writes the sum of these integers.
*/
 
#include <iostream>
using namespace std;
 
void main() {
        int num, sum(0);
        for (int i = 1; i < 11; i++) {
        cout << "Input number " << i << ": ";
        cin >> num;
        sum += num;
        }
        cout << "Sum of all your ten numbers are: " << sum << endl;
        system("pause");
}


[edit] EXERCISE 5

Write a program that asks the user to type 10 integers and writes the smallest value.

Solution
#include<iostream>
using namespace std;
 
int main()
{
 
int i,ppt,x;
 
for(i=0;i<10;i++)
        {
        cout<<"Type an integer: ";
        cin>>x;
        if(i==0)
           ppt=x;
        else 
        if(x<ppt)
           ppt=x;
        }
 
cout<<"The lesser value is: "<<ppt<<endl;
 
return 0;
}
/*Solution #2 */
 
#include <iostream>
#include <algorithm>
#include <vector>
 
using std::cin;
using std::cout;
using std::vector;
 
int main()
 
{
    double input;
    vector <double> vec;
    cout << "Enter 10 separate integers:\n";
 
    for ( int i = 0; i < 10; ++i )
 
    {
        cin >> input;
        vec.push_back(input);
    }
 
    sort(vec.begin(),vec.end());
 
    cout << "Smallest value is " << vec[0];
 
}
/*EXERCISE 5
Write a program that asks the user to type 10 integers and writes the smallest value.
*/
 
// This program will get 10 numbers from user and will determine the lowest number
#include<iostream>
#include<conio.h>
 
using namespace std;
 
void main()
{
        int num[10];
        int i=0,small=0;
 
                cout<<" please enter 10 numbers as random , this program returns the smallest one ";
                cout<<"\n\n start now :";
 
                cout<<"\n\nEnter the number "<<i+1<<" of your 10 numbers ";
                cin>>num[0];
                small=num[0];
 
                for( i=1;i<10;i++)
                {
                        cout<<"\n\nEnter the number "<<i+1<<" of your 10 numbers ";
                        cin>>num[i];
                        if(num[i]<small)
                        { 
                                small=num[i];
                        }
                }
                cout<<"\n\nThe smallest number is :"<<small;
                getch();
}
/*EXERCISE 5
Write a program that asks the user to type 10 integers and writes the smallest value.
*/
 
#include <iostream>
 
using namespace std;
 
int main()
{
    int iNumber = 0;
    int iSmallest = 2147483647;
 
    for (short i=1; i<=10; i++)
    {
        cout << "Enter number " << i << ": ";
        cin >> iNumber;
        if (iNumber < iSmallest)
            iSmallest = iNumber;
 
    }
    cout << "The smallest number is: " << iSmallest;
 
    return 0;
}

Solution in C

#include <stdio.h>
 
#define MAX_VALUES 10
 
int main(int argc, char *argv[])
{
  int values[MAX_VALUES];
  int i, min;
 
  printf("Please input 10 integers...\n");
 
  for(i = 0; i < MAX_VALUES; i++){
    scanf("%d", &values[i]);
  }
 
  min = values[0];
 
  for(i = 0; i < MAX_VALUES; i++){
    if(values[i] < min)
      min = values[i];
  }
 
  printf("Min is %d\n", min);
 
  return 0;
}


[edit] EXERCISE 6

Write a program that asks the user to type an integer N and computes the sum of the cubes from 53 to N3.


Solution

Solution #1

#include<iostream.h>
void main()
{
        int n=0,sum=0,cube=1,j,i;
 
        cout<<"Enter no. = ";
        cin>>n;
 
        for(i=5;i<=n;i++)
        {
                for(j=1;j<=3;j++)
                {
                        cube=cube*i;
 
                }
                sum=sum+cube;
                cube=1;
        }
 
        cout<<"Sum of cubes from 5 to "<<n<<" = "<<sum<<endl;
}

Solution #2

#include<iostream>
using namespace std;
int main()
{
int N,s=0,i;
 
cout<<"Type the value of N : ";cin>>N;
 
for(  i=5 ;  i<=N ; i++  )
                s=s+i*i*i;
 
cout<<"The sum is : "<<s<<endl;
return 0;
}

Solution #3 Here is an example that include numbers greater than 5

#include <iostream>
using namespace std;
int main()
{
  int num, sum = 0;
  cout << "Enter a number from 1-10: "; cin >> num;
 
  if (num < 5)
  {
    for(; num < 5; num++)
      sum =sum + num * num * num;
  }
  else if (num > 5)
  {
    for(; num > 5; num--)
      sum = sum + num * num * num;
  }
  cout << sum + 125 << endl;
  return 0;
}

Solution #4

//another example by using math.h library and pow() function
#include <iostream>
#include <math.h>
 
using std::endl;
using std::cout;
using std::cin;
 
 
int main()
{
        double x(0.0) , y(0.0);
        y = pow(5.0,3.0);
cout << y << endl;
        for(int i=0 ; i<10 ; i++)
        {
cout << "type any value to proceed.\n";
cin >> x;
y += pow(x,3.0);
cout << y << endl;
        }
cout << "the final answer is the : " << y << endl;
        system("pause");
return 0;
}

Solution #5

/*
EXCERCISE 6
Write a program that asks the user to type an integer N 
and computes the sum of the cubes for all integer numbers from 53 to N3.
*/
 
#include <iostream>
#include<conio.h>
 
using namespace std;
 
void main() {
        int N, i(5), result(0);
        cout << "Number please: ";
        cin >> N;
        if (N > i) {
                for (; i <= N ; i++) {
                        result += i*i*i;
                }
        } else if (N < i) {
                for (; i >= N ; i--) {
                        result += i*i*i;
                }
        } else {
                result = 125;
        }
        cout << "Result: " << result << endl << "Press any key to exit...";
        getch();
}

Solution #6

// computes the sum of the cubes from 5^3 to N^3 ; N is input from user;
 
#include <iostream>
 
using namespace std;
 
const int S=5; // series start or end at 5
int N, result=0;
 
void case1();
void case2();
void case3();
 
int main()
{
 
        // get val of N from user
        cout<<endl<<"Enter an Interger : ";
        cin>>N;
 
        // three different cases can occur such as :: N>5 or N<5 or N=5
        if(N>S)
                case1();
        else if(N<S)
                case2();
        else if(N=S)
                case3();     
}
 
void case1()
{
        // N>5
        for(int i=S; i<=N; i++)
                result += (i*i*i);
 
        for(int i=S; i<=N; i++) //to print result with series
                cout<<"("<<i<<"^3)+";
 
        cout<<"\b"<<" = "<<result; // "\b" deletes the last "+" from the above loop
}
 
void case2()
{
        //N<5;
        for(int i=N; i<=S; i++)
                result += (i*i*i);
 
        for(int i=N; i<=S; i++) //to print result with series
                cout<<"("<<i<<"^3)+";
 
        cout<<"\b"<<" = "<<result; // "\b" deletes the last "+" from the above loop
}
 
void case3()
{
        //N=5;
        result = N*N*N;
 
        cout<<"(5^3) = "<<result;
}

Solution #7

//This program will get a number N greater than 5 from user and will calculate the sum of cubes from 5^3 to N^3
 
#include <iostream.h>
#include <conio.h>
 
main()
{
          int sum, N, counter;
          sum = 0;
          cout << "This program will get a number \"N\" greater than 5 from user and will calculate\nthe sum of cubes from 5^3 to N^3.";
          cout << "\n\nPlease enter any number greater than 5 : ";
          cin >> N;
          if(N >= 5)
          {
                   for(counter = 5; counter <= N; counter++)
                   {
                                  sum = sum + (counter * counter * counter);
                   }
                   cout << "\n\nSum of cubes from 5^3 to N^3 is " << sum << ".";
          }
          else
          cout << "\n\nInvalid input! Input must be greater than 5.";
getch();
}

Solution #8

#include <iostream>
 
using namespace std;
 
int cube( int n ) //cube(n): returns the cube of n
{
        return n * n * n;
}
 
int cf5( int n ) //cf5(n): returns the sum of cubes from 5 to n
{
        int sum = 0;
 
        for( int i = n; i >= 5; --i )
        {
                sum += cube(i);
 
                if( i == 5 )
                        break;
        }
 
        return sum;
}
 
int main()
{
        int n;
 
        for(; cin >> n; )
        {
                if( n < 5 )
                        cout << "n must be >= 5" << endl;
                else
                        cout << "The sum of cubes from 5 to " << n << ": " << cf5(n) << endl;
        }
 
        return 0;
}

Solution in C

/* A program that asks the user to type an integer n and computes the sum of the cubes from 5^3 to N^3 in C */
#include <stdio.h>
 
int main (void) {
        int n; // Number input by user. 
        int x = 5;
        int total = 0;
 
        printf("Input a number: "); 
        scanf("%i", &n); // The user inputs an integer, note, it can be greater or less than 5.
 
        /**** We add the if-statement here because we have three possibilities for the input: the integer could be greater than 5, less than 5 or equals 5.
        And we will deal with each case separately.
 
        Note we can replace > with >= and we wouldn't need the last "else" statement */
        if (n > x) {               
                printf("Total sum of the cubes from %i^3 to 5^3 = ", n);
                while (n >= x) {
                        total += n*n*n;
                        n -= 1;      
                }
                printf("%i\n", total);
        }
 
        else if (n < x) {
                printf("Total sum of the cubes from 5^3 to %i^3 = ", n);
                while (n <= x) {
                        total += n*n*n;
                        n += 1;
                }
                printf("%i\n", total); 
        }
        else {
                total = 125;
                printf("Cube of 5 = %i\n", total);
        }
}

Solution #9

// by J0nDaFr3aK
 
#include <iostream>
using namespace std;
 
int sumOfCubes(int n) {
    int sum = 0, i;
    for (i = 5; i <= n; i++) {
        sum += i * i * i;
    }
 
    return sum;
}
 
int main()
{
    int n;
    do {
        cout << "enter number ( >= 5 ): ";
        cin >> n;
    }while (n < 5);
 
    cout << "the sum is " << sumOfCubes(n);
 
    return 0;
}


[edit] EXERCISE 7

Write a program that asks the user to type an integer N and compute u(N) defined with :
u(0)=3
u(n+1)=3*u(n)+4

Solution
//[begin]
#include <iostream>
 
using namespace std;
int u(int n){
        if(n==0){
            return 3;
        }
        return 3 * u(n-1) + 4;
}
int main() {
        int input;
 
        while (input!=-1)
        {
                cout << "Enter an integer or -1 to Exit:";
                cin >> input;
                cout << "U("<< input <<")=" << u(input) <<" \n";
        }
        return 0;
}
// [end]
 
 
 
#include <iostream>
 
using namespace std;
 
 
int u(int n, int i=0, int sum = 3){
 
        if (n==i || n==0)
        {
                return sum;
        }
        sum = 3 * sum + 4;
        i++;
        u(n,i,sum);
 
}
int main() {
        int input;
 
        while (input!=-1)
        {
                cout << "Enter an integer or -1 to Exit:";
                cin >> input;
                cout << "U("<< input <<")=" << u(input) <<" \n";
        }
        return 0;
}
 
//A not so good solution
 
#include<iostream>
using namespace std;
 
int n,output;
 
//function u(x)
int u(int n)
{
    int ans,i;
ans =3;
 for(i=1;i<=n;i++)
 {
 ans = 3*ans+4;
                  }
 return ans;
 
}
 
int main()
{
cin>>n;
cin.ignore();
cout<<u(n);
cin.get();
}
 
 
//Using Recursive function
//By Sampad Mohapatra
 
#include<iostream>
using namespace std;
 
 
int main()
{
  int func(int n);
  int x;
  cout<<"\n Enter a number: ";
  cin>>x;
  int y=func(x);
  cout<<endl<<y;
  return 0;
}
int func(int a)
      {
         int k=a;
         if (a==0)
            return 3;
         else
            return 3*func(--a)+4;
      }

Solution #2

// by J0nDaFr3aK
 
#include <iostream>
using namespace std;
 
int u(int n);
 
int main()
{
    int input;
 
    cout << "enter a value: ";
    cin >> input;
 
    cout << "Final result is " << u(input) << " !\n";
 
    return 0;
}
 
int u(int n) {
    if (n == 0)
       return 3;
    else return (3 * u(n - 1) + 4);
}


[edit] EXERCISE 8

Write a program that asks the user to type an integer N and compute u(N) defined with :
u(0)=1
u(1)=1
u(n+1)=u(n)+u(n-1)

Solution

Solution #1

#include<iostream>
using namespace std;
 
int main()
{
int i,u=1,v=1,w,N;
 
cout<<"Type the value of N : ";cin>>N;
 
w=1;
 
for(i=2;i<=N;i++)
        {
        w=u+v;
        u=v;
        v=w;
        }
 
cout<<"u("<<N<<")="<<w<<endl;
 
return 0;
}

Solution #2

#include <iostream>
 
using namespace std;
 
extern int u(int);
 
int u(int N)
{
    if(N==0) return 1;
    else
    {
        if(N==1) return 1;
        else return u(N-1)+u(N-2);
    }
}
 
int main()
{
    int n;
 
    cout << "Insert N: "; cin >> n;
    cout << "Result: " << u(n) << endl;
 
    system("PAUSE");
    return 0;
}

Solution #3

//not so good solution
 
#include<iostream>
using namespace std;
 
int n;
 
int u(int n)
{
int fibo[n+1];
int i,final;
final=1;
fibo[0]=1;
fibo[1]=1;
for(i=2;i<=n;i++)
{
fibo[i]=fibo[i-1]+fibo[i-2];
final=fibo[i];
                 }
return final;
}
 
int main()
{
    cin>>n;
    cin.ignore();
    cout<<u(n);
    cin.get();
}

Solution #4

//Created By Caveman1337
//Solves for:
//u(0)=1, u(1)=1
//u(n+1)=u(n)+u(n-1)
 
#include <iostream>
using namespace std;
 
int uForm(int n)
{
        int newN=1;
 
        if (n==0||n==1)
                return 1;
 
        else if (n<0) //Fills in equation if negative numbers used to prevent crashing
                return 0;
 
        else
        {
                newN= uForm(n-1) + uForm(n-2);
                return newN;
        }
}
 
int main() 
{
        int input;
        int value;
        cout << "Enter an integer and I will conduct magic on it" << endl;
        cin >> input;
 
        value= uForm(input);
 
        cout << "Your new number is " << value << endl;
 
        system("pause");
        return 0;
}


[edit] EXERCISE 9

Write a program that asks the user to type an integer between 0 and 20 (both included) and writes N+17. If someone types a wrong value, the program writes ERROR and he must type another value.

Solution
#include<iostream>
using namespace std;
 
int main()
{
int N;
bool ok;
 
do
    {
    cout<<"Type the value of N between 0 et 20 :";cin>>N;
    ok= N<=20 && N>=0;
    if(!ok)cout<<"ERROR"<<endl;
    }while(!ok);
 
N=N+17;
cout<<"The final value is : "<<N<<endl;
 
return 0;
}

The solution in C.

#include <stdio.h>
 
int main()
{
        int N;
 
        do
        {
                printf("Integer between 0 and 20: ");
                scanf("%d", &N);
                if((N < 0) || (N > 20))
                        printf("ERROR\n");
        } while((N < 0) || (N > 20));
 
        printf("The final value is %d\n", N+17);
        return 0;
}
#include <iostream>
using namespace std;
 
int main()
{
    int userIn;
    cout << "Enter a number between 0 and 20: " << endl;
    cin >> userIn;
    while(!((userIn >= 0) && (userIn <= 20)))
    {
       cout << "Wrong Input!" << endl;
       cin >> userIn;                   
    }
    cout << "N+17 = " << (userIn + 17) << endl;
    system("pause"); 
}
/*
EXERCISE 9
Write a program that asks the user to type an integer between 0 and 20 
(both included) and writes N+17. If someone types a wrong value, 
the program writes ERROR and he must type another value.
*/
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int num;
entry:
        cout << "Please enter a number: ";
        cin >> num;
        while (num < 8 || num > 20) {
                cout << "Error\n";
                goto entry;
        }
        cout << "N+17";
        getch();
}
//Created by Caveman1337
//Asks for an integer between 0 and 20 (both included) and returns that number + 17
 
#include <iostream>
using namespace std;
 
int main() 
{
        int input;
        int newValue;
        do
        {
                cout << "Please enter a number between 0 and 20 (both included)" << endl;
                cin >> input;
                if (input>=0&&input<=20)
                {
                        newValue=input+17;
                        cout << "Your number plus 17 is " << newValue << endl;
                }
                else
                        cout << "ERROR" << endl;
 
        } while (input<0||input>20);
        system("pause");
        return 0;
}
// by J0nDaFr3aK
#include <iostream>
using namespace std;
 
void error() {
     cout << "\nERROR! Number out of range!\n\n";
}
 
int main()
{
    int n;
 
    do {
        cout << "Enter a value (between 0 and 20 both included): ";
        cin >> n;
 
        if (n < 0 || n > 20)
           error();
    } while (n < 0 || n > 20);
 
    cout << "New number is " << n + 17 << " ! " << endl;
 
    return 0;
}


[edit] EXERCISE 10

Write a program that is able to compute some operations on an integer. The program writes the value of the integer and writes the following menu :

1. Add 1
2. Multiply by 2
3. Subtract 4
4. Quit

The programs ask the user to type a value between 1 and 4. If the user types a value from 1 to 3 the operation is computed, the integer is written and the menu is displayed again. If the user types 4, the program quits.

Solution
#include <iostream>
 
using namespace std;
 
int main()
{
        int n, op;
        bool quit = false;
 
        while( !quit && (cin >> n) ) //get input if 'quit' is false
        {
                cout << "What do you want to do with " << n << '?' << endl
                         << "1. Add 1" << endl
                         << "2. Multiply by 2" << endl
                         << "3. Subtract 4" << endl
                         << "4. Quit" << endl;
                cin >> op;
 
                switch(op)
                {
                        case 1:
                                cout << n + 1 << endl;
                        break;
                        case 2:
                                cout << n * 2 << endl;
                        break;
                        case 3:
                                cout << n - 4 << endl;
                        break;
                        case 4:
                                quit = true;
                        break;
                        default:
                                cout << "Unknown operation!" << endl;
                        break;
                }
        }
 
        return 0;
}
#include<iostream>
using namespace std;
 
int main()
{
int x=0,choice;
 
do
    {
    cout<<"The value of x is "<<x<<endl;
    cout<<"1 : Add 1"<<endl;
    cout<<"2 : Multiply by 2"<<endl;
    cout<<"3 : Subtract 4"<<endl;
    cout<<"4 : Quit"<<endl;
    cout<<"Your choice : ";cin>>choice;
 
    switch(choice)
        {
        case 1 : x++;break;
        case 2: x=x*2; break;
        case 3: x=x-4;break;
        }
}while(choice!=4);
 
cout<<"The final value of x is : "<<x<<endl;
 
return 0;
}

Alternative Solution

#include<iostream>
using namespace std;
 
int main()
{
    int number, processNumber;
 
    cout<<"Enter a number: ";
    cin>>number;
 
    cout<<"What would you like to do to your number? \n";
    cout<<" 1. Add 1 \n 2. Multiply by 2 \n 3. Subtract 4 \n 4. Quit \n \n";
    cin>>processNumber;
 
    switch (processNumber)
    {
    case 1: cout<<"You chose to add: " << number + 1 <<endl;
    break;
    case 2: cout<<"You chose to multiply: " << number*2 <<endl;
    break;
    case 3: cout<<"You chose to subtract: " << number-4 <<endl;
    break;
    case 4: exit(1);
    break;
    }
 
 
 
    system("PAUSE");
    return 0;
 
}

Another solution

#include <iostream>
using namespace std;
 
int main ()
{
     cout<<"Enter an integer: ";
int N, n;
cin>>N;
for(n=0; n>=0; n++)
{
cout<<"\n";
cout<<"Now please choose from the following:\n";
cout<<"1. Add 1 \n";
cout<<"2. Multiply by 2 \n";
cout<<"3. Subtract 4 \n";
cout<<"4. Quit \n\n";
cout<<"Selection? ";
 
int selection;
cin>>selection;
 
if (selection==1)
{
N=N+1;
cout<<"\nThe current value is: "<<N<<"\n";
}
 
else if (selection==2)
{
N=2*N;
cout<<"\nThe current value is:: "<<N<<"\n";
}
 
else if (selection==3)
{
N=N-4;
cout<<"\nThe current value is:: "<<N<<"\n";
}
 
else if (selection==4)
{n=-5;
cout<<"Goodbye";
}
else
cout<<"\nPlease enter a valid selection\n";
}
 
return 0;
}

Another solution

// Solution
#include <iostream>
using namespace std;
 
int main ()
{
    int a, b=5;
    cout << "The number is 5" << endl;
    cout << "1. Add 1" << endl << "2. Multiply by 2" << endl << "3. Subtract 4" << endl << "4. Quit" << endl;
    cin >> a;
    if (a==1){ 
       b=b+1;
       cout << "The result is " << b; 
       }
    else if (a==2) {
       b=b*2;
       cout << "The result is " << b;
       }
    else if (a==3) {
       b=b-4;
       cout << "The result is " << b; }
    else if (a==4) {
       b=5
       return 0; }
}

Another solution:

#include <iostream>
using namespace std;
int main()
{
        int n,i=0,b=0;
        cout << "Input number n: "; cin>>n;
        while (i!=4) 
        {
        cout   << "1. "<<n<< " + 1\n"
                << "2. "<<n<< " * 2\n"
                << "3. "<<n<< " - 4\n"
                << "4. Quit\n\n"
                << "Your option is:";
        cin >> i;
        switch (i)
                {
                case 1 : b=n+1;break;
                case 2 : b=n*2;break;
                case 3 : b=n-4;break;
                }
        if (i!= 4)
                {
                cout << "result: " << b<<endl;
                system("pause");
                system("cls");
                }
 
        }
                return 0;
}
#include <iostream>
using namespace std;
 
int addone(int toAdd)
{
   toAdd = toAdd + 1;
   return toAdd;
}
 
int multiplyByTwo(int toMultiply)
{
    toMultiply = toMultiply * 2;
    return toMultiply;    
}
 
int subtractFour(int toSubtract)
{
    toSubtract = toSubtract - 4;
    return toSubtract;    
}
 
int main()
{
        int numberToOperateOn = 0;
        int selectedOption = 0;
        cout << "Enter a number to operate on: " << endl;
        cin >> numberToOperateOn;
        while(selectedOption != 4)
        {
            selectedOption = 0;
            cout << "1. Add By 1" << endl << "2. Multiply By 2" << endl;
            cout << "3. Subtract By 4" << endl << "4. Quit" << endl;
            cin >> selectedOption;
            if(selectedOption == 1){numberToOperateOn = addone(numberToOperateOn);}
            else if(selectedOption == 2){numberToOperateOn = multiplyByTwo(numberToOperateOn);}
            else if(selectedOption == 3){numberToOperateOn = subtractFour(numberToOperateOn);}
            cout << "Result: " << numberToOperateOn << endl;               
        }
}
/*
EXERCISE 10
Write a program that is able to compute some operations on an integer. 
The program writes the value of the integer and writes the following menu :
1. Add 1
2. Multiply by 2
3. Subtract 4
4. Quit
 
The programs ask the user to type a value between 1 and 4. 
If the user types a value from 1 to 3 the operation is computed, 
the integer is written and the menu is displayed again. If the user types 4, the program quits.
*/
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int num, choice, sum;
        char again = 'y';
        cout << "1. Add 1" << endl <<
                        "2. Multiply by 2" << endl <<
                        "3. Subtract by 4" << endl <<
                        "4. Quit\n";
        while (again == 'y' || again == 'Y') {
        cout << "Choice: ";
        cin >> choice;
        if (choice == 4)
                return;
        cout << "Please enter a number: ";
        cin >> num;
        switch (choice) {
                case 1:
                        sum = num + 1;
                        break;
                case 2:
                        sum = num * 2;
                        break;
                case 3:
                        sum = num - 4;
                        break;
                default:
                        cout << "Wrong input du ma !";
                        getch();
                        return;
        }
        cout << "Result: " << sum << ", Try again ? [Y] [N]: " << endl;
        cin >> again;
        }
}

Another solution that opens a file to show the menu

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
vector<string> readAllLines(string const& filename)
{
        vector<string> lines;
        ifstream ifs(filename.c_str());
        while (ifs)
        {
                string line;
                getline(ifs, line);
                if (ifs) lines.push_back(line);
        }
        return lines;
}
int main()
{
        int x;
        int y;
        int z;
        cout << "Please enter a number: ";
        cin >> x;
        vector<string> lines = readAllLines("Menu.txt");
        copy(lines.begin(), lines.end(), ostream_iterator<string>(cout, "\n"));
        cin >> y;
        if (y == 1)
        {
                z = x + 1;
                cout << "The answer is: " << z << endl;
        }
        else if (y == 2)
        {
                z = x * 2;
                cout << "The answer is: " << z << endl;
        }
        else if (y == 3)
        {
                z = x - 4;
                cout << "The answer is: " << z << endl;
        }
        else if (y == 4)
        {
                return 0;
        }
        else
        {
                cout << "Uhhh, that number was not listed as a choice" << endl;
        }
}

Alternate solution

#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
        int selectedOption;
        double inputVal;
        double output;
 
        cout << "*Enter a Number you wish to use" << endl << " ";
        cin >> inputVal;
 
        cout << "*Please select ONE Option from the list below" << endl;
        cout << "        1. Add 1 " << endl << "        2. Multiply by 2" << endl << " 3. Subtract 4" << endl << "    ";
        cin >> selectedOption;
 
        switch (selectedOption)
        {
        case 1 : output = inputVal + 1;
                         cout << endl << " The New value is " << output;
                         break;
        case 2 : output = inputVal * 2;
                         cout << endl << " The New value is " << output;
                         break;
        case 3 : output = inputVal - 4;
                         cout << endl << " The New value is " << output;
                         break;
        case 4 : break;
        }
 
        cout << endl << endl << "Press enter to continue . . .";
 
        cin.get();
        cin.ignore();
 
}


[edit] EXERCISE 11

Write a program that asks the user to type a positive integer. When the user types a negative value the program writes ERROR and asks for another value. When the user types 0, that means that the last value has been typed and the program must write the average of the positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'.

Solution
// EXERCISE 11 - Solution 1
 
#include<iostream>
using namespace std;
 
int main()
{
int x, s=0,nb=0;
double average;
 
do{
  cout<<"Type an integer:";cin>>x;
  if(x>0){s=s+x;nb++;}
        else if(x<0)cout<<"ERROR ";
 
  }while(x!=0);
 
if(nb==0)cout<<"NO AVERAGE"<<endl;
else {
     average=(double)s/nb;
     cout<<"The average is : "<<average<<endl;
     }
 
return 0;
}
 
 
// EXERCISE 11 - Solution 2
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int num, i(0);
        double sum(0);
                cout << "Type a number, type 0 to stop: ";
                cin >> num;
        while (num != 0) {
                cout << "Number " << i + 2 << ": ";
                cin >> num;
                if (num < 0) {
                        cout << "ERROR";
                        getch();
                        return;
                } else if (num != 0) {
                sum += num;
                i++;
                }
        }
        if (sum != 0)
                cout << "Average: " << sum / i;
        else
                cout << "No average";
        getch();
}
 
 
// EXERCISE 11 - Solution 3
 
#include <iostream>
#include <vector>
#include <cstdlib>
 
using namespace std;
 
int main()
{
    vector<int> numList;
    vector<int>::const_iterator iter;
 
    int num, total(0), average(0);
 
    do
    {
        cout << "Enter a whole number to add to list, '0' to get average.";
        cin >> num;
 
        if (num < 0)
            cout << "ERROR\n";
        else if (num > 0)
            numList.push_back(num);
        else;
    } while (num != 0);
 
    for (iter = numList.begin(); iter != numList.end(); iter++)
        total += *iter;
 
    if (total == 0)
        cout << "NO AVERAGE\n";
 
    average = (total / numList.size());
    cout << "Average is " << average;
 
    return 0;
}
 
// EXERCISE 11 - Solution 4
 
#include <iostream>
 
#define ERR_NONE      0;
 
using namespace std;
 
int main(int argc, char** argv)
{
        int iInput = 0;
        int iIndex = 0;
        int n = 0;
        cout << "Please type a list of positive integers to average. (0 When list is complete):" << endl;            
        do
        {
                cin >> iInput;
                if (iInput < 0)
                {
                        cout << "ERROR! Integer must be positive." << endl;
                }
                else if (iInput > 0)
                {
                        n+=iInput;
                        iIndex++;
                }
        }while (iInput!=0);
 
        if (iIndex > 0)
        {
                cout << "The average is " << n/iIndex << endl;
        }
 
return ERR_NONE;
}

solution #

//Niaz Ahmad
//Tuesday Julay - 19, 2011.
 
/*This program will give prompt to user to enter positive values, if user will enter any negative value program
will genrate a message and will prompt user to re-enter value. At the end average of positive numbers will be calculated
entering a 0 will be considered end of input.*/
 
#include <iostream.h>
#include <conio.h>
 
main()
{
          int input_value, sum, avg, counter;
          input_value = 0;
          sum = 0;
          avg = 0;
          counter = 1;
 
          cout << "This program will give prompt to user to enter positive values, if user will\nenter any negative value"; 
          cout << " program will genrate a message and will prompt user\nto re-enter value. At the end average of positive";
          cout << " numbers will be calculated\nentering a \"0\" will be considered end of input.\n\n";
 
          do
          {
                   cout << "\n\nPlease enter digit # " << counter << " : ";
                   cin >> input_value;
                   if(input_value > 0)
                   {
                                                  sum = sum + input_value;
                                                  counter++;
                   }
                   else if(input_value < 0)
                   {
                                cout << "Invalid input! Please re-enter.";
                                continue;
                   }
                   else if(input_value == 0 )
                   {
                                if(counter == 1)
                                {
                                                   cout << "'NO AVERAGE.'";
                                }
                                else
                                {
                                counter = counter -1;
                                avg = sum / counter;
                                cout << "\nThe average of all " << counter << " number(s) is " << avg << ".";
                                break;
                                }
                   }
          }
          while(input_value != 0);
getch();
}
// by J0nDaFr3aK
#include <iostream>
using namespace std;
 
int main()
{
    int total(0), tmp(-1), counter(0);
 
    cout << "\nYou'll be asked to enter positive numbers." << endl
         << "(Type 0 when you've entered all the values)" << endl
         << "(Negative numbers are not allowed)\n";
 
    while (tmp) {
          cout << "\nEnter value: ";
          cin >> tmp;
 
          if (tmp == 0) break;
 
          if (tmp < 0) {
             cout << "The numbers must be positive! The value will be ignored.\n";
             continue;
          }
 
          total += tmp;
          counter++;
    }
 
    if (!total) {
       cout << "\nNO AVERAGE";
       return 0;
    }
 
    cout << "\nThe average is " << total / counter;
 
    return 0;
}


[edit] EXERCISE 12

Write a program that asks the user to type an integer N and compute u(N) defined with :
u(0)=3
u(1)=2
u(n)=n*u(n-1)+(n+1)*u(n-2)+n

Solution

Solution #1

#include<iostream>
 
int main()
{
int N,u,i=0,v,w;
 
cout<<"Type the value of N : ";cin>>N;
u=3;
v=2;
if(N==0)w=u;
else if(N==1)w=v;
else for(i=2;i<=N;i++){w=i*v+(i+1)*u+i;u=v;v=w;}
 
cout<<"u("<<N<<")="<<w<<endl;
 
return 0;
}

Solution #2

// by blazzer12
 
#include <iostream>
 
using namespace std;
 
int u(int n)
{
        if(n==0)
                return 3;
        else if(n==1)
                return 2;
        else
                return n * u(n-1) + (n+1) * u(n-2) +n;
} 
 
int main()
{
        int n;
 
        cout<<"This program will compute the equation:"<<endl<<"\t\tn * u(n-1) + (n+1) * u(n-2) + n"<<endl;
        cout<<"Please Enter n = ";
 
        while(!(cin>>n))
        {
                cin.clear();
                cin.ignore(10000, '\n');
 
                cout<<"Expected Integer. Try Again."<<endl;
                cout<<"Please Enter n = ";
        }
 
        cout<<endl<<"u("<<n<<") = "<<n<<" * u("<<n<<"-1) + ("<<n<<"+1) * u("<<n<<"-2) +"<<n<<" = "<<u(n);
 
        return 0;
}


[edit] EXERCISE 13

Write a program that asks the user to type 10 integers and write the number of occurrence of the biggest value.

Solution
#include<iostream.h>
void main()
{
        int i,a=0,n=0,occur=0;
 
        cout<<"Enter 10 numers\n";
 
        for(i=1;i<=10;i++)
        {
                cin>>n;
 
                if(i==1 || n>a)
                {
                        a=n;
                        occur=0;
                }
 
                if(a==n)
                        occur++;
        }
 
        cout<<"\noccurance of biggest no. "<<a<<" = "<<occur<<endl;
}
/*
EXERCISE 13
Write a program that ask the user to type 10 integers and write the number of occurrence of the biggest value.
*/
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
    int number, biggest(0), occur(0);
    for (int i = 1; i < 11 ; i++) {
        cout << "Input " << i << ": ";
        cin >>number;
        if (number > biggest){
        biggest = number;
        occur = 0;
        }
        if (biggest == number)
        occur++;
        }
        cout << "Biggest number inputted was: " << biggest << " \nOccurance: " << occur << endl;
system("pause");
getch();
}
//Exercise 13: Example 3
 
#include <iostream>
 
#define ERR_NONE      0;
 
using namespace std;
 
int main(int argc, char** argv)
{
        int iInput = 0;
        int iIndex = 0;
        int iCount = 0;
        int n = 0;
 
        cout << "Enter 10 integers:" << endl;                
        while(iIndex < 10)
        {
                cin >> iInput;
 
                if (iInput > n)
                {
                        n=iInput;
                        iCount=1;
                }
                else if (iInput == n)
                {
                        iCount++;
                }
                iIndex++;
        };
 
        cout << "The occurance of the largest integer " << n << " is: " << iCount << endl;
 
return ERR_NONE;
}


[edit] EXERCISE 14

Write a program that asks the user to type the value of N and computes N! .

Solution
#include<iostream>
using namespace std;
 
int main()
{
int N,i,f=1;
 
cout<<"Type the value of N : ";cin>>N;
for(i=2;i<=N;i++)f=f*i;
cout<<N<<"! is "<<f<<endl;
 
return 0;
}
/*
EXERCISE 14
Write a program that asks the user to type the value of N and computes N! .
*/
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int num, sum(1);
        cout << "Enter a number: ";
        cin >> num;
        for (int i = 1; i != num ; i++) {
                sum += sum * i;
        }
                cout << num << "! = " << sum;
        getch();
}
#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
        int n;
        cout<<"Input n: ";
        cin>>n;
        cout<<"Factorial of n is :"<<factorial(n);
        return 0;
}
int factorial(int n)
{
        if(n==0)
        return 1;
        else if (n==1)
        return 1;
        else
        return n*factorial(n-1);
}
//Taken form the above example, and slightly altered.
#include <iostream>
 
#define ERR_NONE      0;
 
using namespace std;
 
int factorial(int);
 
int main(int argc, char** argv)
{
        int n;
        cout << "Input n: ";
        cin >> n;
        cout << "Factorial of n is :" << factorial(n) << endl;  
return ERR_NONE;
}
 
int factorial(int n)
{
        if(n==0)
        {
                return 1;
        }
        return n*factorial(n-1);
}


[edit] EXERCISE 15

Write a program that asks the user to type an integer N and that indicates if N is a prime number or not.

Solution

Example 1:

#include <iostream>
#include <conio.h>
using namespace std;
 
int main()
{
    bool prime(true);
 
    cout << "Enter a number: ";
    cin >> input;
 
    for (int i = 2, input; i < input/2 && prime; i++)
        prime = !(input%i == 0);
 
    cout << input << " is " << (prime ? "" : "not ") << "prime.";
    getch();
 
    return(0);
}

Example 2:

#include<iostream>
using namespace std;
 
int main()
{
int n;  
bool prime=true; 
 cout<<"Write a number: ";
 cin>>n;
 
 for (int i=n-1;i>1 && prime;i--){
  if(n%i==0) prime=false;
} 
if (n==2) prime=false;
 
 cout<<"Is prime: "<<boolalpha<<prime<<endl;
 
return 0;
}

Example 3:

#include <iostream>
using namespace std;
 
int main()
{
int N,i;
bool prime;
do{
cout << "input an integer: ";
cin >> N;
} while (N<=0);
if (N==2)
    cout << "it is a prime!" << endl;
else {
    for (i=2;i<N;i++){
        if (N%i==0){
            cout << "it is not a prime!" << endl;prime=false;break;}
        else
            {prime=true;}
        }
    if (prime==true)
    cout << "it is a prime!" << endl;}
return 0;
}

Example 4:

/*
EXERCISE 15
Write a program that asks the user to type an integer N 
and that indicates if N is a prime number or not.
*/
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int num, i;
        bool prime = true;
        cout << "Enter a number: ";
        cin >> num;
        for (i = num-1; i > 1 && prime == true; i--) {
                if (num%i == 0)
                        prime = false;
        } 
        if (prime == true)
                cout << "Prime number";
        else
                cout << "Not prime number";
        getch();
}

Example 5:

#include <iostream>
#include <cmath>
 
#define ERR_NONE      0;
 
using namespace std;
 
bool isPrime(int n);
 
int main(int argc, char** argv)
{
        int n = 0;
 
        cout << "Enter an integer: ";
        cin >> n;              
        cout << n << " is " << (isPrime(abs((float)n)) ? "" : "NOT ") << "a prime number." << endl;
 
return ERR_NONE;
}
 
bool isPrime(int n)
{
        if (n > 1)
        {
                for (int i=(n-1);i>1;i--)
                {
                        if(n%i == 0)
                        {
                                return false;
                        }
                }
        }
        return true;
}

Solution #6

// by J0nDaFr3aK
 
#include <iostream>
using namespace std;
 
bool ifPrime(int n);
 
int main()
{
    int input;
 
    cout << "Enter a value: ";
    cin >> input;
 
    if (ifPrime(input))
       cout << input << " is prime!\n";
    else
       cout << input << " is not prime!\n";
 
    return 0;
}
 
bool ifPrime(int n) {
     int i;
 
     if (n == 2) return true;
     else if (n == 0 || n == 1 || n % 2 == 0) return false;
         else
             for (i = 3; i < (n / i); i+=2) {
                 if (n % i == 0)
                    return false;
             }
     return true;
}


[edit] EXERCISE 16

Write a program that asks the user to type an integer N and that writes the number of prime numbers lesser or equal to N.

Solution
#include<iostream>
using namespace std;
 
int main()
{
int N,i,nb=0,d;
bool is_prime;
 
cout<<"Typer the value of N : ";cin>>N;
 
for(i=2;i<=N;i++)
        {
        /* test if i is prime*/
        is_prime=true;
        d=2;
        while(is_prime && d*d<=i)
                if(i%d==0)is_prime=false; else d++;
 
        if(is_prime==true)nb++;
        }
 
cout<<"The number of prime number lesser or equal to "
        <<N<<" is "<<nb<<endl;
 
return 0;
}
/* ex 16: */
Write a program that asks the user to type an integer N and that writes the number
 of prime numbers lesser or equal to N.
 
 
#include <iostream>
using namespace std;
 
int x;
 
int main () {
        cout << "Please enter a number and I will show you all prime numbers between that number and zero.\n";
        cin >> x;
        for ( int i = x; i > 1; --i) {
                if (i%2 != 0 && i%3 != 0 && i%5 != 0 && i%7!=0) 
                        cout << i << ", ";
        }
        cout << "7, 5, 3, 2, and 1 are all prime numbers between 1 and " << x << ".";
}

Example 3:

#include <iostream>
#include <cmath>
 
#define ERR_NONE      0;
 
using namespace std;
 
bool isPrime(int n);
 
int main(int argc, char** argv)
{
        int n = 0;
        int absn = 0;
        int Count = 0;
 
        cout << "Enter an integer: ";
        cin >> n;              
        absn=abs((float)n);
 
        cout << "Prime integers <= to " << n << ":" << endl;
        for (int i=1; i<=absn; i++)
        {
                if (isPrime(i) )
                {
                        if (n < 0) 
                        {
                                cout << i*-1 << endl;
                        }
                        else
                        {
                                cout << i << endl;
                        }
                        Count++;
                }         
        }
 
        cout << endl << "There are a total of " << Count << " primes." << endl; 
return ERR_NONE;
}
 
bool isPrime(int n)
{
        if (n > 1)
        {
                for (int i=(n-1);i>1;i--)
                {
                        if(n%i == 0)
                        {
                                return false;
                        }
                }
        }
        return true;
}


[edit] EXERCISE 17

Write a program that asks the user to type the value of an integer N and compute the N-st prime number.

Solution
#include<iostream>
using namespace std;
 
int main()
{
int N,i=1,nb=0,d;
bool is_prime;
 
cout<<"Type the value of N : ";cin>>N;
 
while(nb<N)
        {
        i++;
        is_prime=true;
        d=2;
        while(is_prime && d*d<=i)
                if(i%d==0)is_prime=false; else d++;
 
        if(is_prime==true)nb++;
        }
 
cout<<"Le N-st prime number is "<<i<<endl;
 
return 0;
}

[edit] EXERCISE 18

Write a program that asks the user to type the value of N and writes this picture :

N=1
*
N=2
**
*
N=3
***
**
*

and so on...

Solution
#include<iostream>
using namespace std;
 
int main()
{
int i,j,N;
 
cout<<"Type the value of N : ";cin>>N;
 
for(i=1;i<=N;i++)
        {
        for(j=1;j<=N+1-i;j++)cout<<"*";
        cout<<endl;
        } 
return 0;
}

The solution in C.

#include <stdio.h>
 
int main()
{
        int i, j, N;
 
        printf("Value of N: ");
        scanf("%d", &N);
 
        for(i = 0; i < N; i++)
        {
                for(j = 0; j < N-i; j++)
                        printf("*");
                printf("\n");
        }
        return 0;
}
/*
EXERCISE 18
Write a program that asks the user to type the value of N and writes this picture :
Example:
 
N=3
***
**
*
 
*/
 
#include <iostream>
#include <conio.h>
 
using namespace std;
 
void main() {
        int N;
        cout << "Enter a number: ";
        cin >> N;
        cout << "\nN = " << N << endl;
        for (; N >= 1; N--) {
        for (int v(N); v != 0; v--) {
                cout << "*";
                }
                cout << endl;
        }
        cout << "Done.";
        getch();
}


[edit] EXERCISE 19

Write a program that asks the user to type the value of N and display an output like the following:

N=1
*
N=2
**
 *
N=3
***
 **
  *

and so on ...

Solution

Solution #1

#include<iostream>
using namespace std;
 
int main()
{
int i,j,N;
 
cout<<"Type the value of N : ";cin>>N;
 
for(i=1; i<=N; i++)
        {
        for (j=1; j<i; j++)
            cout<<" ";
        for (j=1; j<=N+1-i; j++)
            cout<<"*";
        cout << endl;
        } 
return 0;
}

Solution #2

// by blazzer12
 
#include <iostream>
 
using namespace std;
 
int main()
{
        int N;
 
        cout<<"N = ";
 
        while(!(cin>>N))
        {
                cin.clear();
                cin.ignore(10000,'\n');
 
                cout<<"Integer Expected. Try Again."<<endl;
                cout<<"N = ";
        }
 
 
        for(int space=0, star=N;(space<N && star>0); space++, star--)
        {
                for(int spc=space;spc>0;spc--)
                {
                        cout<<" ";
                }
                for(int str=star;str>0; str--)
                {
                        cout<<"*";
                }
 
                cout<<endl;
        }
 
        return 0;
}

Solution #3

// by blazzer12
 
#include <iostream>
 
using namespace std;
 
int main()
{
        int N,spc,str;
 
        cout<<"N = ";
 
        while(!(cin>>N))
        {
                cin.clear();
                cin.ignore(10000,'\n');
 
                cout<<"Integer Expected. Try Again."<<endl;
                cout<<"N = ";
        }
 
 
        for(int space=0, star=N;(space<N && star>0); space++, star--)
        {
                spc=space;
                str=star;
 
                while(spc--)
                {
                        cout<<" ";
                }
                while(str--)
                {
                        cout<<"*";
                }
 
                cout<<endl;
        }
 
        return 0;
}

Solution #4

// blazzer12
 
#include <iostream>
 
using namespace std;
 
void generate(int space, int star)
{
        while(space--)
                cout<<" ";
 
        while(star--)
                cout<<"*";
}
 
int main()
{
        int N;
        cout<<"N = ";
        while(!(cin>>N))
        {
                cin.clear();
                cin.ignore(10000,'\n');
 
                cout<<"Integer Expected. Try Again."<<endl;
                cout<<"N = ";
        }
 
        for(int space=0, star=N; N--; space++, star--) // or the more standard: for(int space=0, star=N; N; space++, star--, N--)
        {
                generate(space, star);
                cout<<endl;
        }
        return 0;
}

Solution #5

// by blazzer12
 
#include <iostream>
 
using namespace std;
 
int main()
{
        int N;
 
        cout<<"N = ";
        cin>>N;
 
        for(int i=N; i>0; i--)
        {
                for(int space = 0; space <(N-i); space++)
                        cout<<" ";
 
                for(int star = i; star>0; star--)
                        cout<<"*";
 
                cout<<endl;
        }
        return 0;
}


[edit] EXERCISE 20

u(n) is defined with:

  • u(0) = a (a is an integer)
  • if u(n) is even then u(n+1)=u(n)/2, else u(n+1)=3*u(n)+1

Conjecture: For all value of a, there exists a value N such that u(N)=1.

a)Write a program that asks the user to type the value of an integer a and writes all the values of u(n) from n=1 to n=N.


Solution
#include<iostream>
using namespace std;
 
int main()
{
int a,n,u;
cout<<"Type the value of a : ";cin>>a;
n=0;
u=a;
 
while(u!=1)
        {
        if(u%2==0)u=u/2; else u=3*u+1;
        n++;
        cout<<"u("<<n<<")="<<u<<endl;
        }
return 0;
}


b) Write a program that asks the user to type a value M and computes the value of a from 2 and M that maximizes the value of N. This value is called A. The program must write the value of A and N.

Solution
#include<iostream>
using namespace std;
 
int main()
{
int a,n,u,M,amax,nmax;
cout<<"Type the value of M : ";cin>>M;
amax=2;
nmax=2;
 
for(a=3;a<=M;a++)
    {
    n=0;
    u=a;
    while(u!=1)
       {
       if(u%2==0)u=u/2; else u=3*u+1;
       n++;
       }
    if(n>nmax){amax=a;nmax=n;}
    }
cout<<"The value of A is :"<<amax<<endl;
cout<<"The value of N is :"<<nmax<<endl;
 
return 0;
}


[edit] EXERCISE 21

Request the user to type numbers, each time printing its triple, until the user enters -999.

Solution

Example 1:

#include <iostream>
using namespace std;
 
int main() {
    for (int input; input != -999;) {
        cout << "Enter a number (-999 to quit): ";
        cin >> input;
        if (input != -999)
            cout << "Tripled: " << input * 3 << endl;
    }
 
    return(0);
}

Example 2:

#include <iostream>
using namespace std;
 
int main() {
    int input;
 
    cout << "Enter a number (-999 to quit): ";
    cin >> input;
 
    while (input != -999) {
        cout << "Tripled: " << input * 3 << endl;
        cout << "Enter a number (-999 to quit): ";
        cin >> input;
    }
 
    return(0);
}


[edit] EXERCISE 22

Request the user to type positive numbers until either a zero or a negative is typed, and then show the user how many positives were typed in.

Solution
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int main() {
    int posCount(-1), input;
 
    do  {
        cout << "Enter a positive number (0 or less to quit): ";
        cin >> input;
        posCount++;
    } while (input > 0);
 
    cout << "Total number of positives: " << posCount;
    getch();
 
    return(0);
}


[edit] EXERCISE 23

Request the user to type positive numbers, or to stop by typing a number smaller than 1. Print the average.

Solution
#include <iostream>
 
using namespace std;
 
int main()
{
        int n, sum = 0, nums = 0;
 
        do
        {
                cout << "Enter a number (less than 1 = quit): ";
                cin >> n;
 
                if( n > 0 )
                {
                        sum += n;
                        ++nums;
                }
        } while( n > 0 );
 
        if( nums > 0 )
                cout << "The average is: " << sum / nums;
        else
                cout << "No average";
 
        cout << endl;
        return 0;
}


[edit] EXERCISE 24

Request the user to type numbers, or type 0 to stop. Show how many numbers were between 100 and 200 (both included).

Solution
#include <iostream>
#include <conio.h>
int main()
{
   int input, numberBetween(0);
    const short int minNum(100), maxNum(200);
    do {
        cout << "Enter a number (0 to quit): ";
        cin >> input;
        if (input >= minNum && input <= maxNum)
            numberBetween++;
    } while (input != 0);
 
    cout << "Numbers between " << minNum << " and " << maxNum << ": " << numberBetween;
    getch();
 
    return(0);
}


[edit] EXERCISE 25

The country A has 50M inhabitants, and its population grows 3% per year. The country B, 70M and grows 2% per year. Tell in how many years A will surpass B.

Solution
#include <iostream>
 
using namespace std;
 
int main()
{
    int countryA(50000000), countryB(70000000);
    const float aRate(1.03), bRate(1.02);
    short int years(0);
 
    cout << "With a population of " << countryA << " and a growth rate of " << aRate*100-100 << "% for country A...\n"
         << "And a population of " << countryB << " and a growth rate of " << bRate*100-100 << "% for country B...\n";
 
    while (countryA <= countryB)
    {
        countryA *= aRate;
        countryB *= bRate;
        years++;
    }
 
    cout << "It would take " << years << " years for country A to surpass country B.";
 
    return(0);
}

Alternative Simple Solution:

#include <iostream> 
using namespace std;
int main()
{
        float A=50,B=70;// no need to enter millions 50 and 70 can do the job
        int years=0;
        while (A<B)
        {
                A=A*1.03;
                B=B*1.02;
                years++;
        }
        cout<<"in "<<years<<" years A will have a greater population than B.\n";
        system("pause");
        return 0;
}

To do:
Explain the possible gotchas with floating-point giving different results to fixed-point

Alternative Solution:

#include <iostream>
 
int main()
{
        int A = 50000000;
        signed int B = 70000000;
        int i = 0;
        for (; B > A; i++) {
                A = A * 1.03;
                B = B * 1.02;
        }
        std::cout << i << " years.";
        std::cin.get();
        return 0;
}

Edit
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export