I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:
Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568
I couldn't figure out why the last number ignores my rule.
Any help would be appreciated.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 6; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
I couldn't figure out why the last number ignores my rule.
Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be
for (int i = 0; i < 5; i++)
~
Then i will be 0 ~ 4, loop 5 times, not 6 times as your code shown.
You might use range-based for loop (since C++11) to avoid such kind of mistake:
for (auto& i : myArray) {
i = (rand() % 55) + 1;
cout << i << '\t';
}
random numbers from 1 to 54
So this is incorrect as well: (rand() % 55) + 1;
You'll need (rand() % 54) + 1;
Because you went to myArray[5] at the last time and your array don't have this place so you got it
you need to write like that:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 5; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
If you want 6 items you need to make a array for six items
int myArray[5];
this will provide 5 items where as
int myArray[6];
this will provide you 6 items
This will fix your problem
Related
Suppose I have the integer 1004.
I want to store this in the array A with the following pattern:
A[0]=1
A[1]=0
A[2]=0
A[3]=4
How can I get the value at that index ?
How can I do this in C++?
You get the last index of a number by using modulo 10 and then remove that value by dividing the number by 10.
So assume you do this:
1004 % 10 = 4
1004 / 10 = 100
Then repeat that for each digit
Using c++ static memory:
int originalNumber = 1004;
int digitArray[10] = {0};
int idx = 0;
while (originalNumber > 0)
{
int digit = n % 10;
originalNumber /= 10;
digitArray[idx] = digit;
++idx;
}
// Reverse the order of the array
std::reverse(std::begin(digitArray), std::begin(digitArray)+(idx-1));
I'm not sure if it's the most efficient way of doing this but it definitely works.
You can enter each digit in the number to the array but from the end of the array to the beginning.
For example, there is an array with the size of 4, so you get the last digit of the number like this: num % 10, and push the digit to the third index of the array.
Code example:
#define SIZE 4
int* numToArray(int num)
{
int* arr = new int[SIZE]; // assuming you already know the number of digits in the number
for(int i = SIZE-1; i >= 0; i++)
{
arr[i] = num % 10; // Enters the last digit to the array
num /= 10; // Gets rid of the last digit in the number
}
return arr;
}
Instead of ordinary integer array, I suggest you using std::vector instead.
Then, you can have something like the following:
#include <iostream>
#include <vector>
int main() {
int number = 1004;
std::vector<int> digits;
while (number != 0) {
digits.insert(digits.begin(), number % 10);
number /= 10;
}
for (auto const i : digits) {
std::cout << i << " "; // 1 0 0 4
}
// or by index
std::cout << std::endl;
std::cout << "[0]" << digits[0] << std::endl; // 1
std::cout << "[1]" << digits[1] << std::endl; // 0
std::cout << "[2]" << digits[2] << std::endl; // 0
std::cout << "[3]" << digits[3] << std::endl; // 4
return 0;
}
Demo
Adding to all the existing answers I'd like to propose a more elegant, if probably less efficient approach utilizing the many wonders of the standard library.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
auto number = 1004;
auto asString = std::to_string(number); //
std::vector<int> digits(asString.length());
std::transform(asString.begin(), asString.end(), digits.begin(), [](char c){return c -'0';});
for(auto d : digits)
{
std::cout << d << ' ';
}
}
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 3 years ago.
I want to randomize variables a and b to output a random number 1 through 4 in the format of a,b. However, when I run my following code, the output is always the same no matter how many times I run it. For example, the output is always: 4,3 (same output shown 10 times.)
What did I do wrong here? Can someone point me in the right direction?
Thanks!
#include <iostream>
using namespace std;
int main()
{
int x;
int a, b;
a= rand() % 4 + 1;
b= rand() % 4 + 1;
x = 0;
while (x < 10) {
x++;
cout << a << "," << b << endl;
}
return 0;
}
You need to set the time seed first then call rand() otherwise you'll get always the same values:
int a, b; //store random number
std::srand(std::time(0)); // set the time seed
for(int i = 0; i != 10; ++i)
{
a = rand() % 4 + 1;
b = rand() % 4 + 1;
cout << a << "\t" << b << endl;
}
Don't forget to include <ctime> header.
What did I do wrong here? Can someone point me in the right direction?
Thanks!
You are setting a and b once and therefore they have the same value. To fix this, set them inside the loop to give them a new value each iteration:
while (x < 10) {
x++;
a = rand() % 4 + 1;
b = rand() % 4 + 1;
cout << a << "," << b << endl;
}
If you don't want the same values each time, you can call
srand(time(0)); // before the loop
Background:
This problem comes from leetcode.com
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Question:
I thought of doing a recursion for this particular problem to keep repeating the squaring of the integers until we arrive at 1. I am new with recursion (just read Absolute C++ Ch 13 --- Recursion yesterday).I thought I would give this problem a shot but I am having some trouble.
When I call my function I created I should get a return of 19 since 19 is a "Happy Number", but instead my function just returns 0, and I am not sure why. I just need some help with my approach I have taken and suggestions to changes in my code.
Here is my code:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int Happy(int n) {
vector<int> nums;
int length = to_string(n).length();
for(int i = 0; i < length; i++) {
int digit = n % 10;
n /= 10;
nums.push_back(digit);
}
reverse(nums.begin(), nums.end());
int sum = 0;
for(int i = 0; i < length; i++) {
sum += pow(nums[i],2);
}
if (sum == 1) {
return n;
}
else {
return Happy(sum);
}
}
int main() {
int n = 19;
int result = Happy(n);
cout << result << endl;
return 0;
}
Again, I am not sure why I get 0 as the result, when it should return 19.
You forgot to place a return in your code, Also you n becomes 0, and you are returning n when you find sum == 1. It should return the original_num.
To Store the original number reference pass it along with your call to happy method.
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int Happy(int n, int original_num) {
vector<int> nums;
int length = to_string(n).length();
for(int i = 0; i < length; i++) {
int digit = n % 10;
n /= 10;
nums.push_back(digit);
}
//reverse(nums.begin(), nums.end());
int sum = 0;
for(int i = 0; i < length; i++) {
sum += nums[i]*nums[i];
}
if (sum == 1) {
return original_num;
}
else {
return Happy(sum, original_num);
}
}
int main() {
int n = 19;
int result = Happy(n, n);
cout << result << endl;
return 0;
}
Hope this helps!
a program that display the following output using "For Loop":
2 4 8 16 32 64 128 256 512 1024
#include <iostream>
using namespace std;
int main()
{
int n ;
for(n=1;n<=2048;n++){
n=n*2;
cout<<"\t"<<n<<endl;
}
return 0;
]
Due to the n++ in the for loop, n is incremented each iteration. Additionally, it is multiplied by 2 at the beginning of each iteration. What you need to do is either change the increment statement in the for loop to transform n how you want:
for (n = 2; n <= 1024; n *= 2) {
cout << "\t" << n << endl;
}
or use a separate loop variable to perform a set number of iterations:
int n = 1;
for (int i = 0; i < 10; i++) {
n *= 2;
cout << "\t" << n << endl;
}
use pow function of c++
#include <math.h>
int s=1;
for(i=1;i<=5;i++)
{
s=Math.pow(2, i);
cout<<s<<"\n";
}
also include math header library
As jcarpenter pointed out, your mistake is incrementing n in your for-loop in addition to n=n*2 (which can be written as n *= 2 BTW). So I've cutted the increment and moved the double operation to the loops head. Fortunatly, multiplying a number with 2 can be implemented very effiecently with a shift operation. So that's the code I would suggest:
#include <iostream>
int main(void)
{
for(int n = 2; n <= 1024; n <<= 1)
{
std::cout << n << std::endl;
}
}
I think I there is some problem in implementation of my loop!
Here's my code.
#include <iostream>
using namespace std;
int main()
{
int i=2;
long long int FiboNo[100];
FiboNo[0] = 1;
FiboNo[1] = 2;
do{
FiboNo[i]=FiboNo[(i-1)]+FiboNo[(i-2)];
cout<<FiboNo[i]<<endl;
i++;
}while(FiboNo[i]<4000000);
return 0;
}
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
i++;
} while (FiboNo[i] < 4000000);
You are incrementing i before you compare.
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
} while (FiboNo[i++] < 4000000);
is what you want to do.
Here's what's happening:
i 2
fibo[2] is 2
now i is 3
fibo[3] is 0
This has no problem, when fibo[someIndex] reaches the limit. It wont come out, because your value is always a 0.