accessing an array [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
i am declaring a global array,and then assigning the values inside a if statement. But when i am using the array in another if statement the array has different values other than i assigned previously.
For example:
int arr[5];
xyz(bool p,bool q)
{
if(p)
{
for(int i=0;i<5;i++)
{
arr[i]=rand()%100;
}
}
if(q)
{
for(i=0;i<5;i++)
printf("%d",arr[i]);
}
}
can anyone help??

Well, if p != q then any changes you make to arr in the first conditional will not be printed when you enter the second conditional. If arr was never initialized, it will almost certaninly not have the values you expect.
Edit: Based on your comment below, Try using a std::vector<int> instead of a C style integer array, as in:
#include <vector>
std::vector<int> arr(5); // was int arr[5]
Also a couple suggestions:
Where practical (which is almost, but not quite always) you should be using the standard containers in C++. They tend to be better behaved than C style arrays.
Use of global variable can sometimes lead to more problems than they solve. Recommend you make arr a local variable and pass it as a parameter where needed. This helps people looking at your code know what it needs and what it accesses without having to actually dig through the code to see it all. It's possible (perhaps even likely) that something else is changing arr without you knowing it. If you always pass arguments and refrain from using globals, this will help you discover where it's being changed.
So, combining these I would recommend doing something like:
#include <vector>
#include <iostream>
xyz(std::vector<int>& arr, bool p, bool q)
{
std::vector<int>::iterator ai;
if(p)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
*ai = rand() % 100;
}
}
if(q)
{
for(ai = arr.begin(); ai != arr.end(); ++ai)
{
std::cout << *ai << std::endl;
}
}
}
int main()
{
std::vector<int> arr(5);
xyz(arr, true, false);
xyz(arr, false, true);
return 0;
}

Try adjusting your first code block to something more like this:
if (p) {
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
printf("%i: %d\n", i, temp);
arr[i] = temp;
}
}
Now, you will get a listing of the random values before they are written into the array. Compare this list to what you get when you read them from the array later.
Update: I ran the above modification to your code on Codepad, and I am seeing the exact same values both times.

