array input not working - c++

The question:
Input data will give the number of test-cases in the first line.
Then test-cases themselves will follow, one case per line.
Each test-case describes an array of positive integers with value of 0 marking end. (this zero should not be included into calculations!!!).
Answer should contain average values for each array, rounded to nearest integer (see task on rounding), separated by spaces.
Problem:
Works fine but at third indice sum is assigned value of arrayInput and it messes everything up. Why does this happen and how can I fix it?
//araytest
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
//var
int i = 0;
int array[13] = {};
//take in # arrays
cin >> i;
for(int x = 0; x<i; x++ )
{
//reset variables (for every array)
float arraySize = 0,
sum = 0, avg = 0;
int indice = 0,
arrayInput = 0;
while(cin >> arrayInput){
if(arrayInput == 0)
{
if(indice == 0)
{
arraySize = 1; /*if only 0 put in first indice
to prevent divide by 0 */
break;
}
else
{
arraySize = indice; // 0 doesn't count
break;
}
}
sum += arrayInput;
array[indice] = arrayInput;
arrayInput = 0;
indice++;
}
avg = round(sum/arraySize);
cout << avg << " ";
}
return 0;
}

First, like other people said, the array you used in this code is totally useless. It did nothing but save arrayinput.
Second, you let arraysize sum avg to be type float. However, arrayinput is assigned to be integer!! That means you never get result like this 2.xxx. So the type you declare for variables is meaningless. They should have same type declaration. I don't understand why you code does not work well. Because if you enter integer number, you wont get anything wrong. But it will crash if you give number like 2.xxx or x.xxx.

Related

I want to know the error in my code. This is to print sum of all even numbers till 1 to N

#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
Let's step through this. Imagine we're on the loop where i = 2 and you've entered N = 5. In that case...
while(i <= N)
2 <= 5 is true, so we loop
if(i%2 == 0)
2 % 2 == 0 is true, so we enter this branch
sum = sum + i;
Update sum, then head back to the top of the loop
while(i <= N)
Neither i nor N have changed, so 2 <= 5 is still true. We still loop
if(i%2 == 0)
2 % 2 == 0 is still true, so we enter this branch again...
Do you see what's happening here? Since neither i nor N are updated, you'll continue entering the same branch and looping indefinitely. Can you think of a way to prevent this? What would need to change?
Also note that int sum; means that sum will have a garbage value (it's uninitialized). If you want it to start at 0, you'll need to change that to
int sum = 0;
You're looping infinitly when i is even because you don't increase it.
Better option would be this if you want to use that while loop :
while(i<=N)
{
if(i%2 == 0)
sum = sum + i;
i=i+1;
}
cout << sum;
If you don't need to do anything when the condition is false, just don't use an else.
No loops are necessary and sum can be evaluated at compile time if needed too
// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
unsigned int m = (n / 2);
return m * (m + 1);
}
int main()
{
// compile time checking of the function
static_assert(sum_of_even_numbers_smaller_then(0) == 0);
static_assert(sum_of_even_numbers_smaller_then(1) == 0);
static_assert(sum_of_even_numbers_smaller_then(2) == 2);
static_assert(sum_of_even_numbers_smaller_then(3) == 2);
static_assert(sum_of_even_numbers_smaller_then(7) == 12);
static_assert(sum_of_even_numbers_smaller_then(8) == 20);
return 0;
}
int main(){
int input; //stores the user entered number
int sum=0; //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1) //this check the number to be bigger than one means must be positive integer.
goto repeat; // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
if(i%2==0){
sum=sum+i;
int j=0;
j=j+1;
cout<<"Number is: "<<i<<endl;
}
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}
Copy this C++ code and run it, it will solve your problem.
There are 2 problems with your program.
Mistake 1
The variable sum has not been initialized. This means that it has(holds) an indeterminate value. And using this uninitialized variable like you did when you wrote sum = sum + i; is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.
This is why it is advised that:
always initialize built in types in local/block scope.
Mistake 2
The second problem is that you're not updating the value of variable i.
Solution
You can solve these problems as shown below:
int main(){
int i = 1;
int sum = 0; //INITIALIZE variable sum to 0
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1; //update(increase i)
}
cout << sum;
}
1For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions that: there are no restrictions on the behavior of the program.

Convert number in binary and print out as matrix (C++)

Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}

