Using switch statement create a code that output remainders( 0, 1, 2, 3 and others) when divided by 8. User inputs 20 integer from 0 till 99. Each remainder should show its total count.
Eg :This is how the output should be.
Total number with remainder 0 is 4.
Total number with remainder 1 is 6.
Total number with remainder 2 is 5.
Total number with remainder 3 is 3.
Total number of other remainder is 2.
/
#include <iostream>
using namespace std;
int main()
{
int i, x[20];
cout << "Enter 20 integer numbers from 0 to 99: " <<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i]; // above this code, its working.
}
int remainder ; // From here im not sure how i should do it
switch (remainder)
{
case x[i] % 8 == 0 :
cout << "Total number with remainder zero is " << endl ;
break;
case x[i] % 8 == 1 :
cout << "Total number with remainder one is " << endl ;
break;
case x[i] % 8 == 2 :
cout << "Total number with remainder two is " << endl ;
break;
case x[i] % 8 == 3 :
cout << "Total number with remainder three is " << endl ;
break;
default :
cout << "Total of others is " << endl ;
}
return 0 ;
}
I have the general idea of the switch statements. I'm new to c++ and also to this website. Between the errors are at case part. It says i cant use x[i]. So should i just use x or other integer? Im not sure how to count the total number for each case. should i be using count++ ?
Switch statements are supposed to have a condition to test and then execute commands based on the results. The problem here is that you are testing a variable that does not have a value. The parentheses contain the data being tested. The cases are to execute given commands based on the resulting value. The thing you are testing here is x[i] % 8. This should go between in the parentheses. The case should just have the value attached to it.
switch (x[i] % 8) {
case 0: //...
case 1: //...
case 2: //...
case 3: //...
default: //...
}
case will test whether the result of the action taken in the parentheses equal its assigned value (e.g. 0, 1, 2, 3, or default) and execute the assigned command.
Related
As the title suggests, my program which is designed to find the largest element within a user defined integer array becomes unstable when all negative numbers are used for the user input. Additionally the output becomes unstable when all zero's are used for the user input (excluding the input for total # of elements).
The program works just fine when all positive numbers are used. This is quite perplexing to me and I'm sure there's a valid explanation but I was under the impression that in C++, the int & float data types were automatically signed and would be able to handle negative numbers for it's data range. So why would the program not return a valid output if all negative numbers are used for the user array input(s)?
Bad Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: -10
Enter number 2: -5
Enter number 3: -20
Enter number 4: -2
Enter number 5: -7
The largest element within specified realNum[5] array is element number: 6 with a value of: 5.88501e-039
Good Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: 10
Enter number 2: 5
Enter number 3: 20
Enter number 4: 2
Enter number 5: 7
The largest element within specififed realNum[5] array is element number: 3 with a value of: 20
Program:
//10.2 Largest Element Finder of an Array
//Mandatory header
#include <iostream>
//Use namespace std ;
using namespace std ;
//Mandatory main method
int main ()
{
//Declare and initlize variables
int i, total, realNum = 0, temp = 1 ;
//Ask user to input a number of total elements
cout << endl << endl
<< "Please enter a total number of elements you'll be using: " ;
//Wait for user input
cin >> total ;
//Declare array set
float setNum [total] ;
//Ask user to input each varaible
cout << endl
<< "Please enter each variable one by one." << endl << endl ;
for ( i = 0 ; i < total ; i ++ )
{
cout << endl << "Enter number " << (i + 1) << ": " ;
cin >> setNum [i] ;
}
//Find the largest element within the array
for ( i = 0 ; i < total ; i ++ )
{
if ( setNum [i] <= setNum [temp] ) //Discard current i if less than the next element - Means temp is HIGHER and should be saved
{
if ( setNum [temp] >= setNum[realNum] )
realNum = temp ; //Temp can now be changed for iteration purposes as realNum is saving the highest element's positon
}
else if ( setNum [i] >= setNum [temp] ) //Discard current i if more than the next element and use the remainder to compete against the realNum
{
if ( setNum [i] >= setNum [realNum] )
realNum = i ;
}
i ++ ;
temp += 2 ;
}
//Display calculations
cout << endl << endl
<< "The largest element within specififed realNum[" << total << "] array is element number: " << (realNum + 1) << " with a value of: " << setNum[realNum] << endl ;
//Mandatory return statement
return 0 ;
}
I need to write a program in C++ that receives a positive number greater than 2 from the user, and prints whether the number is prime or not.
Reminder: A number is prime if it is divisible by a remainder only in itself and in 1, and not in any other number. Therefore, primary 2 is divisible only by itself and 1, but non-primary 4 is also divisible by 2.
but the probleme is in the loop, He repeats the steps
and I have a problem with the number 2177 which is not a prime number.
#include <iostream>
#include <math.h>
using namespace std;
void main()
{
int nNumber;
int i;
cout << "Enter a number:" << endl;
cin >> nNumber;
if (nNumber >= 2)
{
for (i = 2; i <= sqrt (nNumber); i++)
{
if (nNumber % i == 0)
{
// he is repete the step her
cout << nNumber << " is not a prime number." << endl;
}
}
if (nNumber % i != 0)
{
cout << nNumber << " is a prime number. " << endl;
}
}
system("pause");
}
You do not describe what problem you have, but what I get when I run this program is:
2177 is not a prime number.
2177 is a prime number.
sh: 1: pause: not found
First your applications finds correctly that 2177 is not prime (at i=3), but then you continue your loop (which is not necessary or useful because it will just print the line again if it finds extra values).
However your main problem is that you always execute the line if (nNumber % i != 0), even if a value has been found. At this point i has the fixed value ((int)sqrt(2177)) + 1 (which is 47) because the loop is completed at that point and will stay at that value. Because 2177 is not divisible by 47 you print out the message 2177 is a prime number..
This code should work. Added break statement -
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int nNumber;
int i;
cout << "Enter a number:" << endl;
cin >> nNumber;
if (nNumber >= 2)
{
for (i = 2; i <= sqrt (nNumber); i++)
{
if (nNumber % i == 0)
{
cout << nNumber << " is not a prime number." << endl;
break;
}
}
if (nNumber % i != 0)
{
cout << nNumber << " is a prime number. " << endl;
}
}
system("pause");
return 0;
}
Just define a Boolean variable and set its value to 'true'. You only need to run a loop "n/2 times" as the maximum divisor is half of the actual number. So, if the input number is divisible by any value between '2-n/2', set the value of Boolean variable false. In the end, print the result on the basis of Boolean variable value.
Have a look at this link!
https://www.programiz.com/cpp-programming/examples/prime-number
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "\n* This is a program that counts integers you enter as *"
<< "\n* even, odd or zero and positve or negative *"
<< "\n* It classifies 20 numbers or use 99999 to exit early *"
<< "\n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "\n\nPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "\n\t\t or enter number 99999 to exit early. \n\n"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "\n\n\tPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
I am debugging this program. There were originally 6 errors in the program. I've found four of them as they were syntax errors. The compiler doesn't show any error but the program isn't working either.
The program is supposed to store 20 numbers and in the end tell you how many of them were even, odd, zero, negative, and positive. I am just a beginner in C++. I have tried every possible way to solve it from my side but I cannot get it to work. I have looked up every code and syntax on Google why it works that way but found no help. Any help here would be highly appreciated.
If you enable warnings when you compile then the compiler will helpfully point out certain mistakes in your code, and if it's in a good mood it may even suggest a solution:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
Always compile with warnings enabled (e.g. gcc -Wall ...) - it will save you a lot of time and debugging effort in the long run.
I am kind of stranded with a problem. I am trying to test whether a number inputted is prime or divisible by 7.
Basically, my program asks the user to input a number, then asks the user to input one of the following letters: "a", "b", or "c". The letters correspond to the following options:
a) The number inputted is Even or Odd (figured it out)
b) The number is Prime or composite
c) Checks if number is divisible by 7 or not (figured it out)
For example, if the number inputted by the is user is 5 and then chooses the letter "b", I should get the output "The number is Prime". On the other hand, if he chose the letter "a", I should get the output "The number is Odd".
I would really appreciate any help. Thanks in advance!!
This is what I managed to create so far:
#include <iostream>
using namespace std;
int main ()
{
int number;
char letter = 0;
cout << "Input number: ";
cin >> number;
cout << "Enter (a) to check for even or odd.\n"
<< "Enter (b) to check for prime or not.\n"
<< "Enter (c) to check for divisible by 7 or not.\n";
cin >> letter;
switch (letter)
{
case 'a':
switch (number % 2)
{
case 0:
cout << "The number is Even.\n";
break;
case 1:
cout << "The number is Odd.\n";
break;
}
break;
case 'b':
switch ()// Don't know what to put for condition
{
case 0:
cout << "The number is Prime.\n";
break;
case 1:
cout << "The number is composite.\n";
break;
}
break;
case 'c':
switch (number % 7)
{
case 0:
cout << "The number is Divisible by 7.\n";
break;
case 1:
cout << "The number is not Divisible by 7.\n";
break;
}
break;
}
return 0;
}
You already have the solution for c, it's the same as the solution for a.
A number is divisible by two if (number % 2) == 0. Similarly, a number is divisible by seven if (number % 7) == 0.
So, using the first case, and realising that switch has a default clause:
switch (number % 7) {
case 0:
cout << "The number is a multiple of seven.\n";
break;
default:
cout << "The number is NOT a multiple of seven.\n";
break;
}
You'll notice I've used switch there because your question called for it but it's not really required other than by your question. A two-choice either-or switch statement can just as easily be done with if-else.
The solution for b (prime) is a little more complex. The number is prime if it's not a multiple of any number from two up to but not including the number itself (there are efficiencies such as only going up to the square root of the number, and only checking primes rather than all numbers but they can be added later if you wish).
You would therefore have a loop x = 2..(n-1) in which you would check the remainder for zero and say it's not prime if that's the case ((n % x) == 0).
If you check all numbers in the range and don't find one where the remainder is zero, you have a prime.
The pseudo-code for such a beast would be (using switch though, again, it's by no means necessary here):
is_prime = true
for x = 2..n-1: // C++: for (int x = 2; x < n; x++)
if (n % x) == 0:
is_prime = false
break for
switch (is_prime):
case true:
print "Number is prime"
break switch
default:
print "Number is NOT prime"
break switch
To only go up to the square root of the number is a very small modification to the for loop:
is_prime = true
for x = 2..∞ until x * x > n: // C++: for (int x = 2; x * x <= n; x++)
if (n % x) == 0:
is_prime = false
break for
You have another problem with the code as you have it. While you're using break to prevent fall through for the inner switches, you don't have them for the outer switch.
Immediately before the case 'b': and case 'c': lines, you should insert break; lines to prevent the fall-through. Otherwise, choosing option a will result in all three tests being done, and option b will do both b and c.
As the other people have already stated, you can determine if a number is divisible by some other number by using the modulus (%) operator. However, there is no built-in function or operator to determine if a number is prime. There is a multitude of examples on the internet for determining this, but a trivial example of one such function would be:
bool is_prime(int number){
if( number <= 2 ){
return number == 2;
}
for( int divisor = 3; divisor < number / 2; divisor += 2 ){
if( number % divisor == 0 ){
return false;
}
}
return true;
}
You could then use this function in a condition to determine if a number is prime. If you want to test a huge variety of numbers, a sieve would be more time efficient, but this works for most uses.
Here's the code:
#include <iostream>
using namespace std;
int main ()
{
int number;
char letter = 0;
cout << "Input number: ";
cin >> number;
cout << "Enter (a) to check for even or odd.\n"
<< "Enter (b) to check for prime or not.\n"
<< "Enter (c) to check for divisible by 7 or not.\n";
cin >> letter;
switch (letter)
{
case 'a':
if (number % 2 == 0)
{
cout << "The number is Even.\n";
}
else
{
cout << "The number is Odd.\n";
}
break;
case 'b':
if(number > 0 ) //Only positive numbers
{
int count = 0; //dummy variable
for(int i = 2; i < number; i++) // loop till one less than number entered
{
if(number % i == 0) //Number is divisible by other number
{
count++; // increment the count
break;
}
}
if(count == 0) // since prime numbers cannot be divided by any other number except 1 and the number itself
{
cout << "Prime number.\n";
}
else
{
cout << "Not a Prime number.\n";
}
}
else
{
cout << "Please enter a positive integer.\n";
}
break;
case 'c':
if (number % 7 == 0)
{
cout << "The number is Divisible by 7.\n";
}
else
{
cout << "The number is not Divisible by 7.\n";
}
break;
}
return 0;
}
So I am working on a switch statement but I am not quite sure if I am doing this right. This is my first tiny program using C++ (visual studio 2010) and I am not sure that I am using the switch statement quite right. What I am trying to do is have a person input numbers. I have a counter set up to count the number of inputs as well as I have a running total to output at the sum of all numbers inputted.
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment the counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
switch (sum){ //this is where I get into trouble
case 0-99: cout << "\n\n"; //original question, can I do this?
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
return 0;
break;
case 100: cout << "\n\n"; //and so on
So my question is whether or not this is possible. Can I use this for a case?
Standard C++ does not allow case ranges, in your code 0-99 will just end up being evaluated as 0 minus 99 which means what you have is essentially:
case -99:
one alternative is to use an if statement instead so:
case 0-99
would become:
if( sum >= 0 && sum <= 99 )
{
}
Some compilers including gcc offer case ranges as an extension but this would make your code non-standard and not portable and since you are using Visual Studio probably does not apply.
I actually figured this out. It is better to set a case based on the sum. Since I had 3 cases that I was working with, I just made it select the case based on the the total that I had previously gotten. Below is my code:
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
if (sum < 100){ //set condition for option 1
option =1;}
else if (sum == 100){//set condition for option 2
option =2;}
else if (sum > 100)
{option = 3; //last resort option 3
}
switch (option)
{
case 1: cout << "\n\n";//new line
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
break;
case 2: cout << "\n\n";//new line
Works like a charm.