C++ Programming/Exercises/Iterations/Pages

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.

Exercise 1 edit

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
//Example 1
#include <iostream>

using namespace std;

int main()
{
  int input;
  bool win = false;
  
  do {
      cout << "Please enter a number: " << flush;
      cin >> input;
    
          if (56 <= input && input >= 78) {
            cout<<"You win!"<<endl;
            win = true;
          }
          else {
            cout<<"You lose!"<<endl;
          }
  } while(win == false);

  return 0;
}
//Example 2
#include <iostream>
using namespace std;

int main ()
{
    int a;
    cout<<"your Age"<<endl;
    cin>>a;
    if(a>=58 && a<=73)
        {
            cout<<"You win"<<endl;
        }
    else{
            cout<<"You lose"<<endl;
        }

    return 0;
}
//Example 3

#include<iostream>

using namespace std;

int main() {
	cout << "\t\t\t Kheang's Random Number Lotto\n\n";
	cout << "Please pick a number between 0 and 100\n";
	
int num;
cin >> num;

	if ((num <= 78) && (num >= 56)){
	cout << "Congratulations! YOU WIN!";}
    else {
    	cout << "Unfortunately YOU LOSE!";
	}
}
//Example 4
#include <iostream>

using namespace std;

int main()
{
 
    int num; 
    cout<<" enter a number between 56 and 78\n';

    (num >= 56 && num <= 78)? cout<<"you win" : cout<<"you lost";

}
//Example 5
#include<iostream>
using namespace std;
int main()
{
	int num;
	cout<<"Enter any  number"<<endl;
	cin>>num;
	if(num>=56&&num<=78)
		cout<<"YOU WIN"<<endl;
	else
		cout<<"YOU LOSE"<<endl;

	return 0;
}
#include<iostream.h>
#include<conio.h>

int n;

main()
{

cout<<"Enter an integer: ";cin>>n;

if(n>55&&n<79){cout<<"YOU WIN!";}
else{cout<<"YOU LOSE!";}

getche();
return 0;
}
//Example 6
#include <iostream>
using namespace std;

int main()
{
	int i;
	cout << "Type a number between 56 and 78: " << endl;
	cin >> i;
	if (i>=56 && i<=78)
	{
		cout << "YOU WIN" << endl;
	} 
	else 
	{			
		cout << "YOU LOSE" << endl;
	}
	return 0;
}
//Example 7
#include <iostream>

int main()
{
 int num;
 
 std::cout << "Enter a value between 56 and 78\n"; 
 std::cout << "Enter a number:  ";
 std::cin >> num;

 if(num >= 56 && num <= 78)
 {
  std::cout << "You Win!\n";
 }
 else 
 {
  std::cout << "You Lose!\n";
 }
 return 0;
}
//Example 8
#include <iostream> // std::cout, std::cin

using namespace std;

int main()
{
    // The user input
    int input;

    // Ask for a number
    cout << "Please, enter a number: ";
    // Get the user input
    cin >> input;

    // While the user is not inputting a correct number...
    while (cin.fail())
    {
        // Ask again for input
        cout << "Please, enter a valid number: ";
        // Clear the input we got before
        cin.clear();
        // Ignore the new line character
        cin.ignore(256, '\n');
        // Get the input again
        cin >> input;
    }

    // If the input is [56, 78], YOU WIN
    if (input >= 56 && input <= 78)
        cout << endl << "YOU WIN" << endl;
    else // Else YOU LOSE
        cout << endl << "YOU LOSE" << endl;

    return 0;
}
//Example 9
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
	int val;
	do {
		printf("Write a value: ");
		scanf("%i",&val);
		
		if (val <= 78 && val >=56) {
			printf("YOU WIN!\n");
			getch();
		}
		else {
			printf("YOU LOSE!");
			getch();
			system("cls");
		}
	} while(val > 78 || val < 56 );
}

}}
//Example 10

#include <iostream>

void main()
{
	int nInteger;
	std::cout << "Enter an integer: ";
	std::cin >> nInteger;

	(nInteger > 56 && nInteger < 78 ? std::cout << "YOU WIN" << std::endl : std::cout << "YOU LOSE" << std::endl);

	system("Pause");
}
//Example 11

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

#define newline cout<<'\n'

void check(void);

int main()
{
	check();//everything takes place inside check() function.
	return 0;
}

void check(void)
{
	string user_input;
	int input;
	printf("Enter an integer: ");
	getline(cin, user_input);
	stringstream(user_input) >> input;

	if (input >= 56 && input <= 78) { //checks user_input with boolean parameters.
		printf("YOU WIN!");
	}
	else
		printf("YOU LOSE!");
	newline;
}
//Example 12
#include <iostream>

int main()
{
    std::cout << "Enter an integer: __\b\b";

    int ans;
    std::cin >> ans;
    std::cout << std::endl;
    std::cout <<
    (
     56 < ans and ans < 78 ? "Win!" : "Loose!"
     );
    return 0;
}
//Example 13

#include <iostream>

int main()
{
int a = 0;

std::cout<<"Type in integer: ";
std::cin>>a;

std::cout<<std::endl;

if(a >= 56 && a <= 78)
{
	std::cout<<"YOU WIN! :>";
}

else
{
	std::cout<<"YOU LOSE :<";
}

return 0;

}
//Example 14
#include <iostream>

int inpt;

using namespace std;
int main(int argc, char** argv) 
{
	cin>>inpt;
	if(inpt>55&&inpt<79)cout<<"You win!";
	else cout<<"You Lose";
	return 0;
}


Exercise 2 edit

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

Solution


//Example 1
//considering the user already learned Arrays

#include <iostream>

using namespace std;

int main()
{
  int input, arr[16], i = 0;
  bool duplicate = false;
  
  cout << "Please enter integers between 8 and 23:  " << flush;
  
  for(;;) {
    cin >> input;
        if (input >= 8 && input <= 23) {
            for (int j = 0; j <= i; j++) {
                if (input == arr[j]) {
                    duplicate = true;
                }
            }
            
            if (duplicate) {
                cout << "Sorry the integer is already entered, try another one: " << flush;
                duplicate = false;
            }
            else {
                arr[i] = input;
                cout << "Correct, please proceed to the next integer: " << flush;
                i = i + 1;
            }
        }
        else {
            cout << "Incorrect, please enter integers between 8 and 23: " << flush;
        }
  }
  return 0;
}

//by Serenity:
//Simpler way then 999 code lines...
	int main() {
		int t_int;

		for (int i = 8; i < 23; i++) {
			std::cout << "Type numbers 8 util 23" << std::endl;
			std::cin >> t_int;
			if (t_int < i) {
				std::cout << "Invalid number" << std::endl;
			}
			else if (t_int > i && t_int > 23) {
				std::cout << "Invalid number" << std::endl;
			}
			else {
				std::cout << "Valid number" << std::endl;
			}
		}
            system("PAUSE");
	}

// Written by S.SNGWN
#include<iostream.h>
#include<conio.h>
void main(){
int n,i;
cout<<"Type all integers between 8 and 23 both included \n";
for(i=8;i<=23;i++)
cin>>n;
getch();
}
//Made by Lam P.
#include <iostream>

using namespace std;

int main()
{
	int nu;
	for(int n=8; n<=23;n++)
	{
		cin>>nu;
		 if(nu==n)
			{
				cout<<"Correct! Next number is: ";
			}
			
		else
			{
				cout<<"Wrong! Try again: ";
				n=n-1;
			}
	}
}



//Made by: Engineer Reiz Troy D. Durante
#include<iostream.h>
#include<conio.h>

int i,j,k,p,n[16];

main(){
clrscr();
for(i=8;i<25;i++){n[i-8]=i;}
for(i=0;k<16;i++){
	cout<<"The program will end once all required numbers were all given.\nEnter numbers between 8 and 23 (both inclusive): ";
	cin>>p;
	for(j=8;j<25;j++){
		if(n[j-8]==p){k++;n[j-8]=0;}
	}
        clrscr();
}
getche();
return 0;
}
/*******************************************
* Made by Pedro Casagrande, UFRGS - BRAZIL *
*******************************************/

#include <iostream>

using namespace std;

int Range(int);//just declaring the function

int main ()
{
    int num[16],i, j;
    cout << "type all integers numbers between 8 and 23 [inclusive]:\n";
    for (i = 0; i < 16; i++)
    {
        cout << i+1 <<"o number: ";
        cin >> num[i];

        //seeing if the number is out of range, if it is... u need to change it
        num[i] = Range(num[i]);
        //cout << num[i] << "\n";  //if u want to see the new number

        for(j=0; j != i; j++)
        //seeing if the number have been already typed
        {
            while(num[i]==num[j])
            // if is the same, u need to change, until it is not the same as another aready typed
            {
                cout << "u have already typed this number. Type again:\n";
                cin >> num[i];
                //seeing if the number is out of range, AGAIN
                num[i] = Range(num[i]);
                j=-1;
            }
        }
        cout << "Nice!\n"; // just to show u succeeded with the new number
    }
    cout << "\nYOU HAVE DONE IT!\n";
    return 0;
}

int Range(int a)
{
    while(!(a>=8 && a<=23))
    //test if the number is out of range
    {
        cout << "the number u'v typed are out of range. Type again:\n";
        cin >> a;
    }
    return a;
}
#include<iostream>
#include<cstdlib>

using namespace std;

/*************************************************************************************/
/*Soluiton submited by Joshua Waiswa, Makerere University Kampala, jwaiswa7@gmail.com*/
/*************************************************************************************/

int main(){
        int x,j,t;
        int z[16];

        cout <<"Enter numbers between 8 and 23, 8 and 23 inclusive"<<endl;

        /*For statement iterates a number of times corresponding to the number
          of elements in the array*/
        for  (x = 0;x<16; x++){

                cin >> j;

                /*If statement checks if the number entered is between 8 and 23*/
                if(j>=8 && j<=23){

                /*Value of t places the entered number in its position within the array */
                t = j-8;
                 z[t] = j;
                }else{

                /*When an entry is wrong, the counter sets back one step */
                cout <<"Wrong entry"<<endl;
                x--;
                }
        }

        cout <<endl<<endl;

        for (int y =0; y<16; y++){

        /*Writes the values to the screen in there order form 8 to 23 */
                cout << z[y]<<",";

      }

       cout <<endl <<endl;
        return 0;
}
//By Andrea ~ Omega™
#include <iostream>

int main()
{
 int num;
 
 std::cout << "Type all the integers between 8 and 23\n";
 
 for(int cont=8; cont <= 23; cont++)
 {
  std::cout << "Enter a number: ";
  std::cin >> num;

  if(num != cont)
  {
   std::cout << "Error!\n";
   cont--;
  }
 }
 return 0;
}
//alternative solution by Afrim Kamberi
#include<iostream>

using namespace std;

int main()
{
	int n = 8;
	cout << "current number is 8" << endl;
	for (int i = 8; i < 23; i++)
	{
		cout << "put the following number";
		cin >> i;
		n += 1;
		if (i != n)
		{
			cout << "wrong entry,try again" << endl;
			i -= 1;
			n -= 1;
		}
	}

	return 0;
}

//Solution
#include <iostream>
using namespace std;

int main() {
    // Input and loop defined, only adds if input is correct.
    // EDIT: Incrementing the LCV by a truth value is poor form.
    for (short int i = 8, input; i <= 23; i += (i == input))
    {
        cout << "Enter the number " << i << ": ";
        cin >> input;
    }

    return 0;
}


//Kyung Shin
//16/09/2014
#include<iostream>

using namespace std;

int main(){
    short int input,inc=0;
    for(short int i=8;i<=23;i+=inc){
	cout<<"Enter number "<<i<<" : ";
	cin>>input;
	if(input==i) inc=1; else inc=0;
    }
    return 0;
}


//Suneet Kumar Saini
//26/08/2014
#include <iostream>

using namespace std;

int main()
{
	int num, size, i=0;
	int arr[16];
	cout<<"print the number between 8 to 23 "<<endl;

	while(1)
	{
		cin>>num;
		if(num >= 8 & num <= 23)
		{
			if(i == 0)
			{
				arr[i] = num;
				i++;
			}
			else
			{
				for(int j=0; j<=i; j++)
				{
					if(arr[j] != num)
					{
						arr[i] = num;
						i++;
					}
					else
					{
						cout<<"Entered number PREVIOUSLY EXISTED"<<endl;
						break;
					}
				}
			}
			
		}
		else
			cout<<"Entered number does not lie between 8 & 23"<<endl;

		if(i==16)
			break;
	}

	cout<<"Complete array : "<<endl;
	for(int j = 0; j<16; j++)
		cout<<arr[j]<<" "<<endl;

	return 0;
}


//solution by adel_deli

#include <iostream>
using namespace std;

int main()
{
    int num;
    for (int i = 8; i <= 23;) {
            cout <<"Enter number "<< i <<": ";
            cin >> num;

        if (num == i) {
                i++;
        }
        else {
                cout <<"You've entered invalid number, Try again."<<endl;
                continue;
        }
    }
    return 0;

}

Alternative solution

//Alternative solution by Bartosz Radwanski
//This one allows the numbers to be entered in random order and exits
//when all correct numbers have been entered.
//The code also works on any range of integers defined by MIN and MAX.

#include "stdafx.h"
#include <iostream>
#define MIN 8
#define MAX 23
using namespace std;

bool isInHistory(int arr[], int n) {
	for(int i=0; i<MAX-MIN+1; i++) {
		if(arr[i]==n) {
			return(true);
		}
		cout << ".";
	}
	return(false);
}

int _tmain(int argc, _TCHAR* argv[]) {
	int history[MAX-MIN+1];
	int input;
	cout<<"Enter all integers between "<<MIN<<" and "<<MAX<<" (both included).\n";
	for(int i=0; i<MAX-MIN+1; i++) {
		cout << "> ";
		cin >> input;
		if(input>=MIN && input<=MAX && !isInHistory(history, input)){
			history[i]=input;
			cout << "ok.\n";
		}
		else {
			cout << "not ok.\n";
			i--;
		}
	}
	return 0;
}


//alternate solution by Gunnar Godara
#include<iostream>

using namespace std;

void main()

{
	int i,num;
//enter value in for loop
	for(i=8;i<=23;i++)
		{
			cout<<"enter the number = ";
		cin>>num;
		if(num==i)
			{
				cout<<num<<endl;

			}
		else
			{
				cout<<"wrong number type again"<<endl;
				i--;
			}
		}

}


//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>
//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;
 
	cout << "\nEnter numbers from 8-23";
	cin >> b;
	if ((b < 8) || (b > 23))
		cout << "invalid";
	else {
		for (a = 8; a < 23; a++) {
   			cin >> b;
   			if (b > 23)
   				cout << "\nExceeds required input";
   		}
   	}

	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;

int 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;
			return 0;
		}
	}
	cout << "Congratulations\n";
	
	return 0;
}


//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++)
	{
		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;
	}

	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;

  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);
    }
  }

  printf("Congratulations!\n");

  return 0;
}

Another alternate solution

/*
* http://en.wikibooks.org/wiki/C++_Programming/Exercises/Iterations
*
* Exercise 2:
* Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.
*/

//Provided by someone who got bored on May 8, 2012

#include <iostream>

using namespace std;

//This version is a little more complicated, but it allows the numbers to be input in any order

int main()
{
	short int numbers[16]; //array of short ints with capacity 16; ((23 - 8) + 1 for including 8)
	bool valid;
	for (short int i = 8, input; i <= 23; i+=(valid)){ //borrowed from a previous solution
		valid = false;
		cout << "Enter a value between 8 and 23 (inclusive): ";
		cin >> input;
		
		if (input >= 8 && input <= 23) //compare input with range
		{
			if (numbers[input-8] == input) //8 must be subtracted from input in order to get correct index
			{
				cout << "You have already entered that value.\n";
			}
			else
			{
				numbers[input-8] = input; //this will essentially sort the array, allowing efficient access and comparison
				valid = true; //valid value was entered
			}
		}
		else
		{
			cout << "That value is not between 8 and 23!\n";
		}
	}
	
	cout << "Done.";
	return 0;
}


