Question :
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Example
Input:
1
2
88
42
99
Output:
1
2
88
So that is the question, however i am still a beginner and unable to have an input tab like that. In my program, how should i modify it such that it still accepts numbers after 42, however, it does not print them? currently I am only able to terminate the input at 42.
#include <iostream>
using namespace std;
int main()
{
int A[100], num, i=0,k,count;
for(count = 0; count != 1;){
cin >> k;
if (k!=42){
A[i] = k;
i++;
}
else
count =1;
}
cout << endl;
for (count = 0; count <i; count ++){
cout << A[count] << endl;
}
}
You don't have to use array at all. You can print the value just after reading it. Exit when you read 42. This may help you.
#include <iostream>
using namespace std;
int main() {
// your code goes here
int n ;
for(; ;) {
cin >> n ;
if(n == 42) {
return 0 ;
}
cout << n << endl ;
}
return 0;
}
Pretty sure the easiest way to do so is to simply ask the user how many numbers they need to enter.
#include <iostream>
using namespace std;
int main()
{
int A[100], k, count;
cout << "How many numbers do you want to enter ? ";
cin >> count; //this is to count how many numbers the user wants to enter
for(int i(0); i < count; ++i) //put all the numbers user enters in your array
{
cin >> k;
A[i] = k;
}
cout << endl;
for (int i(0); i < count; ++i)
{
if (A[i] == 42) //if the element at index i is == 42 then stop displaying the elements
break;
else
cout << A[i] << " "; //else display the element
}
cout << endl;
return 0;
}
Else you would need to put everything in a string and parse it and i'm not quite sure how that goes as I am a beginner as well.
EDIT:
Actually here you go, I think that is correct and does exactly what you want.
Do keep in mind that if user enters p.e "1 88 442" it will output "1 88 4" because it found "42" in "442". But it should be okay because you precised input numbers should only be two digits max.
#include <iostream>
using namespace std;
int main()
{
string k;
getline(cin, k);
cout << endl;
for (unsigned int i(0); i < k.length(); ++i)
{
if (!((k[i] == '4') && (k[i+1] == '2'))) //if NOT 4 followed by 2 then display
cout << k[i];
else
break; //else gtfo
}
cout << endl;
return 0;
}
Use a bool value to control the execution of your code.
#include <iostream>
#define N_INPUT 100
#define THE_ANSWER 42
using namespace std;
int main()
{
int array[N_INPUT], i, input, count=0;
bool universeAnswered = false;
for (i = 0; i < N_INPUT; i++) {
cin >> input;
if (!universeAnswered)
{
if (input == THE_ANSWER) {
universeAnswered = true;
} else {
array[count] = input;
count++;
}
}
}
for (i = 0; i < count; i++) {
cout << array[i] << endl;
}
}
(My code was not tested)
You just have to have some state to see if you have seen 42 already, and only output if you haven't
#include <iostream>
int main()
{
bool output = true;
for (int n; std::cin >> n;)
{
output &= (n != 42);
if (output)
{
std::cout << n << std::endl;
}
}
return 0;
}
Related
Let me preface this by saying I am fairly new to functions and arrays.
I have to make 3 functions: Function1 will be user input, Function2 will determine even/odd numbers, and Function3 will display the contents. I have Function1 and Function3 complete, and will post below, but I'm having a difficult time with Function2. What I have now will give the user an error message if they enter an even number, but it's messed up, and I just can't seem to figure out.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
int n;
for (int i = 0; i < size; i++)
{
cout << "Enter five odd numbers: ";
cin >> n;
num[i] = n;
if (num[i] % 2 != 0) //if the number is odd then store it, if it is even: //function for even or odd (function 2 of 3 *doesn't work)
{
i++;
}
else
{
cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers.
}
}
}
int main()
{
const int size = 5; //array size is 5 numbers
int num[size];
getUsrInput(num, size);
cout << "D I S P L A Y - PART C/B" << endl;
cout << "========================" << endl;
for (int i = 0; i < size; i++)
{
cout << num[i] << endl; //function for display (function 3 of 3)
}
}
for (int i = 0; i < size; i++)
increments i each time through the loop.
if (num[i] % 2 != 0) {
i++;
}
increments i each time the number is odd. So each time the user inputs an odd number, i gets incremented twice. Change the loop control to
for (int i = 0; i < size; }
so that i only gets incremented on valid input.
It' perfect for a while loop and you only count up if the insert is ok:
void getUsrInput(int num[], int size) //function for user input (function 1 of 3)
{
int n, i=0;
while( i < size )
{
cout << "Enter five odd numbers: ";
cin >> n;
if (n % 2 == 0)
cout << "Invalid input. Please only enter odd numbers!" << endl;
else
num[i++] = n; // ok then store and count up
}
}
is there any way to get rid of arrays in this program? Im not allowed to do it with std::array or std::vector.
#include <iostream>
using namespace std;
int main()
{
int upper,i,j=0,k=0;
int arr1[1000],arr2[1000];
cout<<"Enter the upper bound :";
cin>>upper;
for(i=0 ; i<upper ; i++)
{
if(i%2 == 0)
{
arr1[j] = i;
j++;
}
else
{
arr2[k] = i;
k++;
}
}
cout<<"List of even numbers :";
for(i = 0; i<j ; i++)
{
cout<<arr1[i]<<" ";
}
cout<<"\n";
cout<<"List of odd numbers :";
for(i = 0; i<k ; i++)
{
cout<<arr2[i]<<" ";
}
return 0;
}
Instead of setting elements of two arrays just output at first even numbers in the given range and then odd numbers.
For example
#include <iostream>
int main()
{
std::cout << "Enter the upper bound: " ;
unsigned int n = 0;
std::cin >> n;
std::cout << "List of even numbers :";
for ( unsigned int i = 0; i < n; i += 2 )
{
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "List of odd numbers :";
for ( unsigned int i = 1; i < n; i += 2 )
{
std::cout << i << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look like
Enter the upper bound: 10
List of even numbers :0 2 4 6 8
List of odd numbers :1 3 5 7 9
Quick and dirty solution.
#include <iostream>
int main()
{
int upper;
std::cout << "Enter the upper bound :";
std::cin >> upper;
std::cout<<"List of even numbers :";
for (int i=0; i<upper;i+=2)
std::cout <<i<<" ";
std::cout <<"\n";
std::cout<<"List of odd numbers :";
for (int i=1; i<upper;i+=2)
std::cout <<i<<" ";
return 0;
}
I'll not analyze the rest of your code but focus on the question:
is there any way to get rid of arrays in this program?
Since you can't use std::vector<int> you could allocate the memory dynamically yourself.
#include <cstddef>
#include <iostream>
#include <memory>
int main()
{
size_t upper;
std::cout << "Enter the upper bound :";
if(not (std::cin >> upper)) return 1; // input failed, exit
// create unique_ptr<int[]> poiting to an array of "upper" number of elements:
auto arr1 = std::make_unique<int[]>(upper);
auto arr2 = std::make_unique<int[]>(upper);
// ...
im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}
How do I display 3 names at a time, pausing to let the user press a key before the list continues displaying.
My code now only loops the first 3 values of the array
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
for (int j = 0; j < 3; j++)
{
cout << names[j] << endl;
}
system("pause");
}
}
I changed the answer based on your comment. Instead of sleeping we just pause and wait until user inputs anything into the keyboard. Also a note, since you're using namespace, you don't need to include std::, I decided to use it since I was unsure what way you wanted.
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
int pauseCheck = 0; //new var
string names[10]; //size of array
for (int i = 0; i < 10; i++) {
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++) {
cout << names[k] << endl;
pauseCheck++; //increments check
if (pauseCheck == 3) { //if equals 3
system("pause"); //we pause till user input
pauseCheck = 0; //reset pause check
}
}
system("pause"); //last and final pause before program ends
}
Here's another way of doing it which I think is a little more straight forward:
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
cout << names[k] << endl;
if((k + 1) % 3 == 0) // everytime k + 1 is divisible by 3, let user hit a key
system("pause");
}
}
You can wait for a Enter-Press with another std::cin, just write into an garbage value.
I think other ways are not platform independent. You could ofcourse use the windows api, or unix stuff to get a key press.
Prime number part code is not working, it says i cant compare pointer and interger. I not sure what to do.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int input[20] , i;
for (int i = 0; i < 20 ; i++)
{
cout << " Enter 20 interger numbers from 0 to 99 "<< endl;
cin >> input[i];
}
for (i=2; i<20 ; i++) // edited as per the comments below
{
if(input==i) // there is error here saying cant compare like this
{
cout << input << endl ;
}
}
return 0;
}
Your algorithm for finding prime numbers is wrong. Try this one. This is working solution.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int input[20] , i,prime,t;
cout << " Enter 20 interger numbers from 0 to 99 "<< endl; //
for (int i = 0; i < 20 ; i++)
{
cout << " Enter a number"<< endl; //
cin >> input[i];
}
cout << " prime numbers are: "<< endl; //
prime=1;
for (i=0; i<20 ; i++)
{
for(t=2;t<input[i];t++)
{
if(input[i]%t==0){
prime=0;
break;
}
}
if(prime==1 && input[i]!=0){
cout << input[i] << endl;
}
prime=1;
}
return 0;
}
Your prime check is incorrect. The code:
for (i=2; i<input ; i++)
{
if(input==i)
{
cout << input << endl ;
}
}
does not serve any purpose. When you refer to input in i < input, you are actually referring to a pointer which points to the first element of the array. What you actually need to do is permute over all the elements of this array and check if they are prime or not. Something like what is shown below should work:
bool flag;
for (i=0; i<20 ; i++) //Go over all 20 elements in array
{
flag = true;
for(int j = 2;j < input[i];j++)
{
if(input[i] % j == 0)
{
flag=false;
break;
}
}
if(prime==true)
cout << input[i] << endl;
}
Here, if the number in input[i] is divided by any number from 2 to input[i] and gives the remainder 0 (checked by modulus - % - operator), it is not prime. We initially consider it to be prime and set the flag to true. If we find out it is divisible by something other than 1 or itself, we set flag to false and the break statement breaks out of the inner for loop as no further checks are required.
Here, input[i] refers to the element with the ith index in the array with 0 indexing.
Thanks for the help. I got the full working code here. Just a quick question, it there anything else I need to change to make it better.
#include <iostream>
using namespace std;
int main()
{
int i,t, max, min, x[20], even=0, odd=0, prime;
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i];
}
min=x[0];
max=x[0];
for(int i=1;i<=20;i++)
{
if(min>x[i])
{
min=x[i];
}
else if(max<x[i])
{
max = x[i];
}
}
cout<<"Max is "<< max <<endl;
cout<<"Min is "<< min <<endl;
cout << "Prime numbers are: " << endl ;
prime=1;
for (i=2; i<=20 ; i++)
{
for(t=2;t<x[i];t++)
{
if(x[i]%t==0)
{
prime=0;
}
}
if(prime==1)
{
cout << x[i] << endl;
}
prime=1;
}
return 0 ;
}