Can someone explain this line of c++? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
cout << results[rand()%(sizeof(results)/sizeof(results[0]))] << endl;
results is an array of integers: 1,2,3,4,5.
Can somebody Explain?

This will print the value of your arrayentry in a random order.
It creates a random value and limits it to the index of the arraysize by using the modulo operator %.
rand() create a random integer value in the range of 0 to RAND_MAX
sizeof(results)/sizeof(results[0]) is the size of your array as you defined it earlier in your code i.e. int results[5]
The modulo operator % combines those tww values and makes sure that the result is not bigger then the size of your array (0-4).

Looks like my previous answer was a bit terse...
cout << results[rand()%(sizeof(results)/sizeof(results[0]))] << endl;
could be broken down to
int num_elems = sizeof(results)/sizeof(results[0]);
int randomIndex = rand() % num_elems;
int randomValue = results[randomIndex];
cout << randomValue << endl;
In slightly more detail:
sizeof(results)/sizeof(results[0]) calculates the number of elements in the array results. (Note that this only works when you have access to the array definition - you can't use this with a pointer to an array.)
rand() % num_elems calculates a random number in the range [0..num_elems-1]; this is the range of the results array.
results[randomIndex] returns a single, randomly selected, element from results

rand() returns a random number.
You want a random number from the array that is of size 5. So you use the modulo operator to be sure that you're not exceeding 4 (0,1,2,3 or 4).
sizeof(results) returns the total size in bytes of the array. sizeof(results[0]) is the size of an element in that array. For example, if sizeof(results[0]) is 8, then sizeof(results) is 40, so the result will be 40/8 which is 5, which is the array's size.

Related

How to find the power of the array elements? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need to check if A[0] ^ A[1] ^ A[2] ... ^ A[N] is even or odd.
Is this code right??
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
int main(){
long long n;
cin >> n;
int a[n];
long int mp;
for(int i = 0; i < n; i++){
cin >> a[i];
mp = pow(a[i], a[i+1]);
}
if (mp % 2 == 0){
cout << "YES";
}
else cout<<"NO";
}
Do the maths first.
Consider that
odd * odd * odd * odd .... * odd == odd
You can multiply any odd factors and the result is always odd. Whether a number is odd or even is equivalent to: It has a prime factor 2. Some integer raised to some other integer cannot remove a prime factor, it can also not add a prime factor when it wasn't present before. You start with some x and then
x * x * x * x * x .... * x = y
has the same prime factors as x, just with different powers. The only exceptions is to get an odd number from an even one when you raise a number to power 0, because x^0 = 1.
Ergo, you are on the wrong track. Instead of brute force raising numbers to some power you merely need to consider ...
is A[0] odd or even
is any of the other elements 0 (remember that (a^b)^c) is just a^(b*c))
Thats it.
I will not write the code for you to not spoil the exercise. But I should tell you whats wrong with your code: pow is not made to be used with integers. There are many Q&As here about pow returning a "wrong" result, which is most often just due to wrong expectations. Here is one of them: Why does pow(n,2) return 24 when n=5, with my compiler and OS?. Moreover, you are accessing the array out of bounds in the last iteration of the loop. Hence all your code has undefined behavior. Output could be "maybe" or something else entirely. Also, your code merely calculates a[i] ^ a[i+1] and after the loop you only consider the very last result. Thats not what the task you describe asks for. Last but not least, Why aren't variable-length arrays part of the C++ standard?. Use std::vector for dynamically sized arrays.

What is the median value is decimal? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a program to find the median of an array in CPP. I am not sure if I have a clear idea about what a median is. As far as I know, I've written my program to find median but when the array is even-numbered, I'm confused whether I should print the ceiling or ground value of division ofthe decimal output I get when I divide the middle two elements from the array.
using namespace std;
void findMedian(int sortedArray[], int N);
int main()
{
int ip[4] = {1, 2, 5, 8};
findMedian(ip, 4);
}
void findMedian(int sortedArray[], int N)
{
int size = N;
int median;
if ((size % 2) != 0)
{
median = sortedArray[(size / 2)];
}
else
{
median = (sortedArray[(size / 2) - 1] + sortedArray[size / 2]) / 2;
}
cout << median;
}
Thanks in advance, also if anyone can give the literal purpose of finding a median, I'd appreciate and it'd help me not ask this question again when I have to deal with Median.
Pardon my English.
on odd array the median is unique, but in a even array there are two medians: the lower median (the one in (n/2)th position) and the upper median (the one in (n/2+1) th position). I usually always see that the lower median is used as "median" for even arrays.
In this case you need only one formula for even and odd arrays:
medianPosition = n/2; // integer division
median = sortedArray[medianPosition];
Note that it is true only for array where indices starts with zero (like C/C++).