//alternate solution by James Neill

#include <iostream>
using namespace std;

//does not account for users entering consecuative numbers spaced apart
//inputing "8 9" will output "Please enter number 9: Please enter number 10:"

int main() {
	for(int i = 8, val; i < 24; i++) {
		cout << "Please enter number " << i << ": ";
		cin >> val;
		if (val == i) {
			continue;	//if the input is valid, continue with the loop 
		}			//end if
		if (val != i) {
			cout << endl << "Wrong number entered!" << endl <<  "You entered " << 
				val << " where you were meant to enter " << i << "." << endl << 
				"Try again." << endl << endl;
			--i;
		}			//end if
	}				//end for
	return 0;
}


#include <iostream>
using namespace std;

// Exercise 2: Write a program prompting the user for all numbers from 8 to 23, inclusive.
//             Must use a for loop.

int main(int argc, char **argv) {
	const int START = 8;
	const int END = 23;
	
	// Declared only once for efficiency.
	int n;

	for (int i = START; i <= END; i++) {
		for (;;) {
			cout << "Enter the number " << i << ": ";
			cin >> n;

			if (cin.fail()) {
				cout << "Invalid response. Not a number.\n";
				cin.clear();
				cin.ignore(99999, '\n');
			} else if (n == i) {
				break;
			} else {
				cout << "Invalid response: incorrect input.\n";
			}
		}
	}

	cout << "Congratulations!\n";

	return EXIT_SUCCESS;
}
//Another Solution
#include <iostream>

int main()
{
int v;

std::cout << "Type the integers between 8 and 23, both included" << std::endl;
for (int i = 0; i <= 23; i++)
	{
		if(i>=8 && i <= 23)
		{
			std::cin >> v;

			if (v != i)
			{
				i--;
				std::cout << "That's not the right number." << std::endl;
			}

			if (i == 23)
			{
				std::cout << "You did it!" << std::endl;
			}
		}
	}
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // std::cout, std::cin

using namespace std;

int main()
{
    // The user input
    int input;

    // Ask for a number
    cout << "Please, enter a number: ";
    // Get the user input
    cin >> input;

    // While the user is not inputting a correct number...
    while (cin.fail())
    {
        // Ask again for input
        cout << "Please, enter a valid number: ";
        // Clear the input we got before
        cin.clear();
        // Ignore the new line character
        cin.ignore(256, '\n');
        // Get the input again
        cin >> input;
    }

    // If the input is [56, 78], YOU WIN
    if (input >= 56 && input <= 78)
        cout << endl << "YOU WIN" << endl;
    else // Else YOU LOSE
        cout << endl << "YOU LOSE" << endl;

    return 0;
}
#include<iostream>

int main(int argc, char** argv){
	
	for(int i = 0; i < 1; i++){
		std::cout << "Will you type all of the numbers between 8 and 32?\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");
}


/*EXERCISE 2
Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.
alternative solution by Chaitali Kulkarni.. :) */
# include <iostream>
using namespace std;
# define max 100

int main()
{
	int n,i;
	for(i=0;i<max;i++)
	{

		do
		{
			cout<<"\nEnter N:";
			cin>>n;
			if(n<8||n>24)
				cout<<"\nOops entered value is not between 8-24!!!Please enter it again..";
		}while(n<8||n>24);
		cout<<"\nN=  "<<n;
	}
}

<syntaxhighlight lang="cpp">
/*
	Exercise : you have to enter all number from 8 to 23 .
	Season (08/18/2014).
*/
#include <iostream>
using namespace std;
int main(){
	int num,temp[20];
	bool flag=true;
	cout << "Let enter the number from 8 to 23 !" << endl;
	for(int i=0;i<(23-8);)
	{
		cin>>num;
		if(8<=num && num <=23){
			for(int j=0;j<20;j++){ 		// check number
				if(temp[j]==num){
					flag =false;
				}
			}
			if(flag){
				cout<<"good :"<< num << " go on \n";
				temp[i]=num;
				i++;
			}else{
				cout<<"The number already entered before ! \n";
				flag=true;
			}
				
		}else
			cout<<"Bad ! try again \n";
	}
	cout<< "\n"<< "You have finished";
	return 0;
}



Exercise 3 edit

Same as Exercise 2 but you must use a while.

Solution
#include <iostream>

using namespace std;

int main()
{
  int input, arr[16] = 0, i = 0;
  bool duplicate = false;
  
  cout << "Please enter integers between 8 and 23:  " << flush;
  
  do {
    cin >> input;
        if (input >= 8 && input <= 23) {
            for (int j = 0; j <= i; j++) {
                if (input == arr[j]) {
                    duplicate = true;
                }
            }
            
            if (duplicate) {
                cout << "Sorry the integer is already entered, try another one: " << flush;
                duplicate = false;
            }
            else {
                arr[i] = input;
                cout << "Correct, please proceed to the next integer: " << flush;
                i = i + 1;
            }
        }
        else {
            cout << "Incorrect, please enter integers between 8 and 23: " << flush;
        }
  } while(arr[16] == 0);
  return 0;
}

//Judy Mok sigurrosist@gmail.com //C++ Exercise 20161103 //Write a program that asks the user to type all the integers between 8 and 23 (both included) using a for loop.

  1. include "stdafx.h"
  2. include <iostream>

using namespace std; int main() {int number = 8, correct = 8; while (correct <=23) { cout << "Enter the number " << number << " : " ; cin >> number; while (number != correct) {cout << "Enter the number " << correct << " again : " ; cin >> number;} if (number == correct) {number = 1 + number; correct = 1 + correct;} } cout << "Good job" <<endl; system ("pause");

return 0;

}

// By : Sardor Karimov

  1. include <iostream>

using namespace std;

int main( ) {

  int num, i = 8;
 
 cout<<"enter numbers from 8 to 23\n";
 
 while(i != 23)
 {
  cin >> num;
  
  if(num == i)
  { 
     cout <<"continue"; 
     i++;
  }
   else
   
     {
       cout << " wrong!! the next number was " <<i;
       break;
     }
 }

}

//Made by: Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i,j,k,p,n[16];

main(){
clrscr();
for(i=8;i<25;i++){n[i-8]=i;}
while(k<16){
	cout<<"The program will end once all required numbers were all given.\nEnter numbers between 8 and 23 (both inclusive): ";
	cin>>p;
	for(j=8;j<25;j++){
		if(n[j-8]==p){k++;n[j-8]=0;}
	}
        clrscr();
}
getche();
return 0;
}
//By Andrea ~ Omega™
#include <iostream>

int main()
{
 int number, cont=8;
 
 while(cont <= 23)
 {
  std::cout << "Enter a number: ";
  std::cin >> number;

  if(number != cont)
  {
   std::cout << "Error!\n";
   cont--;
  }
  cont++;
 }
 return 0;
}
//solution by Afrim Kamberi
#include<iostream>

using namespace std;

int main()
{
	int n = 8;
	cout << "current number is 8" << endl;
	int i = 8;
	while(i<=23)
	{
		cout << "put the following number";
		cin >> i;
		n += 1;
		if (i != n)
		{
			cout << "wrong entry,try again" << endl;
			i -= 1;
			n -= 1;
		}
	}

	return 0;
}

#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);
}

Alternative solutions

////Alternate solution by Gunnar Godara

#include<iostream>
using namespace std;

void main() {
    int i=8, num;
    while(i<=23) {
	cout<<"enter the value = ";
	cin>>num;
	if(num==i) {
	    i++;
        }
	else {
	    cout<<"You entered wrong number";
        }
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

A solution that uses input from the user could be

#include<iostream>

//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);
}
}


//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>
//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;
}
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");
}


# include <iostream>

int main ()

{
	using std::cout;
	using std::cin;
	int i = 8;
	int num;
while (i <= 23)
{
	cout<<"Enter the integer again\n";
	cin>>num;
	i++;
		
}
		
return 0;

}


/*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.
*/
// Alternative solution by Metalhands
#include "stdafx.h"
#include <iostream>

void main(){
	int i = 8;
	using namespace std;
	while (i <= 23){
		cout << "Enter nmber:" << endl;
		int flag;
		cin >> flag;
		if (flag != i)
		{
			cout << "Error!!! Try again" << endl;
			continue;
		}
		else
			cout << "Valid number entered: "<< flag << endl;
			i++;
	}
}


An easy solution :) By Francis Percival D. Wisco—Kaykiks<3

/* EXERCISE 3 */

#include<iostream>
#include<conio.h>

using namespace std;

main()
{
      
      int A = 8;
      int B;
      while (A >= 8 && A<=23)
      {
      cout<<"Enter the number "<< A<< ":";
      cin>> B ;
      if(A == B)
      {
           A = A + 1;
       }
      }
      getch();
      return 0;
      }
/* Easy Max and Min solution. Ankit Nayak*/

#include <iostream>
using namespace std;

int main(){
    int max, min;
    max=23;
    min=8;
    int capture;
    int interval=0;
    while(interval<(max-min+1)){
        cout<<"Enter number 8 till 23 serially:  ";
        cin>> capture;
        if(capture==(min+interval)){
            cout<<"Correct entry"<<endl;
            interval++;
        }
        else{
            cout<<"Incorrect entry. Please enter "<<(min+interval)<<endl;
        }
    }
}
#include <iostream> //mostafa jawad
using namespace std;

void main()
{
	int n,sum=0,c=1;
	while(c<=10)
	{
		cout<<"ENTER NUMBER "<<c<<"of 10: ";
		cin>>n;
		cout<<n<<"+"<<sum<<"=";
		sum+=n;
		cout<<sum<<endl;
		c++;
	}
}
//Easy solution by David J
#include <iostream>

using namespace std;

int main()
{
    int ival;
    cout << "please enter integer between 8 and 23: " << endl;
    cin >> ival;
    while (ival >= 8 && ival <= 23)
        cin >> ival;

    return 0;
}
/*
	Exercise : you have to enter all number from 8 to 23 .
	Season (08/20/2014).
*/
#include <iostream>
using namespace std;
int main(){
	int num, temp[20],i=0;
	bool flag = true;
	cout << "Let enter the number from 8 to 23 !" << endl;
	while (i<=(23-8)){
		cin >> num;
		if (8 <= num && num <= 23){
			for (int j = 0; j<20; j++){ 		// check number
				if (temp[j] == num){
					flag = false;
				}
			}
			if (flag){
				cout << "good :" << num << " go on \n";
				temp[i] = num;
				i++;
			}
			else{
				cout << "The number already entered before ! \n";
				flag = true;
			}

		}
		else
			cout << "Bad ! try again \n";
	}
	cout << "\n" << "You have finished";
	return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin

using namespace std;

int main()
{
    // The user input
    int input;

    // Explain the exercise
    cout << "Please, enter every number from 8 to 23." << endl << endl;

    // Loop from 8 to 23 (could also be i <= 23)
    int i = 8;
    while (i < 24)
    {
        // Ask for the number to be entered
        cout << "Please, enter the number " << i << ": ";
        // Get the user input
        cin >> input;

        // If the input isn't a number or the number is not the correct one
        while (cin.fail() || input != i)
        {
            // Ask the user to input the correct value
            cout << "Please, enter the correct value, the number " << i << ": ";
            // Clear the input we got before
            cin.clear();
            // Ignore the new line
            cin.ignore(256, '\n');
            // Get the user input again
            cin >> input;
        }

        // Add a new line to make it look kind of better
        cout << endl;
        i++;
    }

    // Congratulate the user
    cout << "Congratulations, you have correctly entered every number for "
         << "the range [8, 23]!" << endl;

    return 0;
}
//By Alex Lobo Rodrigues
// Example program
#include <iostream>

int main()
{
int v;
int i = 8;
std::cout << "Type the integers between 8 and 23, both included" << std::endl;

while (i != 24)
	{   
	    if(i>=8 && i <= 23)
	    {
	        std::cin >> v;
	        if (v != i)
			{
				std::cout << "That's not the right number." << std::endl;
			}else{
			    i++;
	        }
	    
	    if (i == 24)
			{
				std::cout << "You did it!" << std::endl;
			}
	}
 }

}


Exercise 4 edit

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

Solution
// Example 1
#include <iostream>

using namespace std;

int main()
{
  int input, sum=0;
  
    for (int i = 0; i < 10; i++) {
        cout << "Please enter integer " << i+1 << ": " << flush;
        cin >> input;
        
        if (cin.fail()) {
            while (cin.fail()) {
                cout << "Please do not enter values other than integer, try again: " << flush;
                cin.clear();
                cin.ignore(256,'\n');
                cin >> input;
            }
            sum = sum + input;
        }
        else {
            sum = sum + input;
        }
    }
    cout << "The sum of the integers is " << sum << endl;
}

//Made by: Reiz Troy D. Durante

/// By : Sardor Karimov

#include<iostream>

using namespace std;

int main()
{
  int sum = 0,x = 0;
  
  cout<<"enter 10 integers\n";
   
  for(int i = 0 ; i <= 9; i++)
  {
     cin>>x;
     sum += x;    
  }
  
  cout<<sum;
}
//Solution by C++ expert
#include <iostream>
using namespace std;
int main() {
	int num,sum=0;
	for (int i=0;i<10;i++) {
		cout<<"Enter number: ";
		cin>>num;
		sum+=num;
		}
	cout<<endl<<"The sum of all these numbers is "<<sum<<"\n";
	return 0;
}

// Solution By Mustafa Aga Albania.

//Solution by Aldo Ziflaj
#include <iostream>
using namespace std;
int main() {
	int num[10],sum=0;
	for (int i=0;i<10;i++) {
		cout<<"enter a number: ";
		cin>>num[i];
		sum+=num[i];
		}
	cout<<"The sum of all these numbers is "<<sum<<"\n";
	return 0;
}

Alternative solution by Bartosz Radwanski

//Alternative solution by Bartosz Radwanski
#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Enter 10 integers:\n";
	int n, total=0;
	for(int i=0; i<10; i++) {
		cout << "#" << i+1 << "> ";
		cin >> n;
		total+=n;
	}
	cout << "Total: " << total << endl;
	return 0;
}


#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 << ".";
}

//alternate solution by Gunnar Godara
#include<iostream>

using namespace std;

void main()

{

	int i ,num, sum=0;

	for(i=1;i<=10;i++)
	{
		cout<<"enter value = ";
		cin>>num;
		sum += num;
	}

	cout<<"Sum of all the numbers 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");
}

A possible solution using a vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {
	vector<int> numbers;
	do {
		short int input;
		static short int count = 1;
		cout << "Enter the " << count << "(st/nd/rd/th) value: ";
		if (!(cin >> input)) {
			cin.clear();
			cin.ignore(10000, '\n');
		} else {
			numbers.push_back(input);
			count += 1;
		}
	} while (numbers.size() != 10);
	int total;
	for(int & n : numbers) {
		total += n;
	}
	cout << total << endl;
	return 0;
}
/*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");
}
/*
Write a program that asks the user to type 10 integers and writes the sum of these integers.

By Eliel Garcia
*/

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

const int MAX_ELEMENTS_IN_ARRAY = 10;

int getUserInput(int userInputArray[]);
int inputFail(int arrayPosition, int userInputArray[]);

int main()
{
    int arraySum = 0;

    int userInputArray[MAX_ELEMENTS_IN_ARRAY];
    getUserInput(userInputArray);

    for(int i = 0; i < 10; i++)
    {
        arraySum += userInputArray[i];
    }
    cout << arraySum;

    cin.get();
    return 0;
}

int getUserInput(int userInputArray[])
{
    for(int i = 0; i < 10; i++)
    {
        cout << "Enter number " << i+1 << endl;
        cin  >> userInputArray[i];
        inputFail(i, userInputArray);
    }
}

int inputFail(int arrayPosition, int userInputArray[])
{
    while(!cin)
    {
        cin.clear();
        cin.ignore(3000, '\n');
        cout << "Invalid character, please try again " << endl;
        cin  >> userInputArray[arrayPosition];
    }
}
#include <iostream>
using namespace std;
void main()
{
	int sum=0,num[10];
cout<<"enter the up to 10 number\n";
	for(int i=0; i<10; i++)
	{
		cout<<"num"<<"["<<i<<"]"<<"=";
		cin>>num[i];
		sum+=num[i];
		

	}
	for(int i=0; i<10; i++)
	{
		cout<<num[i];
		cout<<"+";
		if(i==9)
		{
			cout<<"\b";}
	}
	cout<<"=";
	cout<<sum;
	cout<<endl;
}