I don't even see why you're adding those 'bool' variables since you're not creating to never run it!
So just use this code [ which is the same as beta's version];
int temp;
for (int i=0; i<5; i++) {
temp = rand() % 100;
cout << i << temp << endl;
arr[i] = temp;
}

Related

How to find the sum of numbers that have digits higher than 5 [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
so I want to write a function that returns the sum of all numbers in an array who's digits are higher then 5 so for example if the array is [12, 66, 23, 67] the answer would be 66+67
This code summs all the numbers in the array and I can'\t figure out why
using namespace std;
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){
n[i]= n[i]/10;
}
else break;
}
S=S+a;
}
return S;
}
int main()
{
int n[3], i;
for(int i=0; i<3; i++){
cin>>n[i];
}
cout<<func(n, 3)<<endl;
return 0;
}```
S=S+a This piece of code is out of your while loop and inside for loop, this will add all the elements in the array
The main problem is that you are not checking when you should add a to S.
These lines are causing the problem:
int func(int n[], int size){
int digit, S=0, a;
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
if(digit>=5){ // Wrong. Do "digit > 5"
n[i]= n[i]/10;
}
else break; <--- exiting this while loop
}
S=S+a; <--- ...but still adding?
}
return S;
}
You are breaking the loop, but still adding to the sum.
You should use a flag. Your inner loop would look something like this:
// We need to check if each digit is valid
bool each_digit_greater_than_5 = true;
// As long as we have digits left and all previous digits were valid
while(n[i] != 0 && each_digit_greater_than_5)
{
// Extract a digit
digit = n[i] % 10;
// If valid, get next digit to extract
if(digit > 5)
{
n[i] /= 10;
}
// Else, exit the loop
else
{
each_digit_greater_than_5 = false;
}
}
And then, simply check if each_digit_greater_than_5:
// If number was valid
if(each_digit_greater_than_5)
{
// Add to sum
S = S + a;
}
Extra Notes:
How you write the code is often more important than what you write.
Here are (some) food for thoughts.
Use better formatting: The whole block of code should be uniformly indented. This:
...
for(int i=0; i<size; i++){
a= n[i];
while( n[i]!=0){
digit= n[i]%10;
...
is both confusing and unclear. Use same indentation for each separate block:
...
for(int i=0; i<size; i++){ // The base block
a= n[i]; // new block start, add indent
while( n[i]!=0){ // same block, same indent
digit= n[i]%10; // new block, add indent
...
Use better naming: Don't use S, a and n unless they are very clear.
digit is a good choice, so credits for that!
Here, it is better to use:
sum_of_special_numbers
and
array
and
current_number
instead of S, n and a.
Comment!: Another very important part of programming (Note: not coding).
Are you coding?
Don't care if anyone understands it or not, just doing it cause they said so.
Or programming?
Making a clear, maintainable and debuggable code.
You decide!
Since this question is tagged with C++, I want to give an additional answer that uses C++ and especially modern C++ algorithms. I added also comments to the code and used meaningful variable names. I recommend that you try to do the same in the future.
What is the example code doing?
First, it informs the user about the software and asks, how many values should be checked and added. The values will be stored in a std::vector. With std::copy_n and the std::istream_iterator we read the values given by the user. The std::istream_iterator simply calls the extractor operator >> in the copy loop.
Then we call the subfunction to calculate the sum and show it to the user.
The subfunction consists of one Lampda definition and one std::accumulate statement. That's all.
The lambda converts the int to a std::string and then checks if any of the characters in the number is lower than '5'. Then it returns an inverted result.
So, you see, with C++, the implementation get's very simple:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
int sumOfNumbersWithDigitsGreaterThan5(const std::vector<int>& v) {
// Create a lambda that checks, if all digits are greater than 5
auto check5 = [](const int i) -> bool { std::string s{ std::to_string(i) };
return !std::any_of(s.begin(), s.end(), [](const char c) { return c <= '5'; }); };
// Calculate the sume of all given values in the vector with all digits greater than 5
return std::accumulate(v.begin(), v.end(), 0,
[&](const int init, const int i) { return init + (check5(i) ? i : 0); });
}
int main() {
// Inform the user, what to do
std::cout << "Sum of all numbers having all digits greater than 5\n\nHow many numbers to you want to sum?: ";
// Get the number of values that we want to sum up. Check plausibility
if (int numberOfValuesToCheck{}; (std::cin >> numberOfValuesToCheck) && (numberOfValuesToCheck > 0)) {
// Create a std::vector for our values having the requested number of elements
std::vector<int> values(numberOfValuesToCheck);
// Read the requested number of elements from std::cin to the values vector
std::copy_n(std::istream_iterator<int>(std::cin), numberOfValuesToCheck, values.begin());
// Show result
std::cout << "\n\nThe sum for all numbers with all digits greater 5 is: " <<
sumOfNumbersWithDigitsGreaterThan5(values) << "\n";
}
else {
std::cerr << "\n\n*** Error: Wrong input\n";
}
return 0;
}
Of course there are many many other possible solutions . . .

Functions that checks the greatest common divisor of composite figures in an array

#include <iostream>
using namespace std;
int sal_sk (int sal){ // If sal is a composite figure, then true, if its not then false.
for (int i = 2; i <= sal; i++){
if(sal%i==0)
return true;}
return false;
}
int lkd(int a,int b){ // Checks the gcd
int c;
while(b > 0) {
c = b;
b = a % b;
a = c;
}
return a;
}
int main(){
int ok;
do{
int n;//Number of elements
int*a; //
int sal;
cout<<"Put in the number of elements"<<endl;
std::cin >> n;
cout<<"Input"<<n<<"elements"<<endl;
std::cin >> *a;
int *array = new int[*a];
int rez = a[0];
for(int i=1; i<n; i++) {
if(sal_sk(a[i]==true))
rez = lkd(rez, a[i]);
delete [] array;
}
So i have this code and I cant see the problem why it doesnt work, can someone help me? The functions should work so it should be their fault, i think i dont understand the arrays so good so I think there is the problem. The comments will help you understand the code thanks!
I didn't even need to read all the way down to the array part to see that this program would never work.
I'll give you a clue: sal_sk will ALWAYS return true. Also, true and false are not int.
As far as the rest of the program is concerned, it's pretty much unsalvageable. You have an open do statement that leads nowhere, main is incomplete, the ok and sal variables are unused (???). You're trying to cin data into an uninitialized pointer. That new statement uses the wrong variable, and besides it's not where it's supposed to be. The for loop starts indexing from 1 which is wrong, should be 0, and the if has the parentheses in the wrong place. The body of the loop itself destroys the array.
I suggest you delete the main function completely and start from scratch. Apart from reading a C++ book, the best suggestiong I can give you is to read your code line by line and explain to yourself what it does. If you can't, go back to the book.
A couple of hints: you don't need any do...while statement, you wanna initialize the array before you ask for the input, and you wanna ask for the input n times.

Part 1: Referencing an Array Without Using Pointers and only Subscripting | Part 2: "..." with Pointers [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
#include <iostream>
#include <time.h>
using namespace std;
void my_func();
int main()
{
float start_time = clock();
cout << "Starting time of clock: " << start_time;
cout << endl << endl;
for (int i = 0; i < 100000; i++)
{
my_func();
}
float end_time = clock();
cout << "Ending time of clock: " << end_time;
cout << endl << endl;
}
void my_func()
{
int my_array[5][5];
}
I need to write a program that does a large number of references to elements of a two-dimensional array, using only subscripting. This is really a two-part project, but I'm only concerned with getting the first part right. The second part allows the use of pointers but for now, I am only subject to "subscripting" (indices?). Any advice on how to proceed?
I have successfully completed the first part thanks to Volkan İlbeyli. I am now moving on to the second part:
I need to write a program that does a large number of references to elements of a two-dimensional array, using pointers and pointer arithmetic. Here's what I have so far:
#include <iostream>
#include <time.h>
using namespace std;
void my_func();
int main()
{
float start = clock();
for (int i = 0; i < 100000; i ++)
{
my_func();
}
float end = clock();
cout << "Ending time of clock: " << (end - start) / ((double)CLOCKS_PER_SEC);
}
void my_func()
{
int my_array[10][10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
*(my_array+i+j);
}
}
}
I have done the first part and now I am working on the next part. I just want to know if I've missed anything. The code works fine and so does the program. Pointers are not my strongpoint and it took me a lot of time on the Internet to find my answers. Asking for a technical standpoint now on pointers and "pointer arithmetic".
Well, even though I could not understand the purpose or the meaning of the task you are attempting, if I didn't get it wrong, you are asked to reach to the elements of the 2D array by using indices.
Considering your code, in your my_func() you do not access to the elements. You only declare that you will use a 2D array with size 5x5. To access the elements, (i think) in your case to reference the arrays, you should use for loops and indices to access the elements of the array.
I should go like this in your case:
void my_func()
{ //assuming that the usage of
int my_array[1500][500] = {0}; //square matrice is not mandatory
for(int i=0; i<1500 ; i++){
for(int j=0; j<500 ; j++){
my_array[i][j]; //no operation is done, only accessing the element
}
}
return;
}
You could also swap the for loops to access the array in a vertical manner, i.e. going through first column, then 2nd, then 3rd... That will make your referencing a 2D array by indices slower. See this post on SO why it slows down to swap the for loops, i.e. changing the row-column order into column-row.
You should also note that if you are concerned with critical time measuring of a certain event, you should include only that event when starting the clock and ending the clock. In your code, you also include the time to call cout, endl, and the calling time of my_func() which has nothing to do with the array referencing. Also I'd rather measure the time in the main() function since the accessing the 2D array doesn't require too much code. If it did require too much time, I'd call the function, declare the timing variables inside, definitely not print the starting time, start the time before the repeat-the-operations loop and stop after the loop terminates. You can see this post to have an idea about how time is measured and printed (when you need to consider seconds, or milliseconds etc.).

How to complete this for-loop that calls a function [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am having trouble trying to make a certain for-loop continue to completion in the 1D Queens problem.
First, I used goto statements for everything. Now I am trying to get rid of the goto statements by using functions instead. I will eventually get rid of all of them, but I am focusing on NR (new row) and backtrack first, since they are meant to call each other.
The for loop I am having trouble with is the one that checks if a position is safe for a queen. I point out the for-loop that does not complete in the comments.
//forward declarations
int backtrack (int board[], int& c_position);
//NR: q[c]++;
//if (q[c]==8) goto backtrack;
void NR (int board[], int& c_position) //new row
{
board[c_position]++;
if (board[c_position]==8) {backtrack(board, c_position);}
}
int backtrack (int board[], int& c_position) // backtrack
{
c_position--;
if (c_position==-1) {system("PAUSE"); exit(1);}
NR(board, c_position);
}
int main ()
{
int q[8] = {0}; //1D array, the board, all set to 0;
int c=0;
int count=0;
NC: c++; //new column
if (c==8) goto print;
q[c]=-1;
NR(q, c);
//test to see if position is safe
for (int i=0; i<c; i++) //this is the for loop I am having trouble with
{
if ( (q[i]==q[c]) || ((c-i)==abs(q[c]-q[i])) ) { NR(q, c); }
}
goto NC;
print: //printing the 1D board gives us a single line, where each number represents a row where a queen is
count++;
cout << count << endl;
for(int j = 0; j <= 7; j++)
{
cout << q[j] << " ";
}
cout << endl;
backtrack(q, c);
system("PAUSE"); return 0;
}
You're passing c by reference to a function that passes it to another function that decrements it.
That appears to foil your (outer goto-based) loop's attempt to increment it.
Anyway, that's what I'd look at more closely.

arrays and index [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
How can I enter numbers into an array such that duplicate entries are ignored?
For example, if I put 6 and then 3 into the array, attempting to then insert 6 into the the array should cause 6 to be rejected (since it is already in the array).
#include <iostream>
using namespace std;
int main()
{
int x,y;
int number;
int arr[5];
for (x=0; x<5; )
{
cout<<"enter a number:"<<endl;
cin>>number;
bool replace = True;
for (y=0; y<x; y++)
{
if (number != arr[y])
{
cout << "try next time" << endl;
replace = False;
break;
}
}
if (replace)
{
arr[x] = number;
x++;
}
}
return 0;
}
std::set<int> would do what you want. This is not indexable, though.
You could use Boost.MultiIndex to give you random access and enforce uniqueness on the same underlying list of values.
btw - asking directly for code is not recommended practice.
you have too many x++'s and you don't preset arr (maybe more style than error)
how do you know it's not working?
(put some debug code inside of if (number == arr[y]) and if (replace)
What you really want is a set. Sets cannot contain duplicate elements.
Here is a reference to the set in C++.
Just use the set as a container for your numbers. When you try to add a duplicate, it will be automatically rejected.
You don't want an array but a datastructure called Hashtable for that;
Alternatively, you might want to look up a datastructure called associative array.
You shouldn't use arrays for this. You should use, for example, std::set. Or, if you need to have an array as your data structure, you could encapsulate the array (e.g. realized through std::vector) in a class and define specific functions to access the array elements. Additionally, you could hold a std::set to provide a fast check for existing elements.
Should be :
int arr[5] = {0,0,0,0,0};
Remove the x++ from the following line:
for (x=0;x<5;x++)
Then:
bool replace=true;
for (y=0;y<x;y++)
{
if (number == arr[y])
{
replace=false;
break;
}
}
if (replace)
{
arr[x]=number;
x++;
}
Finally, remove the :
else if(number == arr[x])
{
arr[x]=number;
cout << "try next time"<<endl;
}
You can insert :
cout << "try next time"<<endl;
before the
replace=false;
Take out the x++ in the for loop, That way you will only increment that count when you enter a new number.
Also, if you want to only run the loop five times, your outer for loop should be only to x<5.
All in all your outer loop should read:
for (x=0;x<5;)
Take a closer look at where you increment x.
It looks like you want to read in a sequence of numbers eliminating any duplicates.
It also appears that the maximum number of unique numbers is 5.
int n = 0; /* The number of unique numbers read in so far */
for {;;}
cout << "enter nmber" << endl;
cin >> number;
for (x=0; x < n; ++x) {
if (number == arr[x]) goto L1; /* I love messing with peoples head by using this goto */
}
arr[n] = number;
++n;
if (n == 5) break;
L1:
continue;
}