C++ Programming/Exercises/Iterations
Iterations [edit]
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.
===EXERCISE 1 === Write a program that asks the user to type an integer and writes "YOU WIN" if the value is between 56 and 78 (both included). In the other case it writes "YOU LOSE".
//Solution #include<iostream> using namespace std; int main() { int num; cout<<"Enter the number which you would like to give: "; cin>>num; if(num>=56&&num<=78) cout<<"You win" << endl; else cout<<"You lose" << endl; return 0; }
//Alternate Solution by SowmyaBR, Bangalore, India #include<iostream> using namespace std; int main() { int num; cout<<"Enter the number which you would like to give:"; cin>>num; num>=56?(num<=78?cout<<"You win"<<endl:cout<<"You lose"<<endl):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 #include <iostream> using namespace std; int main() { // Input and loop defined, only adds if input is correct. for (short int i = 8, input; i <= 23; i += (i == input)) { cout << "Enter the number " << i << ": "; cin >> input; } return 0; }
Alternative solution by Bartosz Radwanski
//Alternative solution by Bartosz Radwanski (bartekradwanski@gmail.com) //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; }
#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 3 [edit]
Same exercise but you must use a while.
#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 4 [edit]
Write a program that asks the user to type 10 integers and writes the sum of these integers.
//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 (bartekradwanski@gmail.com) #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; }
EXERCISE 5 [edit]
Write a program that asks the user to type 10 integers and writes the smallest value.
//Solution by Aldo Ziflaj #include <iostream> using namespace std; int main() { int num[10],min; for (int i=0;i<10;i++) { cout<<"enter a number: "; 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 (bartekradwanski@gmail.com) //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]; } }
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 #1
//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; }
Alternative solutions
// 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; }
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 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 #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(); }
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.
#include<iostream> using namespace std; int main() { int N; bool ok; do { cout<<"Type the value of N between 0 et 20 :";cin>>N; ok= N<=20 && N>=0; if(!ok)cout<<"ERROR"<<endl; }while(!ok); N=N+17; cout<<"The final value is : "<<N<<endl; return 0; }
The solution in C.
#include <stdio.h> int main() { int N; do { printf("Integer between 0 and 20: "); scanf("%d", &N); if((N < 0) || (N > 20)) printf("ERROR\n"); } while((N < 0) || (N > 20)); printf("The final value is %d\n", N+17); return 0; }
#include <iostream> using namespace std; int main() { int userIn; cout << "Enter a number between 0 and 20: " << endl; cin >> userIn; while(!((userIn >= 0) && (userIn <= 20))) { cout << "Wrong Input!" << endl; cin >> userIn; } cout << "N+17 = " << (userIn + 17) << endl; system("pause"); }
//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 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;}
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; }
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(); }
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 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;}
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 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; }
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 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 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
#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); }
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 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; }
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 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 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 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 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.
#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.
#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.
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.
#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;
}
EXERCISE 23 [edit]
Request the user to type positive numbers, or to stop by typing a number smaller than 1. Print the average.
#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).
#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.
#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; }
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; }
The