< source lang = "cpp"> \\ By metalhands

  1. include "stdafx.h"
  2. include <iostream>

void main(){ using namespace std; int i = 1; int sum = 0; while ( i <=10 ){ cout << "Enter number position " << i << ": "; int y; cin >> y; sum = sum + y; i++;

} cout << "Final sum is: " << sum << endl; } </syntaxhighlight>

/*
	Exercise : you have to enter 10 integers number.The program will auto return the sum of these
	Season (08/20/2014).
*/
#include <iostream>
using namespace std;
int main(){
	int sum=0,num;
	cout << "Let enter 10 integers number ,the program will return sum of these" << endl;
	for (int i = 0; i < 10; i++){
		cout << "number " << i+1 << " :";
		cin >> num;
		sum += num;
	}
	cout << "\n" << "The sum :" << sum<<endl;
	system("pause");
	return 0;
}
//alternate solution by Gazmend Shehu
##include <iostream>
using namespace std;

int main()
{
cout<<"input 10 integrers"<<endl;
int i;
int n;
int sum=0;
for(i=0;i<=10;i++){
cin>>n;
sum=sum+n;

}
cout<<"sum is "<<sum;
	return 0;
} // shehu.meni@gmail.com
#include<iostream>
 
using namespace std;
 
int main(){
int a,b,c;
	c=0;
	cout<<"    Enter any ten Number   \n";
	for(a=1;a<=10;a++){
	cout<<a<<" number: ";
	cin>>b;
	c+=b; // or c=c+b
	}
	cout<<c<<endl;
		return 0;
}


//alternate solution by Dwayne
#include <iostream>

using namespace std;

int num[10] ;
int typeNum = 1;

int main()
{
	cout << "Type in 10 numbers "<<endl;
	for (int i= 0; i <= 9; i++)
	{
		cout << "type in " << typeNum << " number: ";
		cin >> num[i];
		typeNum++;
	}
	cout << "Numbers you type ";
	for (int n = 0; n <= 9; n++)
	{
		cout << num[n] << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin

using namespace std;

// The main function
int main()
{
    // The user input
    int input;
    // The sum (make it big)
    long int sum = 0;

    // Loop 10 times for each digit
    for (int i = 0; i < 10; i++)
    {
        // Ask for the i + 1 integer
        cout << "Please, enter the integer number " << i + 1 << ": ";
        // Get the user input
        cin >> input;

        // If the input isn't correct
        while (cin.fail())
        {
            // Ask for a valid number
            cout << "Please, enter a valid integer number for the value "
                 << "number " << i + 1 << ": ";
            cin.clear(); // Clear the input we had received
            cin.ignore(256, '\n'); // Ignore the new line
            cin >> input; // Get the user input again
        }

        sum += input; // Add the input to the sum value, adding every time
    }

    // Show the outcome of the sum
    cout << endl << "The sum of the 10 digits you entered is " << sum << endl;

    return 0;
}
//By Michaelo Angelo

#include <iostream>

int nTemp;
int nSum;
void main()
{
	std::cout << "Enter ten intenegers: " << std::endl;

	for (int i = 0; i < 10; ++i)
	{
		std::cin >> nTemp;
		nSum = nSum + nTemp;
	}
	std::cout << "Sum of your numbers is: " << nSum << std::endl;
	system("Pause");
}
//By Jonathan Nunez

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

#define newline cout<<'\n'

void process(void);
int main()
{
	printf("Enter 10 integers: ");newline;
	process();
	system("pause");
	return 0;
}

void process(void)
{
	string user_input;
	int sum(0), cc;

	for (int i = 0;i < 10; i++) {
		cout << i << ") ";
		getline(cin, user_input);
		stringstream(user_input) >> cc;
		sum += cc;//sum = 0
	}newline;
	cout << "Sum of all integers: " << sum;
	newline;
}


Author: jimmymass;

Exercise 5 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
  int num, smallest = 0;
  cin >> num;
  smallest = num;
  for(int i = 0; i < 9; i++){
    cin >> num;
    if(num < smallest) smallest = num;
  }
  cout << smallest << endl;
}
// Example
#include <iostream>

using namespace std;

int main()
{
    int arr[10], temp;
    
    for (int i = 0; i < 10; i++) {
    
        cout << "Please enter integer " << i + 1 << " : " << flush;
        cin >> arr[i];
        
            for (int j = 0; j < i; j++) {
                
                if (arr[i] < arr[j]) {
            
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
    }
    
    cout << "The smallest number is: " << arr[0]; 
    return 0;
}
//Made by Lam P.

#include <iostream>

using namespace std;

int main()
{
	int A[10];
	
	for(int i=0;i<10;i++)
	{
		cin>>A[i];
	}
	
	int min;
	min=A[0];
	
	for(int i=0;i<10;i++)
	{
		if(min>A[i])
			min=A[i];
			
		else
			min=min;
	}
	
	cout<<min;
}
//Made by Michael C

#include <iostream>

int main ()
{
    int number, min;
    for (int i = 0; i < 10; i++)
    {
        if (i == 0)
        {
            std::cout << "Number " << i+1 << " ";
            std::cin >> number;
            min = number;
        }
        else
        {
            std::cout << "Number " << i+1 << " "; std::cin >> number;
        }
        if (number < min)
        {
            min = number;
        }
    }
    std::cout << "The smallest value is " << min << std::endl;
    return 0;
}

<syntaxhighlight lang=cpp>

//Made by Mustafa Aga Albanian.
#include<iostream> 
using namespace std; 
 
int main()
{
        int i,  min=999;
        int t[10];
        
        cout << "Write 10 integers:" << endl;
        for (i=1; i<10; i++)
        { cin>> t[i];
        }
        for (i=1; i<10; i++){
		
        if (min>t[i])
        min=t[i];
        
		}
        cout <<"The smollest value is: " << min << endl;
        
        return 0;
}
//Made by: Reiz Troy D. Durante
#include<iostream.h>
#include<conio.h>

int i,n,p=2147483647;

main(){
clrscr();

while(i<10){
     cout<<"Enter 10 integer: \n";
     cin>>n;
     if(n<p){p=n;}
     i++;
     clrscr();
}

getche();
return 0;
}
//Solution by Aldo Ziflaj
#include <iostream>
using namespace std;
 
int main() {
	int num[10],min;
	for (int i=0;i<10;i++) {
		cout<<"enter 10 numbers: ";
		cin>>num[i];
		}
	min=num[0];
	for (int i=0;i<10;i++) if(num[i]<min) min=num[i];
	cout<<"The smallest of all these numbers is "<<min<<"\n";
	return 0;
}
//solution by Ahmed Samir

#include<iostream>

using namespace std;

main()

{

    int counter,value,min_value;

    cout << "Enter 10 values and I tell you which is the smallest one.\n\n";

    counter=1;

    cout << "\n1-\t";

    cin >> value;

    min_value=value;

        while(counter<10)

        {

            counter++;

            cout << endl << counter << "-\t";

            cin >> value;

                if(value<min_value)

                {

                min_value=value;

                }

        }

    cout << "Smallest value is: " << min_value;

}
#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];
    
    return 0;
}
//Possible solution using a vector and min_element()
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
	vector<int> inputVals;
	// Create vector for the input values
	
	do {
		short int input;
		static short int count = 1;
		cout << "Enter the " << count << " value: ";
		if (!(cin >> input)) {
			cin.clear();
			cin.ignore(10000, '\n');
		// This if statement is used for ensuring only numbers are entered and clearing any invalid characters
		} else {
			inputVals.push_back(input);
			count += 1;
			// adds the input value to the vector and increase the count by 1
		}
	} while (inputVals.size() != 10);
	int min = *min_element(inputVals.begin(), inputVals.end());
	// assigns the minimum value to min using the min_element function from algorithm
	cout << min << endl;
	// print the minimum value to the console
	
	return 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>

using namespace std;

int main()
{
	int num[10];
	int i = 0;
	int 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;
		
		return 0;
}
/*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;
}

</syntaxhighlight>

/* By : Sebastian Gherhes 04/08/2016
   Similar to something above, but using a for loop
*/
#include<iostream>

using namespace std;

int main(){

    int value = 0, min = 0;

    cout<<"Enter 10 values and I will tell you which one is the smallest"<<endl;
    cout<<"Enter number: "<<endl;

    cin >> value;

    min = value;

    for(int i =0; i < 9; i++){
        cout<<"Enter number: "<<endl;
        cin>>value;
        if(value < min){
            min = value;
        }

    }

    cout<<"Smallest value is: "<<min<<endl;

    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;
}
/*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() { // solution by Minwoo Ju,8NX
    
    
 cout << "this program calculates the smallest value between 10 intergers." << endl;

int num[10];
int small = num[0];

for(int i = 0;i <= 10;i++) {
        
cin >> num[i]; // gets all the values from the user.

}

for (int i = 0;i <= 10 ; i++){
    
    if (small > num[i]) {
      
      small = num[i]; // analyzes the array until the smallest value is found.
      
      }
      }

cout << "the smallest value of them all is:" << small << endl;

system("pause"); // program successful.
return 0; 
}
// Ternary abuse
#include <iostream>
int main() {
    int num, smallest;
    std::cout << "Enter 10 numbers:" << std::endl;
    for (int i = 0; i < 10; i++) {
        std::cin >> num;
        (i == 0) ? smallest = num : ((num < smallest) ? smallest = num : NULL);
    }
    std::cout << "Smallest number: " << smallest << std::endl;
}
/*
Write a program that asks the user to type 10 integers and writes the smallest value.

//Eliel Garcia
*/

#include <iostream>
#include <climits>

using std::cin;
using std::endl;
using std::cout;

int getUserInput(int arrayOfInts[]);
void getMinInteger(int arrayOfInts[]);
void inputFailControl(int arrayPosition, int arrayOfInts[]);

int main()
{
    int arrayOfInts[10];

    getUserInput(arrayOfInts);
    getMinInteger(arrayOfInts);

    cin.get();
    return 0;
}

void getMinInteger(int arrayOfInts[])
{
    double min = INT_MAX;

    for(int i = 0; i < 10; i++)
    {
        if(min > arrayOfInts[i])
        {
            min = arrayOfInts[i];
        }
    }
    cout << min;
}

int getUserInput(int arrayOfInts[])
{
    for(int i = 0; i < 10; i++)
    {
        cout << "Type integer number " << i+1 << ": " << endl;
        cin  >> arrayOfInts[i];
        inputFailControl(i, arrayOfInts);
    }
}

void inputFailControl(int arrayPosition, int arrayOfInts[])
{
    while(!cin)
    {
        cin.clear();
        cin.ignore(3000, '\n');
        cout << "Invalid character, please try again " << endl;
        cin  >> arrayOfInts[arrayPosition];
    }
}


//Solution Provided By Neeraj Morar
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
	int nums[10];

	for (int i = 1; i <=10; i++) {
		cout << "Type in an integer: ";
		cin >> nums[i];
		cout << "\n";
	}

	sort(nums, nums + 9);
	cout << nums[0];
	cout << "\n";
	cout << "\n";

	system("PAUSE");
}
//solution by adel deli
#include <iostream>

using namespace std;

int main()
{
    cout <<"Enter 10 numbers to determinate the smallest value: "<< endl<< endl;

    int num, temp;
    int min;

    cout<< "Enter number 1: ";
    cin >> num;

    min = num;

    for(int i = 2; i <= 9; i++){
            cout << "Enter number "<<i <<": ";
            cin >> num;
            if (num < min){
                    min = num;
            }
    }
    cout <<"The smallest number is: "<< min;

    return 0;
}
/*    EXERCISE 5 : enter 10 intergers and return the smallest number .
      Season (09/3/2014).
        
*/ 
#include<iostream>
using namespace std;
int main()
{
	int i, arg[10],min;
	for (i = 0; i < 10; i++)
	{
		cout << "Let enter the number " << i+1 << " :";
		cin >> arg[i];
		cout << endl;
		if (i == 0) min = arg[0];
		if (arg[i] < min) min = arg[i];
	}
	cout << "string number :";
	for (i = 0; i < 10;i++)
		cout << arg[i] << "\t";
	cout << endl;
	cout << "The smallest number is : " << min << endl;
	return false;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin

using namespace std;

// The main function
int main()
{
    // The user input
    int input;
    // The array that will hold every integer
    int inputs[10]; // A size of 10 for 10 inegers
    // The smallest integer
    int smallest;

    // Loop 10 times, one per digit
    for (int i = 0; i < 10; i++)
    {
        // Ask for the i + 1 integer
        cout << "Please, enter the integer number " << i + 1 << ": ";
        // Get the user input
        cin >> input;

        // If the input isn't correct
        while (cin.fail())
        {
            // Ask for a valid number
            cout << "Please, enter a valid integer number for the value "
                 << "number " << i + 1 << ": ";
            cin.clear(); // Clear the input we had received
            cin.ignore(256, '\n'); // Ignore the new line
            cin >> input; // Get the user input again
        }

        // Set the corresponding value in the inputs array with the input value
        inputs[i] = input;
    }

    // Set a default value for smallest
    smallest = inputs[0];

    // Iterate through each number of the array except the first one that we
    // already used right before
    // Remember sizeof returns the number of bytes, so we divide it by the
    // number of bytes in the first value and we'll get the real
    // array size (10)
    for (int i = 1; i < sizeof(inputs) / sizeof(inputs[0]); i++)
    {
        // If any of the new numbers is smaller than the first number
        if (inputs[i] < smallest)
            smallest = inputs[i]; // Set such number as the smallest one
    }

    // Inform the user about the smallest number
    cout << endl << "The smallest value you have entered is " << smallest
         << endl;

    return 0;
}
/*By Jonathan Nunez*/

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

namespace vars {
	float input;
	string user_input;
	int min = 10, max = 0;
}

#define newline std::cout<<'\n'
float minimum(float &m);

int main()
{
	printf("Write 10 integers: ");
	//for loop for user entering values within 10 elements in an array
	for (int i = 0; i < 10;i++) {
		std::getline(cin, vars::user_input);
		std::stringstream(vars::user_input) >> vars::input;

		minimum(vars::input); 
	}
	std::cout << "Min: " << minimum(vars::input);newline;	
	return 0;
}

float minimum(float &m)
{
	if (m < vars::min) {
		vars::min = m; 
	}
	return vars::min;	
}
/*
 * uebung1.cpp
 *
 *  Created on: 28.01.2016
 *      Author: bobska
 */
#include<iostream>
#define MIN(a,b) ((a) < (b) ? a : b)
using namespace std;
int main(){
	 int sum = 0;
	 int num;
	 cin >> num;
	 sum = num;
	 for(int i=1; i<10; i++){
		 cin >> num;
	  sum = MIN(sum, num);}
	 cout<< "the smallest given in Integer is: " << sum;

}
// Solution by Alexander Christensen //
// In this program the user enters 10 integers,
// then the program calulates the minimum value.

#include <iostream>

using namespace std;

void main() 
{
	long int input, min = LONG_MAX;

	cout << "Enter 10 integers - " << "the program will find the minimum value" << endl << endl;
	
	for(int i = 1; i <= 10; i++)
	{
		cout << "number #" << i << ": ";
		cin >> input;
		if(input < min)
		{
			min = input;
		}
	}
	cout << "The smallest was: " << min << endl;
}
//By: Michał Sikorski 02/05/16
#include<iostream>

int i, inpt, outpt;

using namespace std;
int main()
{
	cin>>outpt;
	while(i!=9)
	{
		cin>>inpt;
		if(outpt>inpt)outpt=inpt;
		i++;	
	}
	cout<<outpt;
}


Exercise 6 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
#include <cmath>
using namespace std;

int main(int argc, char const *argv[]) {
  double x = pow(5,3);
  int y;
  cin >> y;
    cout << "5^3 + " << y << "^3 = " << x + (int)pow(y,3) << endl;
  return 0;
}
// Example
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int input, sum=0;
    
    cout << "Please enter an integer: " << flush;
    cin >> input;
    
    if (input < 4) {
        cout << "Please enter an integer greater than 5" << endl;
    }
    
    else {
        for (int i = 5; i <= input; i++) {
            sum = sum + (i*i*i);
        }
        cout << "The sum is: " << sum << endl;
    }

    return 0;
}
#include <iostream>

using namespace std;

int main()
{
	int N;
	int end = 0;

	cin >> N;
	while (N < 5)
		cin >> N;

	for (int i = 5; i <= N; ++i)
		end = end + i^3;

	cout << end << endl;

	system("pause");

	return 0;
}
#include<iostream.h>
#include<conio.h>
void main(){
double i,sum,n;
cout<<"Enter number";
cin>>n;
for(i=5;i<=n;i++)   {
cube=i*i*i;
sum=sum+cube;       }
cout<<"Sum of cube is "<<sum;
getch();
}
//Solution by Lam P
#include <iostream>

using namespace std;

int main()
{
	int N;
	int cube=0;
	int sum=0;
	cin>>N;
	
	
	for(int i=5; i<=N;i++)
	{
		cube=i*i*i;
		
		sum=sum+cube;
	}
	
	cout<<"The sum of the cube between 5 and "<<N<<" is "<<sum<<endl;
}
//Made by: Reiz Troy D. Durante</br>]
#include<iostream.h>
#include<conio.h>

int i,n,p=125;

main(){

clrscr();
cout<<"Enter a number: \n";
cin>>n;

for(i=n;i>5;i--){p+=i*i*i;}
for(i=n;i<5;i++){p+=i*i*i;}

cout<<"The sum of cube of 5 up to cube of "<<n<<" is "<<p;
getche();
return 0;
}
// Author: Franklin
// A big simplification on the number of operations (no iterations) is to take into account
// that there is a closed formula for the sum of consecutive cubes of natural numbers.
// See http://en.wikipedia.org/wiki/Faulhaber%27s_formula#Examples
// The formula is a polynomial. This means that there is yet another point to take into account.
// That is the Horner-Ruffini algorithm to evaluate polynomials. This reduces the number of 
// operations to compute the formula even further.
/* Sidenote from random reader: In the "else if"-statement you can leave the
   "&&(input <5) out. That is, why it's called "else". You can leave it though,
   for readability.*/
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	unsigned long N, result; To input N
	cin >> N;
	// Following is the sum of the cubes all numbers from 1 up to N 
        // It is stored in a temp to not repeat computations
	unsigned long temp{ (input*(input*(input*(input + 2) + 1))) / 4 };
	if (input >= 5){
		result = temp - 100; // Temp minus the sum of the cubes of numbers up to 4.
		cout << "The sum of the cubes from 5 to " << input << " is: " << result << endl;
	}
	else if ((input>=0)&&(input <5)){ 
		result = 225 - temp + input*input*input; //Sum of cubes up to 5 minus that up to N plus N^3
		cout << "The sum of the cubes from " << input << " to 5 is: " << result << endl;
	};
	return 0;
}