(C++) Finding all prime numbers between two integers (without using sieve of Eratosthanes)

I'm trying to find all the prime numbers between two integers and place them in an integer array.
The catch is that i have to use a specific method of doing so (divide each subsequent integer by all the primes in my array). So I can't use the sieve of Eratosthanes or any other 'easier' methods.
My code successfully prompts the user for two integers, but for now I do not use either of them. First I want to make sure the program works for values between 0 and whatever, in this case 200 just to test it.
Problem is, when I run the program and print the first 20 or so values in the array, I'm getting
2, 3, 5, 7, 11, 200, 0, 0, 0, 0, 0, 0 ...... more zeroes.
The first 5 values are correct because they start in the array, but after that the whole thing goes haywire.
I've worked through my nested loop by hand for a couple values and it SEEMS like it should work. I feel like there's a specific array property that I'm overlooking.
Here's my code:
#include "stdafx.h"
#include "iostream"
#include "climits"
#include "cmath"
#include "array"
using namespace std;
int main()
{
// declare variables to store user input
int lowerBound, upperBound;
// prompt user for lesser and greater integers and store them
cout << "Program to find all primes between two integers." << endl;
cout << "Enter lesser integer: " << endl;
cin >> lowerBound;
cout << "Enter greater integer: " << endl;
cin >> upperBound;
// if statement to switch the input variables if the user accidentally enters them backwards
if (lowerBound > upperBound) {
int temp = lowerBound;
lowerBound = upperBound;
upperBound = temp;
}
// initialize int array with the first 5 primes
int primes[100] = { 2, 3, 5, 7, 11 };
// loop to find primes between 12 and 200 (since we already have primes from 1-11 in the array)
for (int i = 12; i <= 200; i++) {
// the maximum divisor needed to determine if the current integer being tested is prime
double maxDivisor = sqrt(i);
// variable for the current size of the array
int size = 5;
// boolean variable is set to true by default
bool isPrime = true;
for (int j = 0; j < size; j++) { // changed "j<=size" to "j<size"
int remainder = (i % primes[j]);
// once the maximum divisor is reached, there is no need to continue testing for the current integer
if (primes[j] > maxDivisor) {
break;
}
// if the remainder of divison by a prime is 0, the number is not prime, so set the boolean variable to false
if (remainder = 0) {
isPrime = false;
}
}
// if isPrime is still true after the nested loop, the integer value being tested will be placed in the next element of the array
if (isPrime == true) {
primes[size] = i;
// since we added to the array, increment size by 1
size++;
}
}
// display the first 20 values in the array for debugging
for (int k = 0; k < 20; k++) {
cout << primes[k] << ", ";
}
system("pause");
return 0;
}
This here
if (remainder = 0) {
isPrime = false;
}
Needs to be changed to
if (remainder == 0) {
isPrime = false;
}
Because = does assignment, not comparison. So what remainder = 0 does it setting remainder to 0, and then it returns that 0, which gets casted to false, which is on of the reasons why it's not finding any primes.
Also, as Fantastic Mr Fox pointed out, for (int j = 0; j <= size; j++) needs to be changed to for (int j = 0; j < size; j++).
Also, did your compiler issue any warnings? If not, try to see if you can set it to be more strict with warnings. I figure most modern compilers will give you a hint at if (remainder = 0). Getting useful warnings from the compiler helps a lot with preventing bugs.
Edit:
As Karsten Koop pointed out, you need to move the int size = 5; out of the loop, to before the for (int i = 12;. With those changes, it's now working on my machine.
Last but not least, a tip: instead of if (isPrime == true), you can just write if (isPrime).

While loop being inefficient and not working

Ok, well, I'm writing a program for a store (just a project to learn c++) and I'm having a problem. The white loop doesn't seem to do what it's supposed to, the program just goes through it.
I have a function:
int decimali_float (pole &artikli){
int num = artikli.cena;
int count = 0;
num = abs(num);
num = num - (int)num;
while(num >= 0.0000001){
num *= 10;
count++;
num -= (int)num;
}
return count;
}
And my struct is this :
struct pole{
int sifra;
string opis;
float cena;
int vlez_kol;
int izlez_kol;
float dan_stapka;
float iznos;
int datum;
};
And I've got an array declared for the struct:
pole artikli[100];
And here's my code where the while loop gets skipped.
for (int i = 0; i < 5; i++){
while(!(cin >> artikli[i].cena) || decimali_float(artikli[i]) > 2){
cout << "Error, try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
Where is my mistake?
decimali_float is a function to count the decimals of a number.
the element cena of the struct means price in English.
pole artikli[100] is the amount of elements(articles) in the struct
Is it only me, or num is an integer value which is explicitly set to value equal or below 0:
int num = artikli.cena;
num = abs(num);
num = num - (int)num;
Obviously it will always be less than whatever non-zero constant it is compared too and the while loop will get skipped.
Update
It appears that the main question was already addressed in comments. As for the follow-up question, instead of counting decimal places one may simply check, whether there is a residue from subtracting an adjusted "cena" from the original one (assuming cena is positive for now):
double cena1 = cena * 100;
if ((cena1 - floor(cena1)) > 0.000001)
// error condition here

What is wrong with this C++ code? 3n+1 in programming-challenges/UVa

The Programming-Challenges website marked it as a wrong answer. I checked with sample inputs and they were all correct. I added an optimization to the code, I made it so it doesn't check numbers that are known to be in another number's sequence, since it would be a subsequence and obviously have a shorter cycle length.
Also I just got back into programming so the program isn't too terse but I hope it is readable.
Here is the code:
#include <iostream>
#inclue <vector>
struct record
{
int number;
int cyclelength;
};
void GetOutput(int BEGIN, int END)
{
//determines the output order at the end of function
bool reversed = false;
if (BEGIN > END)
{
reversed = true;
int temp = BEGIN;
BEGIN = END;
END = temp;
}
vector<record> records;
for (int i = BEGIN; i <= END; ++i)
{
//record to be added to records
record r;
r.number = i;
r.cyclelength = 1;
records.push_back(r);
}
int maxCycleLength = 1;
//Determine cycle length of each number, and get the maximum cycle length
for (int i =0;i != records.size(); ++i)
{
//
record curRecord = records[i];
//ABCD: If a number is in another number's sequence, it has a lower cycle length and do not need to be calculated,
//set its cyclelength to 0 to mark that it can be skipped
if (curRecord.cyclelength != 0)
{
//
while (curRecord.number != 1)
{
//next number in the sequence
int nextNumber;
//finds the next number
if (curRecord.number % 2 == 0)
nextNumber = curRecord.number / 2;
else
{
nextNumber = curRecord.number * 3 + 1;
//if nextNumber is within bounds of input, mark that number as skippable; see ABCD
if (nextNumber <= END)
{
records[nextNumber - BEGIN].cyclelength = 0;
}
}
curRecord.number = nextNumber;
curRecord.cyclelength += 1;
}
maxCycleLength = max(curRecord.cyclelength, maxCycleLength);
}
}
if (reversed)
{
cout << END << " " << BEGIN << " " << maxCycleLength;
}
else
{
cout << BEGIN << " " << END << " " << maxCycleLength;
}
}
int main(){
//The first and last numbers
vector< vector<int> > input;
int begin, end;
while (cin >> begin >> end)
{
//storage for line of input
vector<int> i;
i.push_back(begin);
i.push_back(end);
input.push_back(i);
}
for (int i = 0;i != input.size(); ++i)
{
GetOutput(input[i][0], input[i][1]);
cout << endl;
}
return 0;
}
I'll try to give you a hint to nudge you into figuring out the problem.
The sample inputs are good as a smoke test, but they're often not good indicators that your program can handle the more extreme test cases too. You should always test with more than the sample inputs. If my calculations are correct, your program will produce the wrong result for the following input:
999000 999250
For reference, the expected output for this is:
999000 999250 321
There, I narrowed your search space down to 251 cycles :) Now get your debugger and finish the job.
Anyway, what follows is the full explanation and solution in spoiler markup. Mouse over the blank space if you want to read it, stay put if you want to figure it yourself.
The problem states that i and j are less than one million and that no operation overflows a 32-bit integer. This means that no intermediate result will be larger than 4294967295. However, an int is a signed type, so, even if it has 32-bits, it only has 31 bits for the absolute value, and thus cannot fit any number larger than 2147483647. Numbers larger than these occur in the cycles of for several Ns in the problem range, one of which is 999167. Using an unsigned 32 bit integer is one solution.
There is nothing mystery. The largest intermediate number overflows 31-bit of the signed integer. You need to declare record.number and nextNumber as unsigned int.