Why is My Program Only Sometimes Correctly Identifying the Highest and Lowest Values in an Array? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am writing a homework program which, among other things, must be able to output the highest and lowest values in an array. The ten numerical values in this array, referred to as scores int he context of the program are inputted by the user early on. I have two functions which calculate the highest and lowest value int he array respectively. For reasons I cannot figure out, the getHighScore function only sometimes correctly determines the largest value depending on what values have been stored int he array and the value returned by the getLowScore function always determines that the lowest number is the same one that is returned by getHighScore.
I have already tried comparing my code to other code both from my own past programs and online that is meant to serve the same purpose, and although it was nearly identical to one such example, my getLowScore function still never works as intended. I believe it also worth including the function in my program which calculates the average of the array's contents below, as although it uses different commands, it always works as intended and I am not sure what sets it apart from the other two functions.
//Stores the highest score in the array in the "highest" variable
int getHighScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The largest value in the array is stored in the "highest" variable
{
int highest = 0;
highest = somearray [0]; //Set highest to the first element in the array
for (int index = 1; index < size; index++)
{
if (somearray [index] > highest);
highest = somearray [index];
}
return highest;
}
//Stores the lowest score in the array in the "lowest" variable
int getLowScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The lowest value in the array is stored in the "lowest" variable
{
int lowest = 0;
lowest = somearray [0]; //Set lowest to the first element in the array
for (int index = 1; index < size; index++)
{
if (somearray [index] < lowest);
lowest = somearray [index];//
}
return lowest;
}
//Stores the mean of all the values in the array in the "average" variable
int getAvgScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The average value in the array is stored in the "average" variable
{
int totalScore = 0;
double average = 0;
//average = somearray [0]; //Set highest to the first element in the
array
for (int index = 0; index < size; index++)
{
totalScore += somearray [index];
}
average = totalScore / 10;
return average;
}
This code compiles, but logic errors prevent me from achieving the desired outcome.
It's these lines right here:
if (somearray [index] > highest);
highest = somearray [index];
Should be something like this instead:
if (somearray [index] > highest) {
highest = somearray [index];
}
Note: You may or may not be making the same mistake more than once, so I'd double check if I were you.
I think #Chipster's answer is correctly, another suggestion to avoid that kinds of error is treat your compile warning as error.
Because if you check you compile warning carefully, you will find at least one warning(I'm use clang)
warning: if statement has empty body [-Wempty-body]
if (somearray [index] > highest);
The only issues I can see with your getLowScore/getHighScore methods is that they may go very wrong if the size is zero. Otherwise, there are no problems there. Without any additional context provided as to where & how those methods are used, it's not possible to help much further sadly.
Only other issue I can see in the getAvgScore method is that you want to append .0 to the 10 here:
average = totalScore / 10.0;
(otherwise the average can only ever end up being a whole number). Also, would it be sensible to return a double from getAvgScore? If thats cast to an int where its used, so be it. But at least you are returning the additional digits to the right of the decimal place in case you need them.

Single number as xy coordinates [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm using a very specific random number generator to produce numbers between 0 and 2^20. I am trying to access elements of a two dimensional array using this number.
Because myArray[x][y] can be represented as myArray[x*a + y] (where 'a' is the number of elements in the second dimension), shouldn't I be able to turn my single random number into 2-dimensional coordinates? The array in question is 2^10 by 2^10 exactly, so I thought it would be:
int random = randomize(); //assigned a random value up to 2^20
int x = floor(random / pow(2, 10));
int y = random % pow(2, 10);
myArray[x][y] = something(); //working with the array
The arrays elements are not being accessed as predicted and some are not being accessed at all. I suspect a bug in my logic, I've checked my program's syntax.
No I can't use two random numbers to access the array.
No I can't use a one dimensional array.
Just checking this would be the correct math. Thank you.
In C++ ^ is a binary bitwise XOR operator, not a power operator.
An idiomatic expression for obtaining powers of 2 in C++ is 1 << n, so you can rewrite your expression like this:
int x = floor(random / (1<<10));
int y = random % (1<<10);
The reason the left shift by n works like raising 2 to the power of n is the same that adding n zeros to one in a base-ten system multiplies the number by n-th power of ten.
2^10 isn't 1024 in C++.
Because in c++ ^ is XOR (a bitwise operator ) c++ operators
include <math.h> /* pow */
int main ()
{
int random = randomize(); //assigned a random value up to 2^20
int x = floor(random / pow(2,10));
int y = random % pow(2,10);
myArray[x][y] = something(); //working with the array
return 0;
}
Hope this helps.

C++ Arrays & pointers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
can anyone help me with the following inequalities for arrays:
#include <stdio.h>
#define PRD(a) printf("%d", (a))
#define NL printf("\n")
int a[] = {0,1,2,3,4};
int main ()
{
int i;
int*p;
for (i=0; i<=4; i++)
PRD(a[i]);
NL;
for (p=&a[0]; p<=&a[4]; p++)
PRD(*p);
NL;
for (p=&a[0]; i=0; p+i<=a+4; i++)
PRD(p[i]);
NL;
for (p=a, i=0; p+i<=a+4; p++, i++)
PRD(*(p+i));
NL;
Basically I dont understand the 4 loops, please kindly help to explain to me!
A detail here, the "inequalities" you're asking about are about pointers, not arrays. Think of comparing memory locations, and the following will be easier to follow.
First one should be pretty straightforward: print each element of the array in order (a[0], a[1], etc.)
In number 2, p is the address of element 0 of a. p++ increases that address to be address of the next element in the array.The termination condition can be read as "p is less or equal the address of element number 4 of the array". To put some values and make this concrete: imagine &a[0] is 200, as a consequence &a[4] is 216, as p is incremented it becomes 204, 208, 212, 216, and finally 220.
When it becomes 220 the condition becomes false, and the loop ends.
Number 3's left side is similar but instead of increasing p it adds i to p. Note that thanks to the magic of pointer arithmetic p + 1 is actually p + i*(sizeof(*p)). The sequence is exactly the same as in case 2. BTW, initialization should be p = &a[0], i=0; (note the comma before the i). For the right side (a+4), the plain a means the address of the first element of a (this is the C equivalency between pointers and arrays, a topic full of subtleties and pain). a + 4 is thus equivalent to &a[4].
Number 4 is there to mess with your head. The information above should be enough to translate the initialization and condition; but having both i++ and p++ means you will be advancing 2 elements each iteration.
The use of the preprocessor here is likely obscuring what gets called, try expanding manually to follow up more easily. and PRD should be adding a space after each number for easier reading.