Alternative solutions

//Solution by Aldo Ziflaj
#include <iostream>
#include <cmath>
using namespace std;
 
int main() {
	int a,i,sum=pow(5,3);
	cout<<"Enter an integer greater than 5: ";
	cin>>a;
	i=a-5;
	while (i<=a) {
		sum+=pow(i,3);
		i++;
	}
	cout<<"Sum of cubes from 5 to "<<a<<" is "<<sum;
	return 0;
}


// by Matthewkos
//Exercise 6
#include<iostream>
using namespace std;
//declare
         int N,sum,loop;
//main
      int main () {
         cout<<"Enter an integer N\t";
         cin>>N;
         if (5>N)
            for (loop=5;loop>=N;loop--)
                sum+=loop*loop*loop;
            else for (loop=5;loop<=N;loop++)
                     sum+=loop*loop*loop;
         cout<<"Sum of Cube 5 to Cube "<<N<<" is\t"<<sum<<endl;
         system("PAUSE");
         return 0;}
#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>

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 ;
}

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>

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.";
}

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;
}

Solution #10

#include <iostream>

using namespace std;

int main()
{
    cout << "Enter an integer N and I will compute the sum of 5³ to N³." << endl;

    int N = 0;
    cin >> N;

    int count = N > 5 ? 1 : -1, //If N > 5 we count up to N else we count down to N
 	i = 5,			//Startvalue is 5
	sum = N*N*N;		//The sum-total

    for (; i != N; i += count)
	sum += i*i*i;

    cout << "The sum is: " << sum << endl;
}

Solution #11

#include <iostream.h>

int main()
{
  int num, sum = 0;
  cout << "Vstavi število večje od 5: "; cin >> num;
	if (num>=5)
	{ 
		int num1=num;
		for (int stevec=5;stevec<=num1;stevec++)
		{sum=sum+(num*num*num);
			num--&&num>=5;}
		cout << "Število je: " << sum;}
	else cout <<"Število je premajhno"<<endl;

}

Solution #12

//by David J
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter an integer (more than 5): " << endl;
    int ival, sum = 0;
    cin >> ival;
    if (ival <= 5)
            cout << "An integer must be more than 5";
    else
    {
    for (int i = 5; i <= ival; i++)
        sum += (i*i*i);

    cout << "Sum of cubes from 5 to " << ival << " = "<< sum << endl;
    }
    return 0;
}

Solution #13

//by Alan Costa
#include <iostream>

using namespace std;

int main(){
	int n;
	int sum = 0;

	cout<< "Type N greater than 5: \n";
	cin>> n;

	for (int i = 5; i <= n; i++)
		sum += i*i*i;
	cout<< "The sum is: " << sum << endl;
	return 0;
}

Solution #14

// Wojtek Baginski
#include <iostream>
using namespace std;
int main() {
        int n;
        do { cout << endl << "Type n>=5: ";
             cin >> n;  
        } while (n<5);
        int m = n*(n+1)/2
        cout << "The sum is " << m*m-100 << endl;
}

Solution #15

//Richard Mahogany

#include <iostream>

int main()
{
    int n = 0;
    double both = 0;
    int i = 5;

    cout << "Please Enter a number: ";
    cin >> n;

    do
    {

        if(n >= i)
        {
        both +=  (i * i * i);
        cout << "\n\n"<< both << endl;
        cout << "\n";
        i++;
        }else
        {

        both +=  (i * i * i);
        cout << "\n\n" << both << endl;
        cout << "\n";
        i--;

        }
        if(i == n)
        {
            both += (i * i * i);
            cout << "\n\n Your answer is: " << both << endl;
            break;
        }
    }while(i <= n || i >= n);

     return 0;

    }
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std;

int main()
{
    // The user input;
    int input;

    // Ask for input from the user
    cout << "Please, enter an integer number: ";
    // Get the user input
    cin >> input;

    // While the input is not correct
    while (cin.fail())
    {
        // Ask for valid input again
        cout << "Please, enter a valid integer number: ";
        // Clear the old input
        cin.clear();
        // Ignore the new line
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Read the input again
        cin >> input;
    }

    // Calculate the cube of 5
    long int cubefive = 5 * 5 * 5;

    // If the integer is under 5
    if (input < 5)
    {
        // Show a new line
        cout << endl;

        // Calculate from such number up to 5
        for (int i = input; i <= 5; i++) // Remember i <= 5 could also be i < 6, both will stop at 5
            cubefive += i * i * i;

        // Show the sum
        cout << "The sum of the cubes from " << input << " to 5 is " << cubefive
             << endl;
    }
    // If the integer is exactly 5
    else if (input == 5)
    {
        // Show a new line
        cout << endl;

        // Simply calculate the cube of 5
        cout << "The cube of " << input << " is " << input * input * input
             << endl;
    }
    // If the integer is over 5
    else if (input > 5)
    {
        // Show a new line
        cout << endl;

        // Calculate from 5 to such number
        for (int i = 5; i <= input; i++) // In this case, i <= input would be equivalent to i < input + 1
            cubefive += i * i * i;

        // Show the sum
        cout << "The sum of the cubes from " << input << " to 5 is " << cubefive
             << endl;
    }

    return 0;
}
-----------------------------------------------------------------------------------

#include<iostream>
#include<cmath>
using namespace std;
int main()
{

int i,n,sum=0;

cout<<"Enter a number ";
cin>>n;

for(i=5 ; i<n ; i++)
{

sum=sum+pow(5,3)+pow(n,3);

}
cout<<"Sum of cubes from 5 to "<<n<<" is: "<<sum;

return 0;
}
//By Jonathan Nunez
#include <iostream>
#include <sstream>
#include <string>

#define newline std::cout<<'\n';

using namespace std;

void evaluate(void);
float process(float &N);

namespace vars {
	float exponent, N, total, initial;
	int i = 5;
	string user_input;
}

int main()
{
	printf("Enter any number greater than 5: ");	
	getline(cin, vars::user_input);//input is in string 
	stringstream(vars::user_input) >> vars::N;//converts string to numerical values
	evaluate();
	process(vars::N);	
	std::cout << "Sum is: " << vars::initial;newline;
		
	return 0;
}
void evaluate(void)
{
	if (vars::N < 5) {
		printf("Input must be greater than 5!");newline;
		main();
	}
}

float process(float &N)
{
	for (;vars::i <= N;vars::i++) {
		std::cout << vars::i << "^3 = " << pow(vars::i, 3);newline;
		vars::initial += pow(vars::i, 3);
	}newline;

	return vars::initial;
}
#include <iostream>
using namespace std;
int main()
{
    int n,c;
    float sum;
   
    
    
   
    cout<<"put your intger n please ";
    cin>>n;
     if(n>=5)
     {
     for(c=5;c<=n;c++)
    {
    sum+=c*c*c;
                       
      }
      cout<<"your sum is "<<sum;
      }
      else if (n<5)
      {
      for(c=n;c<=5;c++)
      {
       sum+=c*c*c;
                             
       }
       cout<<"your sum is "<<sum;
        }
         
        return 0;
        }


Exercise 7 edit

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
// Author: Faton
//NOTICE: u(n) is a recursive function!

#include <iostream>
using namespace std;

double function (double b){
	if(b==0)
		{return 3;}
	else
		{return (3*function(b-1)+4);}
	}

int main () {
double a;
cout<<"Type a number!\n\n";
cin>>a;
cout<<"\n\nu("<<a<<") equals "<<function(a)<<".\n\n";
system("pause");
}
//Solution by Aldo Ziflaj
#include <iostream>
#include <cmath>
using namespace std;
int f(int n) {
	if (n==0) return 3;
	else return 3*f(n-1)+4;
}

int main() {
	int a;
	cout<<"Enter an integer: ";
	cin>>a;
	cout<<"u("<<a<<")="<<f(a);
	return 0;
}

Solution by Matthewkos - compatible with positive and negative N

//Exercise 7
#include<iostream>
using namespace std;
         int N;
         long double ans;
         long double u (int n){
             long double rec=3;
             if (n>0)
                rec= 3*u(n-1)+4;
             if (n<0)
                rec= (u(n+1)-4)/3; 
             return rec;}
      int main () {
         cout<<"Enter an integer N\t";
         cin>>N;
         ans=u(N);
         cout<<"u(N) =\t"<<ans<<endl;
         system("PAUSE");
         return 0;}

Alternative solutions

//[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]

Solution

#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);
}

Solution #3

// by RyszardRudy
#include <iostream>

using namespace std;

int u( int n ) {
    switch ( n ){
        case 0 : return 1; break;
        case 1 : return 1; break;
        default:  return (u(n - 1)+u(n - 2)) ; break;
    }
}

int main()
{
    int value;
    cout << "Please enter an integer: ";
    cin >> value;
    cout << "The answer is: " << u(value);
    return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The defined u fucntion. It is an integer, because it will return an integer
// Compatible with positive and negative numbers
long int u(long int n)
{
    // If n is under 0
    if (n < 0)
        return (u(n + 1) - 4) / 3;
    // If n is 1 or 0
    else if (n == 0)
        return 3;
    // If n is over 0
    else if (n > 0)
        return 3 * u(n - 1) + 4;
}

// The main function
int main()
{
    // The user input
    long int input;

    // Ask for input
    cout << "Please, enter an integer to calculate with the formula: " << endl;
    cout << "\tu(0)=3" << endl;
    cout << "\tu(n+1)=3*u(n)+4" << endl;
    cout << "$~ ";
    // Receive user input
    cin >> input;

    // If the input is of the wrong kind
    while (cin.fail())
    {
        // Ask for valid input again
        cout << "Please, enter a valid integer: ";
        // Clear the input we had got
        cin.clear();
        // Ignore the new line character
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Get input again
        cin >> input;
    }

    cout << "The result for the integer is " << u(input) << endl;

    return 0;
}

</syntaxhighlight>

/*By : Sebastian Gherhes 04/08/2016
  Using a for loop
*/

#include<iostream>

using namespace std;

int main(){

    int n;
    int func = 0;
    cout<<"Enter a value: "<<endl;

    cin>>n;

    for(int i = 0; i < n; i++){
        if(i == 0){
            func += 3;
        }
        func = 3*func +4;
    }

    cout<<"The result of the computed function is: "<< func <<endl;

    return 0;
}
/* Solving
 * u: N -> N
 * u(0) = 3
 * u(n+1) = 3u(n) + 4
 * gives u(n) = 5*3^n - 2
*/

#include <iostream>
#include <cmath>
using namespace std;

int main() {
	int N;
	cout << "Enter a non-negative integer:" << endl;
	cin >> N;
	cout << "u(" << N << ") = " << 5 * pow(3, N) - 2 << endl;
}


Exercise 8 edit

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

//Solution by Aldo Ziflaj
#include <iostream>
#include <cmath>
using namespace std;
int fib(int n) {
	if (n<=1) return 1;
	else return fib(n-1)+fib(n-2);
}

int main() {
	int a;
	cout<<"Enter an integer: ";
	cin>>a;
	cout<<"u("<<a<<")="<<fib(a);
	return 0;
}

Solution by Matthewkos - compatible with positive and negative N

//Exercise 8
#include<iostream>
using namespace std;int N;
         long double ans;
         long double u (int n){
             long double rec=1;
             if (n>1)
                rec= u(n-1)+u(n-2);
             if (n<0)
                rec= u(n+2)-u(n+1); 
             return rec;}
      int main () {
         cout<<"Enter an integer N\t";
         cin>>N;
         ans=u(N);
         cout<<"u(N) =\t"<<ans<<endl;
         system("PAUSE");
         return 0;}

Alternative solutions

#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

//solution by Tomislav Petrović

#include <iostream>
using namespace std;

int get(int num)
{
    int result;
    switch(num)
        {
        case 0:
            result = 1;
            break;
        case 1:
            result = 1;
            break;
        default:
            result = get(num - 1) + get(num - 2);
            break;
        }
    return result;
}

int main()
{
    int num;
    cout << "type int N: ";
    cin >> num;

    cout << "u(N) = " << get(num);

    return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The defined u fucntion. It is an integer, because it will return an integer
// Compatible with positive and negative numbers
long int u(long int n)
{
    // If n is under 0
    if (n < 0)
        return u(n + 2) - u(n + 1);
    // If n is 1 or 0
    else if (n == 0 || n == 1)
        return 1;
    // If n is over 1
    else if (n > 1)
        return u(n - 1) + u(n - 2);
}

// The main function
int main()
{
    // The user input
    long int input;

    // Ask for input
    cout << "Please, enter an integer to calculate with the formula: " << endl;
    cout << "\tu(0) = 1" << endl;
    cout << "\tu(1) = 1" << endl;
    cout << "\tu(n + 1) = u(n) + u(n - 1)" << endl;
    cout << "$~ ";
    // Receive user input
    cin >> input;

    // If the input is of the wrong kind
    while (cin.fail())
    {
        // Ask for valid input again
        cout << "Please, enter a valid integer: ";
        // Clear the input we had got
        cin.clear();
        // Ignore the new line character
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Get input again
        cin >> input;
    }

    cout << "The result for the integer is " << u(input) << endl;

    return 0;
}

Solution #5

//solution by Farm

#include <iostream>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;

static unsigned long int u ( const unsigned long int n );

int main ( int argc, char ** argv )
{
    unsigned long int n = 0, c = 0;
    string again = "n";

    do
    {
        try
        {
            cout << "Type the integer N to compute u(N): ";
            cin >> n;
            getchar( );

            if ( 0 > n )
                throw 0;

            cout << "The value of u(" << n << ") will be: " << u( n ) << endl;
        }

        catch ( ... )
        {
            cout << "You typed a wrong number!" << endl;
        }

        cout << "Want to try again? [y/N] ";
        c = getchar( );
        again = tolower( c );

    } while ( !again.compare( "y" ) );

    return 0;
}

static void recursiveU ( const unsigned long int n, unsigned long int * vet )
{
    if ( ( 0 == n ) || ( 1 == n ) )
        vet[ n ] = 1;

    else
    {
        if ( 0 != vet[ n - 1 ] )
        {
            if ( 0 == vet[ n - 2 ] )
                recursiveU( n - 2, vet );

            vet[ n ] = vet[ n - 1 ] + vet[ n - 2 ];
        }

        else
        {
            recursiveU( n - 1, vet );
            recursiveU( n - 2, vet );
            vet[ n ] = vet[ n - 1 ] + vet[ n - 2 ];
        }
    }
}

static unsigned long int u ( const unsigned long int n )
{
    unsigned long int value = 0;
    unsigned long int *vet = NULL;

    if ( ( 0 == n ) || ( 1 == n ) )
        value = 1;

    else
    {
        vet = ( unsigned long int * ) calloc ( n + 1, sizeof( unsigned long int ) );
        recursiveU( n, vet );
        value = vet[ n ];
        free( vet );
    }

    return value;
}


Exercise 9 edit

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
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
  int n;
  while(true){
    cin >> n;
    if (n < 0 || n > 20)
      cout << "ERROR" << endl;
    else{
      cout << n << " + 17 = " << n + 17 << endl;
      break;
    }
  }
  return 0;
}

Made by: Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i,n,p=1;

main(){
clrscr();
while(p==1){
	cout<<"Enter a number: ";cin>>n;
	if(n>-1&&n<21){
		n+=17;
		cout<<"Your number + 17 is "<<n;
		p=0;
	}
        else{
                cout<<"ERROR\n";
        }

}
getche();
return 0;
}
// Solution by adel_deli

#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Enter a number between 0 and 20: ";
    cin >> num;

    while ( num < 0 || num > 20) {
            cout <<"ERROR, Invalid value. Enter a valid value: ";
            cin >> num;
    }

    int sum;

    sum = num + 17;

    cout <<"Sum of the "<< num<< " + 17 = "<< sum;
    return 0;
}
#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;
}
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
void fx();

