C++ Programming/Exercises/Iterations

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

Iterations[edit]

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


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
//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 by Bartosz Radwanski

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


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


   #include<iostream.h>
   #include<conio.h>
   void main()
   {
     int min,max;
     cout<<"Enter Minimum Value";
     cin>>min;  
     cout<<"Enter Maximum Value";
     cin>>max;
     for (;min<=max;min++){
     cout<<"\n"<<min;}
     getch();
     }
/*
	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
//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;
}


EXERCISE 4[edit]

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

Solution
//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; } </source>

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






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

EXERCISE 5[edit]

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

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

Alternative solution by Bartosz Radwanski

//Alternative solution by Bartosz Radwanski
//A nice, very basic sorting mechanism.
#include "stdafx.h"
#include <iostream>
#define NUM 10
using namespace std;
 
int _tmain(int argc, _TCHAR* argv[])
{
	int min=sizeof(int), input, i=0;
	cout<<"Enter "<<NUM<<" integers:\n";
	while(i<10) {
		cout<<"#"<<i+1<<"> ";
		cin>>input;
		if(input<min) {
			min=input;
		}
		i++;
	} 
	cout<<"Smallest value: "<<min<<endl;
	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;
}

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


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

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: Franklin
// A big simplyfication is to notice that the recurrence is essentially running 
// Horner-Ruffini's algorithm to evaluate, at x=3, a polynomial that has all its non-leading coefficient equal to 4. 
// This is, the sum is 3^n+4*3^{n-1}+...+4*3+4.
// This sum has a closed form. It is equal to 3^(n+1)-2
// Therefore the most important routine in the program is to compute the power of 3.
// The power of 3 can be computed using the square-and-multiply algorithm if wanted. 
// To make the program short we can use the pow() function from cmath. Most surely this is computed
// using said algorithm
 
#include<iostream>
#include<cmath>
 
using namespace std;
 
int main(){
int n;
cout << "Input the number n: ";
cin >> n;
if (n==0){
  cout << "c(0)=3" << endl;
}else{
  cout << "c(" << n << ")=" << pow(3,n)-2 << endl;
};
 
}


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


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


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


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

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


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

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


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

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


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

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


EXERCISE 14[edit]

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

Solution

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

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

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


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

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

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

Solution #2

#include <iostream>
#include <cmath>
 
using namespace std;
 
bool isPrime(int n)
{
    for (int i = 2; i <= sqrt(n); i++)
    {
        if (n%i == 0)
	    return false;
    }
    return true;
}
 
int main()
{
    int count = 0,
    value = 0;
 
    cout << "Enter a value: ";
    cin >> value;
 
    int prime = 0;
 
    for (int i = 2; count < value; i++)
    {
	if(isPrime(i))
	{
	    count++;
 	    prime = i;
	}
    }
 
    cout << "The " << count << "th prime is " << prime << endl;
}


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

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


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

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


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


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

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


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


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

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 getOccurenceCount(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 occurences = 0, last_found_position = this->find(what);
 
		while(last_found_position != this->npos){
			last_found_position = this->find(what, last_found_position + 1);
			++occurences;
		}
 
		return occurences;
	}
};
 
using namespace std;
 
list<str> readStringListByCount(uint n){
	cout << "Please supply " << n << " strings to search occurences 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 getOccurenceCount(const list<str>& string_list, const str& target_char){
	uint occurence_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 > occurence_count) occurence_count = targets_found;
	}
 
	return occurence_count;
}
 
int main(int argc, char* argv[]){
	list<str> string_list = readStringListByCount(_sentence_count);	
	string target_char = getTargetCharFromUser(true);
	uint maximal_occurence_count = getOccurenceCount(string_list, target_char);
 
	cout << "Maximum occurence count of character \"" << target_char << "\" ";
	cout << "is " << getOccurenceCount(string_list, target_char) << "." << endl;
 
	return 0;
}


EXERCISE 27[edit]

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.

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


Edit