int main()
{
    fx();

}
void fx(){
    int n;
    cin>>n;
    if (0<=n && n<=20) {
        cout<<n+17<<endl;
        
    }
    else
    {
        cout<<"error"<<endl;
        fx();
        
    }
}
//Solution provided by Neeraj Morar
#include <iostream>

using namespace std;

int main()
{
	while (true) {
		int N;

		cout << "Type an integer between 0 and 20 (both included): ";
		cin >> N;

		if (N >= 0 && N <= 20) {
			cout << "\n";
			N += 17;
			cout << N;
			cout << "\n";
			cout << "\n";
			break;
		} else {
			cout << "\n";
			cout << "ERROR";
			cout << "\n";
			cout << "\n";
		}
	}

	system("PAUSE");
}

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"); 
}
//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;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The main function
int main()
{
    // The user input
    int input;

    // Ask for user input
    cout << "Please, enter a valid integer between 0 and 20, included (range "
         << "[0, 20]): ";
    // Get the user input
    cin >> input;

    // Error checking. Check if the input is valid AND if it is inside the range
    while (cin.fail() || input < 0 || input > 20)
    {
        // Show the ERROR message that the exercise asks for
        cout << "ERROR" << endl;
        // Ask for valid input again
        cout << "$~ ";
        // Clear the old input
        cin.clear();
        // Ignore the new line
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Get the input again
        cin >> input;
    }

    cout << input << " + 17 = " << input + 17 << endl;

    return 0;

====================================================================================================================

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int n,sum=0;
cout<<"Enter a number between 0 and 20: ";

cin>>n;

if(n>20)
{

    while(n>20)
    {
      if(n>20)
      {
        cout<<"ERROR!!! type another value"<<endl;
      }
      cout<<"Enter a number between 0 and 20: "<<endl;
      cin>>n;
    }
}

if(n<=20)
{
    sum=n+17;

    cout<<"the number you have typed "<<n<<" +17 = "<<sum<<endl;
}

return 0;
}
}
// Excercise 9 by Alexander Christensen

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
	system("cls");
	cout << "\nWrite an integer between 0 and 20 (both included): ";
	int n;
	cin >> n;

	while(cin.fail() || n < 0 || n > 20)
	{
		cin.clear();
		cin.ignore(256, '\n');
		cout << "n was not a proper input. Please try again: ";
		cin >> n;
	}

	cout << n << " + 17 = " << (int)(n+17) << "\n";

	return 0;
}


Exercise 10 edit

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
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
  int n, op = 0;
  cout << "Enter with an integer: ";
  cin >> n;
  while(op != 4){
    cout << "1. Add 1\n2. Multiply by 2\n3. Subtract 4\n4. Exit" << endl;
    cout << "Opt: ";
    cin >> op;
    switch (op) {
      case 1:
        cout << "\n" << n << " + 1 = " << n++ << "\n" << endl;
        break;
      case 2:
        cout << "\n" << n << " * 2 = " << n*2 << "\n" << endl;
        break;
      case 3:
        cout << "\n" << n << " - 4 = " << n - 4 << "\n" << endl;
        break;
      case 4:
        return 0;
      default:
        cout << "Invalid option, try again" << endl;
        break;
      }
  }
  return 0;
}
//Made by Michael C
#include <iostream>

int main ()
{
    double number; // for accuracy;
    int variant;

    std::cout << "Enter the number: ";
    std::cin >> number;
    std::cout << "\n";
    std::cout << "Please choose an action from the below table \n";
    std::cout << "1. Add 1 \n";
    std::cout << "2. Multiply by 2 \n";
    std::cout << "3. Subtract 4 \n";
    std::cout << "4. Quit 1 \n\n";
    do
    {
        std::cout << "Enter the action number : "; std::cin >> variant;

        if (variant == 1)
        {
            number += 1;
            std::cout << "Output: " << number << std::endl;
        }
        else if (variant == 2)
        {
            number *= 2;
            std::cout << "Output: " << number << std::endl;
        }
        else if (variant == 3)
        {
            number /= 4;
            std::cout << "Output: " << number << std::endl;
        }
        else if (variant == 4)
        {
            return 0;
        }
    }
    while (variant != 4);
 
   return 0;
}

Made by: Reiz Troy D. Durante</br>
<syntaxhighlight lang=cpp>
#include<iostream.h>
#include<conio.h>

int i,j,n,p;

main(){
clrscr();

cout<<"Enter an integer: ";
cin>>n;

while(p!=4){
clrscr();
cout<<"Your number: "<<n<<"\n\nSelect and enter the number of your desired operation:\n1. Add 1\n2.Multiply by 2\n3. Subract 4\n4. Quit\nOperation: ";
cin>>p;

	switch(p){
		case 1:{n++;break;}
		case 2:{n*=2;break;}
		case 3:{n-=4;break;}
		default:{break;}
	}
}
getche();
return 0;
}

Solution by Matthewkos

//Exercise 10
#include<iostream>
using namespace std;
      int input[2];
      int main(){
          cout<<"Enter an integer:\t";
          cin>>input[0];
          cout<<"Menu\n1. Add 1\n2. Multiply by 2\n3. Subtract 4\n4. Quit"<<endl;
          cin>>input[1];
          do switch (input[1]){
                    case 1:input[0]++;break;
                    case 2:input[0]*=2;break;
                    case 3:input[0]-=4;break;
                    case 4:exit(0);break;
                    default:cout<<"Invalid value, input again!"<<endl;}
          while (!(input[1]>=1 and input[1]<=4));
          cout<<"Answer =\t"<<input[0]<<endl;
          system("PAUSE");
          return 0;}
//solution by adel deli

#include <iostream>

using namespace std;

int main()
{
                                            //ask the user to input number
    int inNum, optNum;
    while (optNum >= 1 || optNum <= 4) {    //repeat asking loop
    cout << "Please Enter an Integer: ";
    cin >> inNum;

                                            //ask the user what should happens to the integer
    cout << "What do you want to do with "<< inNum << "?"<< endl;

    cout <<"1. Add 10"<< endl;
    cout <<"2. Multiply by 2"<< endl;
    cout <<"3. Subtract 4"<< endl;
    cout <<"4. Quit"<< endl;

    cout <<"Enter an option: ";
    cin >> optNum;

                                            //action between 1 to 4
    int result;

    while (optNum < 1 || optNum > 4) {
            cout << "ERROR!, You've entered invalid number, Try again."<<endl;
            cin >> optNum;
    }

    if (optNum == 1) {
            result = inNum + 10;
            cout << "You've choosed option 1."<< endl;
            cout << inNum << " + 10 = "<< result<< endl;
    }
    else if (optNum == 2) {
            result = inNum * 2;
            cout << "You've choosed option 2."<< endl;
            cout << inNum << " x 2 = "<< result<< endl;
    }
    else if (optNum == 3) {
            result = inNum - 4;
            cout << "You've choosed option 3."<< endl;
            cout << inNum << " - 4 = "<< result<< endl;
    }
    else if (optNum == 4) {
        return 0;cout << "ERROR!, You've entered invalid number, Try again."<<endl;
            cin >> optNum;
    }

    }

    return 0;
}

Alternate Solution

//solution by Ahmed Samir
//using while loop and if

#include <iostream>

using namespace std;

main()

{
    int number;

    char choice;

    cout << "Enter a integer number.\n\n";

    cin >> number;

    cout <<endl
         <<"1. Add 1\n\n"
         <<"2. Multiply by 2\n\n"
         <<"3. Subtract 4\n\n"
         <<"4. Quit\n\n"
         <<"Whats your choice?\n\n";

    cin >> choice;

    while ((choice=='1')||(choice=='2')||(choice=='3'))
    {

        if(choice=='1')
        {
            number+=1;
        }

        if(choice=='2')
        {
            number*=2;
        }

        if(choice=='3')
        {
            number-=4;
        }

        cout << endl
             <<"The number is now: " << number <<endl<<endl
             <<"1. Add 1\n\n"
             <<"2. Multiply by 2\n\n"
             <<"3. Subtract 4\n\n"
             <<"4. Quit\n\n"
             <<"Whats your choice?\n\n";

        cin >> choice;

    }

        if( (choice!='4') && (choice!='3') && (choice!='2') && (choice!='1'))
           {
               cout << "\aUn recognized choice.. Plz try again !!\n\n";

               main();
           }
    cout << "Finaly the number is:" << number;
}
#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;
     
}
//Solution provided by Neeraj Morar
#include <iostream>

using namespace std;

int main()
{
	while (true) {
		int n;
		int menu;

		cout << "Type in an integer: ";
		cin >> n;
		cout << "\n";
		cout << n << "\n";
		cout << "\n";
		cout << "1. Add 1\n";
		cout << "2. Multiply by 2\n";
		cout << "3. Subtract 4\n";
		cout << "4. Quit\n";
		cout << "\n";
		cout << "Choose an option: ";
		cin >> menu;
        cout << "\n";
		if (menu == 1) {
			n += 1;
			cout << n << "\n";
			cout << "\n";
		} else if (menu == 2) {
			n *= 2;
			cout << n << "\n";
			cout << "\n";
		} else if (menu == 3) {
			n -= 4;
			cout << n << "\n";
			cout << "\n";
		} else if (menu == 4) {
			break;
		} else {
			cout << "Please type in a valid option.\n";
			cout << "\n";
		}
	}
}

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>

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 !";
			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();
		
}

Solution

/* 
Solution
Author: Lukaskuko
*/

#include <iostream>

using namespace std;

int main()
{
    int x,choose;
    cout << "Choose your desired number.\n\n";
    cin >> x;
    cout << "\n1.Add 1\n2.Multiply by 2\n3.Substract 4\n4.Quit\n";
    cin >> choose;
    getchar();
    
    if(choose == 1) { x+=1; cout << "x = " << x; } else {
              if(choose == 2) { x*=2; cout << "x = " << x; } else {
                        if(choose == 3) { x-=4; cout << "x = " << x; } else {
                                   if(choose == 4) { } else {
                                             cout << "Wrong number.Choose again.\n"; main(); } } } }
    
    cout << "\n";
    getchar();
    return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

void drawMenu()
{
    // The menu
    cout << "*****************************************************" << endl;
    cout << "* Choose an entry from 1 to 4.                      *" << endl;
    cout << "*    [1] Add 1                                      *" << endl;
    cout << "*    [2] Multiply by 2                              *" << endl;
    cout << "*    [3] Substract 4                                *" << endl;
    cout << "*    [4] Quit                                       *" << endl;
    cout << "*****************************************************" << endl;
}

// The main function
int main()
{
    // The user input
    int input;
    // Ask for user input
    cout << "Write an integer number: ";
    // Get the user input
    cin >> input;

    // Error checking. Check if the input is valid
    while(cin.fail())
    {
        // Ask for valid input
        cout << "Write a valid integer number: ";
        // Clear the input we had
        cin.clear();
        // Ignore the new line
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Get the new input
        cin >> input;
    }

    // We can simply create a "game" loop for this application
    bool quit = false; // We haven't quitted yet
    do
    {
        // The user choice
        int choice;

        // Print the menu
        drawMenu();
        // Get the user choice
        cin >> choice;

        // Error check again. Include the fact that the number has to be 1-4
        while(cin.fail() || choice < 1 || choice > 4)
        {
            cout << endl << "Choose a correct entry from 1 to 4 (with numbers)"
                 << endl << endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            // Draw the menu again
            drawMenu();
            cin >> choice;
        }

        // Check the choice we have received
        switch (choice)
        {
        case 1: // If the choice is 1
            cout << endl << input << " + 1 = " << input + 1 << endl << endl;
            break;
        case 2:
            cout << endl << input << " * 2 = " << input * 2 << endl << endl;
            break;
        case 3:
            cout << endl << input << " - 4 = " << input - 4 << endl << endl;
            break;
        case 4:
            quit = true;
            break;
        default:
            break;
        }
    } while (!quit); // Keep looping forever, until we quit

    // Say goodbye, be polite
    cout << endl << "Shutting down. Hope I'll see you soon!" << endl << endl;

    return 0;
}
int main()
{
	int choice, input;
	cout << "Enter integer: ";
	cin >> input;
	while (true)
	{
		cout << "Choose one of the following operations for your integer:\n"
			<< "1. Add one\n"
			<< "2. Multipky by two\n"
			<< "3. Subtract four\n"
			<< "4. Quit\n"
			<< "Your choice: ";
		cin >> choice;
		switch (choice)
		{
			case 1: { input++; break; }
			case 2: { input *= 2; break; }
			case 3: { input -= 4; break; }
			case 4: { cout << "Godbye! :)"; return 0; }
			default: { break; }
		}
		cout << endl << "Answer: " << input << endl << endl;
	}
	return 0;
}
// By Sebastian Gherhes
#include<iostream>

using namespace std;

int add(int n){
    return n+1;
}

int multiply(int n){
    return n*2;
}

int subtract(int n){
    return n-4;
}

int main(){

    int option, n;
    cout<<"Type the integer representing the function you want: "<<endl;
    cout<<"1. Add by 1"<<endl;
    cout<<"2. Multiply by 2"<<endl;
    cout<<"3. Subtract by 4"<<endl;
    cout<<"4. Quit"<<endl;

    do{
        cout<<"Enter the number: "<<endl;
        cin>> option;

        if(option == 1){
            cout<<"Enter an integer: "<<endl;
            cin>>n;
            cout<<add(n)<<endl;
        }
        if(option == 2){
            cout<<"Enter an integer: "<<endl;
            cin>>n;
            cout<<multiply(n)<<endl;
        }
        if(option == 3){
            cout<<"Enter an integer: "<<endl;
            cin>>n;
            cout<<subtract(n)<<endl;
        }

        if (option == 4){
            cout<<"Goodbye!"<<endl;
            break;
        }
    }while(true);

    return 0;
}


Exercise 11 edit

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
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
  int n, sum = 0, i = 0;
  cout << "Type 0 to stop!" << endl;
  while(true){
    cout << "Type a positive integer: ";
    cin >> n;
    if (n < 0) cout << "ERROR" << endl;
    else if (n > 0){
      sum += n;
      i++;
    }
    else{
      if (sum == 0) cout << "NO AVERAGES" << endl;
      else          cout << "avg: " << sum/i << endl;
      break;
    }
  }
  return 0;
}

Made by: Reiz Troy D. Durante

#include&l5iostream.h>
#include<conio.h>

int i,n,p;

main(){

clrscr();

do{
	cout<<"0 to end\nEnter a positive integer: ";
	cin>>n;

	if(n>0){p+=n;i++;}
	if(n<0){cout<<"ERROR\n";}
}while(n!=0);

if(i!=0){p/=i;cout<<"AVERAGE: "<<p;}
else{cout<<"NO AVERAGE";}

getche();
return 0;
}

//Solution by Matthewkos

//Exercise 11
#include<iostream>
using namespace std;
      float avg,sum=0;
      int input=true,loop;
      int main(){
          for (loop=0;input!=0;) {
              do{
                 cout<<"Enter a POSITIVE Integer ";
                 cin>>input;}
              while (input<0);   
              if (input==0 && loop==0) {
                 cout<<"NO AVERAGE!"<<endl;
                 system("PAUSE");
                 exit(0);}
              sum+=input;
              loop++;}
          avg=sum/(loop-1);
          cout<<"Average =\t"<<avg<<endl;
          system("PAUSE");
          return 0;}
// EXERCISE 11 - Solution 1

#include <iostream>
using namespace std;
void main()
{
	double num,total=0,b=0;
	do
	{
	cout<<"enter the num ; ";
		cin>>num;

		if(num>0)
		{
			total+=num;
		b++;}
		else if(num<0)
		{
			cout<<"wrong number";
			cout<<endl;
		}

		if((num==0)&&(b==0))
		{
			cout<<"NO Ave\n";}

	}while(num!=0);
	if(num==0&&b!=0)
	{
		cout<<"Ave =";
		cout<<total/b;}
	cout<<endl;}
			

// EXERCISE 11 - Solution 2

#include <iostream>

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";
			return;
		} else if (num != 0) {
		sum += num;
		i++;
		}
	}
	if (sum != 0)
		cout << "Average: " << sum / i;
	else
		cout << "No average";
}

// 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>

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);
}
// 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;
}
#include <iostream>
using namespace std;
void main()
{
	double num,total=0,b=0;
	do
	{
	cout<<"enter the num ; ";
		cin>>num;

		if(num>0)
		{
			total+=num;
		b++;}
		else if(num<0)
		{
			cout<<"wrong number";
			cout<<endl;
		}

		if((num==0)&&(b==0))
		{
			cout<<"NO Ave\n";}

	}while(num!=0);
	if(num==0&&b!=0)
	{
		cout<<"Ave =";
		cout<<total/b;}
	cout<<endl;}
//By David J
#include <iostream>

using namespace std;

int main()
{
    int ival, cnt = 0;
    double sum = 0;
    do
    {
        cout << "Enter a positive integer (Type 0 to finish): " << endl;
        try_loop:
            cin >> ival;
        if (ival > 0)
        {
            sum += ival;
            cnt++;
        }
        if ((ival == 0) && sum > 0)
        {
            cout << "Average of entered integers = " << (sum / cnt);
            break;
        }
        else if ((ival == 0) && sum <= 0)
        {
            cout << "No average." << endl;
            break;
        }
        while (ival < 0)
        {
            cerr << "ERROR, an integer must be positive number. try again\n";
            goto try_loop;
        }
    } while (ival >= 0);

    return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits
#include <vector> // Use vectors for unknown array size

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The main function
int main()
{
    // Explain the program to the user
    cout << "Please, enter numbers to calculate the average. Write a 0 to stop "
         << "adding numbers." << endl;

    // Follow how many integers have been entered and initialize it
    int numberOfIntegers = 0;
    // The user input
    long int input;
    // The numbers that the user added
    vector<int> numbers;

    // Keep asking for numbers while the user hasn't written a 0
    do
    {
        // Ask for user input. Add one to the numberOfIntegers so that it
        // asks from number 1 and not 0, which would be more user friendly
        cout << "Number " << numberOfIntegers + 1 << ": ";
        // Get the user input
        cin >> input;

        // Error checking. Make sure the input is valid. Make sure the number is
        // over 0
        while (cin.fail() || input < 0)
        {
            // Ask for valid input
            cout << "Number " << numberOfIntegers + 1
                 << " (enter a valid positive integer): ";
            // Clear the input we had
            cin.clear();
            // Ignore the new line
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            // Get the input again
            cin >> input;
        }

        // If the input is 0
        if (input == 0)
            break; // Exit from the loop
        else // Otherwise
            numbers.push_back(input); // Add a new value to the vector

        // Increase the number of integers
        numberOfIntegers++;
    } while (1); // Loop forever until we break from it

    // Change the size of the vector to the number of integers
    // We have to add one because numberOfIntegers starts at 0, not 1,
    // so if the numberOfIntegers is 2, that means the numbers will be 0 and 1,
    // but the size should still be 2 (it's an array, starts at 0)
    numbers.resize(numberOfIntegers + 1);

    // If there is no numbers...
    if (numberOfIntegers == 0)
        // Show the message we have been asked to show in the exercise
        cout << "NO AVERAGE" << endl;
    else // If there are numbers...
    {
        // The sum
        int sum;
        // Sum every number
        // Since we are using i < numberOfIntegers, we avoid recording and using
        // the number 0 when the user wants to stop adding numbers. This way
        // the sum is correct, as well as the average
        for (int i = 0; i < numberOfIntegers; i++)
            sum += numbers.at(i); // Sum every number in the vector to the same variable

        // Make the average. Average numbers tend to be decimal, so cast the
        // result into a float
        float average = (float)sum / (float)numberOfIntegers;
        cout << "The average is: " << average << endl;
    }

    return 0;
}


Exercise 12 edit

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
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int foo(int n){
  if (n == 0) return 3;
  if (n == 1) return 2;
  return n * foo(n-1) + (n+1) * foo(n-2) + n;
}
int main(int argc, char const *argv[]) {
  int n;
  cin >> n;
  cout << foo(n) << endl;
  return 0;
}

Solution by Matthewkos

//Exercise 7
#include<iostream>
using namespace std;
      int N;
      long double ans;
      long double u (int n){
           long double rec;
           if (n==0)
              rec=3;
           if (n==1)
              rec=2;
           if (n>1)
              rec=n*u(n-1)+(n+1)*u(n-2)+n;
           if (n<0)
              rec=(u(n+2)-(n+2)-(n+2)*u(n+1))/(n+3); 
           return rec;}
      int main () {
          cout<<"Enter an integer N\t";
          cin>>N;
          ans=u(N);
          cout<<"u(N) =\t"<<ans<<endl;
          system("PAUSE");
          return 0;}

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;
}
// by siwers17
#include <iostream>

int f(int x){
    if(x==0 || x==1){
        if(x == 0){
            return 3;
        }
        if(x == 1){
            return 2;
        }
    }
    else{
        return x*f(x-1)+(x+1)*f(x-2)+x;
    }
}

int main(){
    int n;
    std::cout << "Enter an integer: " << std::endl;
    std::cin >> n;
    std::cout << std::endl << "Result: " << f(n);
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The defined u fucntion. It is an integer, because it will return an integer
// Compatible with positive and negative numbers
long double u(int n)
{
    // If n is under 0
    if (n < 0)
        return (u(n + 2) - (n + 2) - (n + 2) * u(n + 1)) / (n + 3);
    // If n is 1
    else if (n == 0)
        return 3;
    // If n is 1
    else if (n == 1)
        return 2;
    // If n is over 1
    else if (n > 1)
        return n * u(n - 1) + (n + 1) * u(n - 2) + n;
}

// The main function
int main()
{
    // The user input
    int input;

    // Ask for input
    cout << "Please, enter an integer to calculate with the formula: " << endl;
    cout << "\tu(0) = 3" << endl;
    cout << "\tu(1) = 2" << endl;
    cout << "\tu(n) = n * u(n - 1) + (n + 1) * u(n - 2) + n" << endl;
    cout << "$~ ";
    // Receive user input
    cin >> input;

    // If the input is of the wrong kind
    while (cin.fail())
    {
        // Ask for valid input again
        cout << "Please, enter a valid integer: ";
        // Clear the input we had got
        cin.clear();
        // Ignore the new line character
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // Get input again
        cin >> input;
    }

    cout << "The result for the integer is " << u(input) << endl;

    return 0;
}


Exercise 13 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
  int n, biggest, ocurr = 0;
  cin >> n;
  biggest = n;
  for(int i = 0; i < 9; i++){
    cin >> n;
    if (n > biggest) biggest = n;
    if (n == biggest) ocurr++;
  }
  cout << "biggest value is " << biggest << " with " << ocurr << " occurrences" << endl;
  return 0;
}

Made by: Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i,n,p=-2147483648,k[10];

main(){

while(i<10){
	clrscr();
	cout<<"Enter 10 integers: ";
	cin>>n;

	if(n>p){p=n;}
	k[i]=n;
	i++;
}

n=0;
for(i=0;i<10;i++){
	if(k[i]==p){
		n++;
	}
}
clrscr();
cout<<"The biggest number "<<p<<" was entered "<<n<< " times.";

getche();
return 0;
}

//Solution by Matthewkos

//Exercise 13
#include<iostream>
using namespace std;
      int input[9],maxs=INT_MIN;
      int main() {
          cout<<"Enter 10 integers"<<endl; 
          for (int loop=0;loop<=9;loop++){
              cin>>input[loop];
              if (input[loop]>maxs)
                 maxs=input[loop];}
          cout<<"The maximum is\t"<<maxs<<endl;
      system("PAUSE");
      return 0;}
#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<<"\noccurence 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>

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 << " \nOccurence: " << occur << endl;
system("pause");
}
//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 occurence of the largest integer " << n << " is: " << iCount << endl;

return ERR_NONE;
}
#include <iostream>
using namespace std;

int main ()
{
    int num[10], max, freq=0;
    cout << "Enter ten integers: " << endl;
    for (int i=0;i<=9;i++)
    {
        cin >> num[i];
    }
    max=num[0];
    for (int i=1;i<=9;i++)
    {
        if (num[i]>max) max=num[i];
    }
    for (int i=0;i<=9;i++)
    {
        if (num[i]==max)
        {
            num[i]=1;
            freq += num[i];
        }
    }
    cout << "The greatest value is " << max << ". Its frequency is " << freq << "." << endl;
    return 0;
}
// By Víctor Matía Rodríguez, Spain <vmatir@gmail.com>
#include <iostream> // cout, cin
#include <limits> // numeric_limits

using namespace std; // Avoid having to use std::cout, std::cin, etc

// The main function
int main()
{
    // The user input
    int input;
    // The numbers the user has input. We know it'll be 10 integers
    int numbers[10];

    // Loop until we have entered 10 numbers
    for (int i = 0; i < 10; i++)
    {
        // Ask for user input
        cout << "Please, enter the integer number " << i + 1 << ": ";
        // Get the user input
        cin >> input;

        // Error checking
        while (cin.fail())
        {
            // Ask for valid input
            cout << "Please, enter a valid integer number for the integer "
                 << "number " << i + 1 << ": ";
            // Clear the input
            cin.clear();
            // Ignore the new line
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            // Get the new input
            cin >> input;
        }

        // Put the received input into the corresponding array place
        numbers[i] = input;
    }

    // Check which number is the biggest one and if it is repeated
    int biggest = numbers[0]; // Set the first number to the smallest one as default
    int repeats = 0; // Initialize the variable
    // Do it looping through each value of the array. sizeof(numbers) is the
    // size in bytes, if we do sizeof(array) / sizeof(array[0]) we get the
    // size in the form of a simple integer (how many integers are there?)
    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        // If the number is bigger than the biggest number,
        // set it as the biggest one
        if (numbers[i] > biggest)
            biggest = numbers[i];
        // If the number is repeated, add it to the repeats
        if (numbers[i] == biggest)
            repeats++;
    }

    // Inform the user of the results
    cout << "The biggest number you have entered is " << biggest << ", and you "
         << "have entered it " << repeats << " times." << endl;

    return 0;
}


Exercise 14 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

int fact(int n){
  if (n == 0 || n == 1) return 1;
  return n * fact(n-1);
}

int main(int argc, char const *argv[]) {
  int n;
  cin >> n;
  if (n < 0){
    cout << "the number typed is not a positive integer" << endl;
    return 0;
  }
  cout << n << "! = " << fact(n);
}

//Made by Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i,n,p=1;

main(){
clrscr();
cout<<"Enter a number: ";
cin>>n;

for(i=1;i<=n;i++){p*=i;}

cout<<"Factorial of "<<n<<" is "<<p;

getche();
return 0;
}

//Solution by Matthewkos

//Exercise 14
#include<iostream>
using namespace std;
      int x,ans;
      int f(int n){
          int rec=1;
          if (n>1)
             rec=n*f(n-1);
          return rec;}
      int main(){
          cout<<"Enter a positive integer X\t";
          cin>>x;
          ans=f(x);
          cout<<x<<"! =\t"<<ans<<endl;
          system("PAUSE");
          return 0;}

Alternate Solutions

//Solution by adel_deli
#include <iostream>

using namespace std;

int main()
{
    int num;

    cout << "Enter a number: ";
    cin >> num;

    long fact = 1;

    for (int i = 1; i <= num; i++) {
            fact *= i;
    }

    cout <<"!"<< num<< "= "<< fact;

    return 0;
}
#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>

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;
}
#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);
}
//Solution by Neeraj Morar
#include <iostream>

using namespace std;

int main()
{
    unsigned long long int N, n;

    while (true) {

        cout << "Type in an integer: ";
	cin >> N;
	n = N - 1;

	for (; n >= 1; n--) {
	    N = N * n;
	}

	cout << "\n" << N << "\n";
	cout << "\n";
	}

    system("PAUSE");
}


Exercise 15 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

bool prime(int n){
  if (n == 1) return false;
  int mod;
  bool check = true;
  for(int i = 2; i <= n; i++){
    mod = n % i;
    if (mod == 0 && i != n)
      check = false;
  }
  return check;
}

int main(int argc, char const *argv[]) {
  int n;
  cin >> n;
  if (prime(n))  cout << n << " is a prime number" << endl;
  else           cout << n << " is not a prime number" << endl;
}
//Rami Alkubaty's solution

#include<iostream>

using namespace std;

int main(){
  
int number;
   
int prime = 2;
    
bool found = false;
   
cout << "Enter a number: ";
   
cin >> number;
   
for (; prim<=number-1;prime++){
       
         if(number%prime !=0){
             
               found = true;
             }
             
         else{
             
               found = false;
               
               break;
               
               
               }
             
               
             
             }
         
    if (found){
           
           cout << "Number = "<<number<<" is a prime number";
                   
           }
          
        else {cout << "Number = "<<number<<" is a not prime number";}   
         
     
    }

// Made by: Engineer Reiz Troy D. Durante
Please visit my site: ccphplusplus.blogspot.com

#include<iostream.h>
#include<conio.h>

int n;

main(){
clrscr();

cout<<"Enter an integer: ";
cin>>n;

if(n>7&&n%2!=0 && n%3!=0&& n%5!=0 && n%7!=0){
	cout<<"The number you've entered is a prime number.";
       }
else if(n<8&&n!=1&&n!=4&&n!=6){
	cout<<"The number you've entered is a prime number.";
       }
else{
	cout<<"The number you've entered is not a prime number.";
    }
getche();
return 0;
}

//Solution by Matthewkos

//Exercise 15
#include<iostream>
using namespace std;
      int input,loop,quo=1;
      int main(){
          cout<<"Enter a nutral integer N\t";
          cin>>input;
          for (loop=2;loop<input;loop++){
              quo=input%loop;
              if (quo==0) break;}
          cout<<"It is ";
          (quo==0) ? cout<<"not a ": cout<<"a ";
          cout<<"prime number"<<endl;
          system("PAUSE");
          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>

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";
}

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;
}

Example 7

#include <iostream>
using namespace std;
int main() {
    start:
        int a,x;
        cout << "Enter a number: ";
        cin >> a;
        if (a%2==1 && a>1 || a==2) {
            for (x=3; x<=a/x; x+=2){            
                if (a%x==0)
                    goto no;              
                }
            goto yes;
            }
        else
            goto no;   
    yes:
        cout << a << " is a prime."<< endl;
        goto start;
    no:
        cout << a << " is not a prime." << endl;
        goto start;
    return 0;            
}

Solution #8

/*Using square root makes this a lot easier.
  You only have to check the numbers up to
  a numbers square root when looking for posible divisors.
*/

#include <iostream>
#include <cmath> //To be able to use sqrt()

using namespace std;

int main()
{
    cout << "Prime check" << endl;
    cout << "Enter an integer: ";

    bool isPrime = true;
    int value = 0;
    cin >> value;

    if (value < 2)
    	isPrime = false;
    
    //Only have to check up to the values square root.
    for (int i = 2; i <= sqrt(value) && isPrime; i++)
    {
 	if (value%i == 0)
            isPrime = false;
    }

    cout << "Entered value is" << (isPrime ? "" : " not") << " a prime number." << endl;
}

Solution #9 with recursive method

#include <iostream>
#include <String>

using namespace std;

string isPrime (int in )
{
	static int i =2 ;
	if ( i < in )
	{
		if ( in % i == 0)
			return "Not Prime Number" ;
		else
		{
			i++;
			return isPrime (in); 
		}
		
	}
	return "Prime Number" ;
}

int main()
{
int in ;

cout << "Enter an integer : ";
cin >> in ;
cout << in << " is " << isPrime (in) << endl ;
	// wait for user response to exit
	system("pause");
	return 0;
}


Exercise 16 edit

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
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

bool prime(int n){
  if (n == 1) return false;
  int mod;
  bool check = true;
  for(int i = 2; i <= n; i++){
    mod = n % i;
    if (mod == 0 && i != n)
      check = false;
  }
  return check;
}

int main(int argc, char const *argv[]) {
  int n, cont = 0;
  cin >> n;
  for(int i = 2; i <= n; i++){
    if(prime(i)) cont++;
  }
  if (cont > 0)  cout << "has "<< cont << " prime numbers lesser or equal to " << n << endl;
  else           cout << "havent any prime numbers lesser or equal to " << n << endl;
}

//Made by: Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i, j, k, n, p[4]={2, 3, 5, 7};

void main(){
clrscr();
cout<<"Enter an integer: ";
cin>>n;
for(i=0;i<4;i++){
	if(p[i]<n){cout<<p[i]<<"\t";}
}
for(i=2;i<=n;i++){
	for(j=0;j<4&&k==0;j++){
		if(i%p[j]==0){k=1;}
	}
	if(k==0){cout<<i<<"\t";}
	k=0;
}
getche();
}

//Solution by Matthewkos

//Exercise 16
#include<iostream>
using namespace std;
      int input,loop[2],quo;
      int main(){
          cout<<"Enter a netural number ";
          cin>>input;
          cout<<"Prime number >=\t"<<input<<" are:"<<endl;
          for (loop[0]=1;loop[0]<=input;loop[0]++){
              for (loop[1]=2;loop[1]<loop[0];loop[1]++){
                  quo=loop[0]%loop[1];
                  if (quo==0) break;}
              if (quo!=0 ||loop[0]==1 ||loop[0]==2) cout<<loop[0]<<"\t";}
          cout<<endl;
          system("PAUSE");
          return 0;}

Alternate Solutions

#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;
}

Solution #4

/* A solution using whats called "sieve of eratosthenes".
*/

#include <iostream>
#include <cmath>

using namespace std;

bool* findPrimes(int n)
{
    bool* primes = new bool[n];
    //0 and 1 are not prime
    primes[0] = false; 
    primes[1] = false;
    //Set all others to true
    for (int i = 2; i <= n; i++)
	primes[i] = true;
    //"Sieve of eratosthenes"
    for (int i = 2; i <= sqrt(n); i++)
    {
	if (primes[i])
	{
	    for (int j = i*2; j <= n; j += i)
	    {
		primes[j] = false;
	    }
	}
    }
    return primes;
}

int main()
{
    cout << "Enter an integer: ";
    int value = 0;
    cin >> value;

    bool* primes = findPrimes(value);

    for (int i = 1; i <= value; i++)
		cout << i << " is " << (primes[i] ? "" : "not") << " a prime number" << endl;
    return 0;
}

Solution #5

#include <iostream>

bool is_prime(int n)
{
	for (int i = 2; i < n; i++)
	{
		if ((n % i) == 0)
		{
			return false;
		}
	}
	
	return true;
}

int main()
{		
	int temp = 0;
	
	std::cout << "Enter an integer: ";
	std::cin >> temp;
	
	for (int i = 2; i <= temp; i++)
	{
		if (is_prime(i))
		{
			std::cout << i << std::endl;
		}
	}
	
	return 0;
}


Exercise 17 edit

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

Solution
/**
* @author Luiz Erivan M. S. Filho
*/
#include <iostream>
using namespace std;

bool prime(int number){
  if (number == 1) return false;
  int mod;
  for(int i = 2; i <= number; i++){
    mod = number % i;
    if (mod == 0 && i != number)
      return false;
  }
  return true;
}

int main(int argc, char const *argv[]) {
  int n, i = 2, count = 0, last = 0;
  cin >> n;

  if (n == 0) return 0;

  for(int j = count; count < n; j++){
    bool check = prime(i);
    if(check == true){
      last = i;
      count++;
    }
    i++;
  }

  cout << "#" << n << " prime number is " << last;

}

Solution by Matthewkos

//exercise 17
#include<iostream>
using namespace std;
      int input,loop[2],counter,quo;
      bool prime;
      int main(){
          cout<<"Enter a netural number ";
          cin>>input;
          for (counter=0,loop[0]=1;counter<input;loop[0]++){
              for (loop[1]=1;loop[1]<=loop[0];loop[1]++){
                  quo=loop[0]%loop[1];
                  prime=!(quo==0 && (loop[0]/loop[1])!=loop[0] && (loop[0]/loop[1])!=1); 
                     if (! prime) break;}
              if (prime) counter++;}
          cout<<"The "<<input;
          switch (loop[0]%10){
                 case 1: cout<<"st";break;
                 case 2: cout<<"nd";break;
                 case 3: cout<<"rd";break;
                 default:cout<<"th";}    
          cout<<" prime number is\t"<<loop[0]-1<<endl;
          system("PAUSE");
          return 0;}

// solution by Cyrex1337

#include <iostream>
#include <string>

int PrimeByIndex( size_t idx )
{
	auto nPrime = 1;
	for ( auto i = 2;; ++i )
	{
		auto isPrime = true;

		if ( nPrime == idx )
			return i - 1;

		if ( idx == 2 )
			return 3;

		if(i > 2)
		{
			for ( auto j = 2; j < i; ++j )
			{
				if ( i % j == 0 )
				{
					isPrime = false;
					break;
				}
			}

			if ( isPrime )
				++nPrime;
		}
	}
}

int main( )
{
	auto primeIndex = -1;
	std::cout << "Prime number index: ";
	std::cin >> primeIndex;

	if ( primeIndex < 1 )
		std::cout << "[ERROR] An invalid index has been entered!" << std::endl;

	auto prime = PrimeByIndex( primeIndex );
	std::cout << "Prime at " << primeIndex << " is " << prime << std::endl;
}

Alternate Solutions

#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;
}


Exercise 18 edit

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>
#include <string>
using namespace std;

string write(int n){
  string stars = "";
  for(int i = 0; i < n; i++){
    stars += "*";
  }
  return stars;
}

int main(){
  int n, i;
  cin >> n;
  string stars = write(n);
  i = stars.length();
  while(!stars.empty()){
    cout << stars << endl;
    stars = stars.substr(0, --i);
  }
  
  return 0;
}

// Easy method using for loop

  1. include <iostream>
  2. include <cmath>

using namespace std;

int main() { int n;

cin >> n;

for (int i = n; i >= 1; i--) { for (int k = 1; k <= i; k++) cout << "*"; cout << endl; }

system("pause"); return 0; }

//Made by: Reiz Troy D. Durante

#include<iostream.h>
#include<conio.h>

int i, j,k,n;

void main(){
clrscr();
cout<<"Enter a number: ";
cin>>n;
for(i=1;i<=n;i++){
	cout<<"N="<<i<<endl;
	for(j=i;j>0;j--){
		for(k=0;k<j;k++){cout<<"*";}
		cout<<endl;
	}
}
getche();
}

//Solution by Matthewkos

//Exercise 18
#include<iostream>
using namespace std;
      int input,loop[2];
      int main(){
          cout<<"Enter the number of star(s) :\t";
          cin>>input;
          cout<<endl<<endl;
          for (loop[0]=input;loop[0]>0;loop[0]--){
              for (loop[1]=1;loop[1]<=loop[0];loop[1]++)
                  cout<<"*";
              cout<<endl;}
          system("PAUSE");
          return 0;}

Alternate Solutions

#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>

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.";
}

A recursive solution

#include <iostream>

using namespace std;

void printAsterisk(int n) {
	for (int i = 0; i < n; i++) {
		cout << '*';
	}
	cout << endl;
	if (n > 1) printAsterisk(n - 1);
}

void main() {
	cout << "N=";
	int n;
	cin >> n;
	if (n < 0)
		cout << "ERROR, N has to be positive." << endl;
	else
		printAsterisk(n);
}
int main( )
{
	int number;
	std::cin >> number;

	auto save = number;
	for ( auto i = number; i > 0; --i )
	{
		std::cout << "*";

		if ( i == 1 )
		{
			std::cout << std::endl;
			i = --save + 1;
		}
	}
}


Exercise 19 edit

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
#include <iostream>
#include <string>
using namespace std;

string write(int n){
  string stars = "";
  for(int i = 0; i < n; i++)
    stars += "*";
  return stars;
}

string spaces(int n){
  string tabs = "";
  for(int i = 0; i < n; i++)
    tabs += " ";
  return tabs;
}

int main(){
  int n, i, numOfSpaces = 1;
  cin >> n;
  string stars = write(n);
  i = stars.length();
  cout << stars << endl;
  stars = stars.substr(0, --i);
  while(n > 0){
    string sp = spaces(numOfSpaces++);
    cout << sp << stars << endl;
    stars = stars.substr(0, --i);
    n--;
  }

  return 0;
}

//Solution by Matthewkos

//Exercise 19
#include<iostream>
using namespace std;
      int input,loop[2];
      int main(){
          cout<<"Enter the number of star(s) :\t";
          cin>>input;
          cout<<endl<<endl;
          for (loop[0]=input;loop[0]>0;loop[0]--){
              for (loop[1]=0;loop[1]<(input-loop[0]);loop[1]++)
                  cout<<" ";
              for (loop[1]=1;loop[1]<=loop[0];loop[1]++)
                  cout<<"*";
              cout<<endl;}
          system("PAUSE");
          return 0;}

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;
}

Solution #6 - Using a matrix. By David Castillo (decaalv@gmail.com)

#include <iostream>
#include <string>
using namespace std;

int main(){
    
    int intN;

    cout << "Type a value for N:\n";
    cin >> intN;
    string arrtemp[intN+1][intN+1];    
    
    cout << "\nN=" << intN << endl;
    
    for ( int i = 0 ; i < intN ; i++ ){
        for ( int j = 0 ; j < intN ; j++ ){
            ( i > j ) ? arrtemp[i][j]=' ' : arrtemp[i][j]='*';
            cout << arrtemp[i][j];
        }
        cout << endl;
    }

    return 0;
}

Solution #7 - Using allignment to the right. by Anboias.

#include <iostream>

using namespace std;

int main()
{
   int n;
   int a = 1;

    cout << "Insert a number N: " << endl;
    cin >> n;
    
        for(int i = n; i > 0; i--)
        {   
            cout.width(a);
            a++;
            for(int j = i; j > 0; j--){
                cout << "*";
                }
        cout << endl;
        }
    return 0;
}


Exercise 20 edit

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;
}
#include <iostream>
using namespace std;

int u(int,int,int);

int main(){
    int a, N, temp;
    cout << "Enter the initial value u(0): " << endl;
    cin >> a;
    cout << "Enter the value of N. I will return all the values from u(0) to u(N).";
    cin >> N;
    temp = a;
    for (int i = 0; i <= N; i++){
        temp = u(a, i, temp);
        cout << "u(" << i << ")=" << temp << endl;
    }

    return 0;
}

int u(int a,int N,int prev){
    if (N == 0) return a;
    else {
        if (prev%2==0) return prev/2;
        else return 3*prev+1;
    }
}


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;
}


Exercise 21 edit

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

Solution
#include <iostream>
using namespace std;

int main(){
  int n = 0;
  while(true){
    cin >> n;
    if (n == -999) break;
    cout << "triple is " << n*3 << endl;
  }

  return 0;
}

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);
}

Example 3:

//By Andrea ~ Omega™
#include <iostream>

int main() 
{ 
 int num, value;

 while(num != -999)
 {
  std::cout << "Enter a number: ";
  std::cin >> num;
  value = num * 3;
  std::cout << "The triple of " << num << " is " << value << std::endl;
 }
 return 0;
}


Exercise 22 edit

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>
using namespace std;

int main(){
  int n = 0, count = 0;
  while(true){
    cin >> n;
    if (n <= 0) break;
    count++;
  }
  cout << count << " positive numbers typed" << endl;

  return 0;
}
// Example program
#include <iostream>
#include <vector>

using namespace std;

//Rami Alkubaty's sloution

//Function for reading numbers and storing them in a vector

vector<int> VecOfNumbers (){
    
  vector <int> num;
  
  int input; 
  
  cout << "Enter a number, zero or negative to stop:\n";
  
  cin >>input;
  
  while (input > 0){
  
    num.push_back(input);
                     
    cout << "Enter a number, zero or negative to stop\n";
  
    cin >>input; 
  
  }
    
    return (num);
    
    }

//Function for checking if a number is even

void check_even(vector<int>&myVector){
    
  bool even_found = false;    
  
  int sum = 0;
    
  for (vector<int>::iterator it = myVector.begin() ; it != myVector.end(); ++it)
  {
      
      if (*it%2){;}
      
      
      else{
          
           sum++;
            
           even_found = true;
          
          }
      
      
      
      }
      
      
    if(myVector.empty()){
        
          cout << "Vector empty\n";
        
        
        }
      
    else if((!myVector.empty()) && (!even_found )){
        
        
        cout << "No even number found!\n";
        
        }  
        
  
    else {
        
        
          cout << "Number of positive numbers found = "<<sum;
        
         }    
    
    
    }

//Main function, calls two functions above

int main()
{
  
 vector <int> num =  VecOfNumbers ();
 
 check_even(num);

} //End sloution

#include <iostream>

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;

    return(0);
}
SOLUTION 2

#include <iostream>

using namespace std;

int main()
{
    int i,k=0,nr;
    for(i=1; i<=10000; i++)
    {
        cin>>nr;
        if(nr>0)
        k=k+1;
        else
        break;
    }
    cout<<k;
    return 0;
}
//Solution provided by Neeraj Morar
#include <iostream>

using namespace std;

int main()
{
	int n;
	int i;

	for (i = 0; n > 0; i++) {
		cout << "Type in an integer: ";
		cin >> n;
	}

	cout << "\n";
	i -= 1;
	cout << "You typed in " << i << " positive integers.\n";
	cout << "\n";

	system("PAUSE");
}
// The above solutions should be reviewed/sanitized.  They are unnecessarily complex or wrong (off by 1)
#include <iostream>
using namespace std;

int main()
{
    int32_t in_num;
    uint32_t count = 0;

    while (true) {
        cout << "Enter a positive number or 0/negative number to quit :";
        cin >> in_num;

        if (in_num >= 1)
            ++count;
        else
            break;
    };

    cout << "Number of positive numbers entered : " << count << endl;

    return 0;
}
//solution by David J
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter positive numbers (enter 0 or less to quit): " << endl;
    int pnum, cnt = 0;
    do
    {
        cin >> pnum;
        if (pnum > 0)
            cnt++;
    } while (pnum > 0);

    cout << "You have entered " << cnt << " positive numbers.\n";

    return 0;
}
//solution by Cyrex1337
#include <iostream>
#include <string>

//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.

int main( )
{
	size_t positives = 0;
	for ( auto number = 0; std::cin >> number && number > 0; )
		++positives;

	std::cout << positives << std::endl;
}


Exercise 23 edit

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, count = 0, sum = 0;
  while(true){
    cin >> n;
    if (n < 1) break;
    sum += n;
    count++;
  }

  if (count > 0)
    cout << "average of typed numbers is " << sum/count << endl;

  return 0;
}
#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;
}


Exercise 24 edit

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>
using namespace std;

int main(){
  int n, count = 0;
  while(true){
    cin >> n;
    if (n == 0) break;
    if (n >= 100 && n <= 200)
      count++;
  }

  cout << count << " numbers between 100 and 200" << endl;

  return 0;
}
#include <iostream>
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;

    return(0);
}


Exercise 25 edit

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 growingOfA(int a){
  return a * 0.03;
}

int growingOfB(int b){
  return b * 0.02;
}

int main(){
  int a = 50000, b = 70000, years = 0;
  while(a <= b){
    a = a + growingOfA(a);
    b = b + growingOfB(b);
    years++;
  }
  cout << "A will superpass B in " << years << " years" << endl;
  return 0;
}
#include <iostream>

class City {
	public:
		int inhabitants,gpy; //growth per year
		City(int a,int b) {
			inhabitants=a;
			gpy=b; 
		}
};

int main () {
	City A(50,3),B(70,2);
	int i=0;

	begin:
		A.inhabitants+=A.gpy*A.inhabitants/100;
		B.inhabitants+=B.gpy*B.inhabitants/100;
		i++;
		if (A.inhabitants>B.inhabitants) 
				std::cout<<"In "<<i<<"year(s), A will surpass B\n";
		else goto begin;
	return 0;
}

Alternative Simple 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);
}
#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;
}
#include <iostream>
using namespace std;

int main() {

    float populationA = 50;
    float populationB = 70;
    int years = 0;
    while (populationA < populationB)
    {
        populationA += (3*populationA)/100;
        populationB += (2*populationB)/100;

        years++;
    }
    cout << "Population A: " << populationA << endl;
    cout << "Population B: " << populationB << endl;
    cout << "Years: " << years;
    
    return 0;
}
#include <iostream>

float percent(float x,int p)
{
    return (x/100)*p;
}

int main()
{
    float A=50;
    float B=70;
    for(int i =0; A!=B;i++)
    {
        std::cout<<i<<"\n";
        A=A+percent(A,3);
        B=B+percent(B,7);
    }

}

Yet another alternative Simple Solution:

#include <iostream>
using namespace std;

class Country
{
    public:
        Country(size_t pop, uint32_t rate) :
            pop_(pop), rate_(rate) {}
        void grow() { pop_ = pop_ + ((pop_ * rate_) / 100); }
        size_t get_pop() { return pop_; }
    private:
        size_t pop_;
        uint32_t rate_;
};

int main()
{
    Country c_a(50000000, 3);
    Country c_b(70000000, 2);
    uint32_t years = 0;

    while (c_a.get_pop() < c_b.get_pop()) {
        c_a.grow();
        c_b.grow();
        ++years;cout<<"Enter Minimum Value";
    }

    cout << "Years : " << years << endl;
    cout << "A pop : " << c_a.get_pop() << endl;
    cout << "B pop : " << c_b.get_pop() << endl;
}

Exercise 26 edit

Write a program that asks the user to input 5 sequences of characters. Then it will ask the user for a character to search for and will output the maximum number of times that it occurred between the 5 sequences. Example: Sequence 1: aabc Sequence 2: aaaa If the user chooses to search for character 'a', the program will output "Character a occurred a maximum of 4 times" because it occurred 4 times in the second sequence, and only twice in the first sequence.

Solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    int a = 1;
    string sTemp;
    vector<string> sHold;

    cout << "Enter any sequence of characters. Enter up to 5 sequences.\n\n";
    do {
        cout << "Enter sequence " << a << ": ";
        cin >> sTemp;
        sHold.push_back(sTemp);
        a++;
    }
    while(a<6);

    char cSeek;
    cout << "Enter a letter to look for and count its max occurrence: ";
    cin >> cSeek;

    vector<int> viCount;
    for(int i=0; i<sHold.size(); i++) {         //Counting the occurrences of cSeek
        int iCount = 0;
        for(int k=0; k<sHold[i].size(); k++) {
            if(sHold[i][k] == cSeek) {
                iCount++;
            }
        }
        viCount.push_back(iCount);              
        //The maximum occurrence of cSeek for each sequence will be stored in viCount, each value referred to as a local maximum
    }

    int iMax = viCount[0];                      //Finding the max of the local maximums
    for(int i=0; i<viCount.size(); i++) {
        if(viCount[i] > iMax) {
            iMax = viCount[i];
        }
    }

    cout << "The character " << cSeek << " occurred a maximum of " << iMax << " times.\n\n";

    return 0;
}

Alternative, optimized solution

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    const uint32_t num_str = 5;
    vector<string> input_str;
    string temp_str;
    char a_char;

    cout << "Enter five seq. of chars : " << endl;
    for (uint32_t i = 0; i < num_str; ++i) {
        cout << "Enter sequence (" << i << ") : ";
        cin >> temp_str;
        input_str.push_back(temp_str);
    }

    cout << "Enter a char : ";
    cin >> a_char;

    uint32_t max = 0, temp = 0;
    for (uint32_t i = 0; i < input_str.size(); ++i) {
        temp = 0;
        for (uint32_t j = 0; j < input_str[i].size(); ++j) {
            if (input_str[i][j] == a_char)
                ++temp;
        }
        if (max < temp)
            max = temp;
    }

    cout << "Max of " << a_char << " : " << max << endl;

    return 0;
}
//solution by David J
#include <iostream>

using namespace std;
int look_for_char(const string &s, char ch)
{
    int cnt = 0;
    for (int i = 0; i < s.size(); i++)
    {
        if (ch == s[i])
            cnt++;
    }
    return cnt;
}

int main()
{
    string a, b, c, d, e;
    char ch;
    int ia, ib, ic, id, ie, iMax = 0;
    cout << "Please enter 5 sequences of characters:" << endl;
    cin >> a >> b >> c >> d >> e;
    cout << "Enter character that you are looking for: ";
    cin >> ch;
    ia = look_for_char(a, ch);
    if (iMax < ia)
        iMax = ia;
    ib = look_for_char(b, ch);
    if (iMax < ib)
        iMax = ib;
    ic = look_for_char(c, ch);
    if (iMax < ic)
        iMax = ic;
    id = look_for_char(d, ch);
    if (iMax < id)
        iMax = id;
    ie = look_for_char(e, ch);
    if (iMax < ie)
        iMax = ie;

    cout << "Character " << ch << " has been typed - " << iMax << " times.\n";
    return 0;
}

Class based solution.

#include <iostream>
#include <string>
#include <list>

typedef unsigned int uint;
class str;

const uint _sentence_count = 5;
const uint _target_char_max_length = 1;

std::list<str> readStringListByCount(uint);
std::string getTargetCharFromUser(bool strict = false);
uint getOccurrenceCount(const std::list<str>&, const str&);

class str : public std::string{
public:
	template<typename T>
	str(T& t) : std::string(t){}

	template<typename T>
	unsigned int count(const T& what) const throw(){
		unsigned int occurrences = 0, last_found_position = this->find(what);

		while(last_found_position != this->npos){
			last_found_position = this->find(what, last_found_position + 1);
			++occurrences;
		}

		return occurrences;
	}
};

using namespace std;

list<str> readStringListByCount(uint n){
	cout << "Please supply " << n << " strings to search occurrences in." << endl;
	string s;
	list<str> string_list;

	for (uint i = 0; i < _sentence_count; ++i){
		cout << i+1 << ": ";
		cin >> s;
		string_list.push_back(s);
	}

	return string_list;
}

string getTargetCharFromUser(bool strict){
	cout << endl << "Please specify character to find: ";
	string target_char;

	cin >> target_char;
	while (target_char.size() != _target_char_max_length && strict){
		cout << "Invalid target character. Expected length is ";
		cout << _target_char_max_length << endl << "Try again." << endl;
		cin >> target_char;
	}

	return target_char;
}

uint getOccurrenceCount(const list<str>& string_list, const str& target_char){
	uint occurrence_count = 0, targets_found;
	list<str>::const_iterator it;

	for (it = string_list.begin(); it != string_list.end(); ++it){
		targets_found = it->count(target_char);
		if (targets_found > occurrence_count) occurrence_count = targets_found;
	}

	return occurrence_count;
}

int main(int argc, char* argv[]){
	list<str> string_list = readStringListByCount(_sentence_count);	
	string target_char = getTargetCharFromUser(true);
	uint maximal_occurrence_count = getOccurrenceCount(string_list, target_char);

	cout << "Maximum occurrence count of character \"" << target_char << "\" ";
	cout << "is " << getOccurrenceCount(string_list, target_char) << "." << endl;

	return 0;
}


Exercise 27 edit

Write a program that asks the user to type a random number. Write in the output if this number is a prime number or not. Write which numbers your number can be divided by.

Solution
/*

Author: Lukaskuko
Date:14.11.2014

About:
Write a program that asks the user to type a random number.Write in output if this number is a prime number or not.
Write,by which numbers can your number be divided.

*/

#include <iostream>

using namespace std;

int main()
{
    int x;
    int count = -1;
    cout << "Write a number:\n";
    cin >> x;
    getchar();
    
    for(int i=1;i<x+1;i++)
    {
            if(x%i == 0) 
            { 
                   count+=1;  
                   cout << "Number " << x << " can be divided by " << i << endl;
            }       
    }
    if(count == 1) cout << "This number is prime number." << endl; 
    else cout << "This number is not a prime number." << endl;
    getchar();
    return 0;
}


Exercise 28 edit

Write a program for finding the amount of a specific character inside a string.

Solution
/* By: N.T-A.N. - 2230_072015 - (VS_2013_ULT_U4) */
#ifndef SOURCE_CPP
#define SOURCE_CPP

#include <iostream>
#include <string>

int main()
{
	std::string input_str, input_char;
	std::cout << "Do type in a random string: ";
	std::getline(std::cin, input_str);
	std::cout << "What is that one character, specifically, are you looking for? ";
	std::getline(std::cin, input_char);
	if (input_char.size() > 1) std::cout << "ONE character, I SAID ONE!!" << std::endl;
	else
	{
		unsigned cntr{ 0 };
		for (auto &tmp_char : input_str)
			if (input_char.front() == tmp_char) cntr++;
		std::cout << "\'" << input_char << "\' was found " << cntr << " time(s) in this string: " << input_str << std::endl;
	}
	return 0;
}

#endif /* SOURCE_CPP */


Exercise 29 edit

Write a Program to find out no. of Even & Odd no. in a given Data Series.

Solution
/*

Author: Rami Alkubaty

Date: 28.10.2015

*/

#include <iostream>
#include <vector>
using namespace std;

void filter (vector<int>&myVect){
    
       unsigned int index = 0;
       
       int num_even = 0;
       
       int num_odd = 0;
        
       if (myVect.empty()){
          
           cout << "The data set is empty";
           
           return;
          
          }
    
       else{
           
             for (; index < myVect.size(); index++){
                 
                  if(myVect[index]%2){
                      
                      num_odd++;
                        
                      
                      }   
                 
                  else{
                        num_even++;
                        
                      }
                 
                 
                 }
           
           
           
           }
           
           
         cout << "In the data set being given there was/were " << num_odd << " odd number and "<<num_even << "even number(s)"<<endl;
         
      
     
    
    }

int main(){
    
    int num;
    
    vector <int> myVect;
    
    cout << "Enter a positive number: ";
    
    cin >> num;
    
    while(num < 0 && num != -1){
        
        cout << "Wrong input, enter a positive number: ";
        
        cin >> num;
        
    }
    
    while (num != -1){
        
        myVect.push_back(num);
        
        cout << "Enter a positive number: ";
    
        cin >> num;
    }
     
    filter(myVect);
}

//End

/* By: N.T-A.N. - 1900_072015 - (VS_2013_ULT_U4) */
#ifndef SOURCE_CPP
#define SOURCE_CPP

#include <iostream>

int main()
{
	unsigned data[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
	even_n{ 0 }, odd_n{ 0 };
	std::cout << "Given numbers: ";
	for (auto &tmp : data)
	{
		std::cout << tmp << ' ';
		if (tmp % 2 == 0) even_n++;
		else odd_n++;
	}
	std::cout << "\nEven No.: " << even_n << std::endl;
	std::cout << "Odd No.: " << odd_n << std::endl;
	return 0;
}

#endif /* SOURCE_CPP */


Exercise 30 edit

Write a Program to count Zero, Positive, Negative no. in a given Data Series.

Solution
/* By: N.T-A.N. - 1900_072015 - (VS_2013_ULT_U4) */
#ifndef SOURCE_CPP
#define SOURCE_CPP

#include <iostream>

int main()
{
	int data[]{-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
	unsigned positive_n{ 0 }, negative_n{ 0 }, zero{ 0 };
	std::cout << "Given numbers: ";
	for (auto &tmp : data)
	{
		std::cout << tmp << ' ';
		if (tmp > 0) positive_n++;
		else if (tmp < 0) negative_n++;
		else zero++;
	}
	std::cout << "\nZero: " << zero << std::endl;
	std::cout << "Positive No.: " << positive_n << std::endl;
	std::cout << "Negative No.: " << negative_n << std::endl;
	return 0;
}

#endif /* SOURCE_CPP */


Exercise 31 edit

Write a program to count the numbers which are divisible by 3 in a given Data Series.

Solution
// Example program
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  //Write a program to count the numbers which are divisible by 3 in a given Data Series.
  //This is very simple to work it.
  
  vector<int> sayilar;
  vector<int> bol;
  int sayi;
  int count = 0;
  cout<<"plesase enter 5 numbers"<<endl;
  for(int i = 0 ; i < 5 ; i++){
  cin >> sayi;
  sayilar.push_back(sayi);
  }
  for(int i = 0 ; i < sayilar.size();i++){
    if(sayilar[i]%3==0){
        bol.push_back(sayilar[i]);
        count++;
    }
  }
  cout<<"bölünenler = "<<count<<endl;
  for(int i = 0 ; i < bol.size();i++){
    cout<<bol[i]<<endl;   
  }
}

Simple alternative solution:

/* By: N.T-A.N. - 1921_072015 - (VS_2013_ULT_U4) */
#ifndef SOURCE_CPP
#define SOURCE_CPP

#include <iostream.h>

int main()
{
	unsigned data[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
	_3divisible{ 0 };
	std::cout << "Given numbers: ";
	for (auto &tmp : data)
	{
		std::cout << tmp << ' ';
		if (tmp % 3 == 0) _3divisible++;
	}
	std::cout << "\nNumbers which are divisible by 3: " << _3divisible << std::endl;
	return 0;
}

#endif /* SOURCE_CPP */