So, the goal of the function is to add odd numbers to the array between 1 and a provided integer (inclusive). It seems like a simple task, however, I can't seem to get it to successfully add the integers to the actual array.
void populate(std::vector<int> ary, int a)
{
for (int i = 1; i <= a; i++)
{
if (i % 2 != 0)
{
ary.push_back(i);
}
}
}
The function itself isn't const, so shouldn't it be adding values to the array successfully?
EDIT: This is all done in a main, so here it is.
int main()
{
std::vector<int> loli(100);
populate(loli, 31);
for (int value : loli)
{
std::cout << value << " ";
system("pause");
}
}
EDIT 2: I've tried adding a return statement instead, however i still get the result zero.
std::vector<int> populate(std::vector<int> ary, int a)
{
for (int i = 1; i <= a; i++)
{
if (i % 2 != 0)
{
ary.push_back(i);
}
}
return ary;
}
int main()
{
std::vector<int> loli(100);
for (int value : populate(loli, 31))
{
std::cout << value << " ";
system("pause");
}
}
Your function should either return the final array after the for loop or you should pass the array as a pointer to the function.
Related
I have to create functions for print array, fill array witn descending numbers.
I created functions for printing array and creating descending array.But I faced with a problem.
If I use my own function printArray() it prints something unclear. Where is the problem, what i do wrong?
Please, help.
Here is the code in C. value - is value of array
Function for printing array:
void printArray (int arr[]){
int i;
printf("\n");
for(i = 0; i < value; i ++)
printf("%3d ", arr[i]);
}
Function for creating descending array:
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
Main function:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
However when I don't use my print function in function createDescendingArray() and print it in Main funktion with standart method like this:
{int i;
for(i = 0; i < value; i++)
{
a[i]=i;
printf("%3d", a[i]);
}
}
It shows descending array as ascending (look at the picture)
How it works?
You have been using a variable named value in your function which prints array, without initializing it, hence the garbage value.
you should initialize it in the function or pass its start value as an argument to the function.
#include <stdio.h>
#include <stdlib.h>
void printArray(int *arr, int length)
{
int i;
printf("\n");
for (i = 0; i < length; i++)
{
printf("%3d ", arr[i]);
}
}
int *createDescendingArray(const int length)
{
if (length == 0)
return NULL;
int *a = malloc(length * sizeof(int));
;
printf("\nDescending array is created.\n");
for (int i = length-1; i >= 0; i--)
{
a[i] = i;
}
printArray(a, length); // print of created array
return a;
}
int main()
{
int *a = createDescendingArray(20);
printArray(a, 20);
return 0;
}
these changes should most probably do the trick but again, there is no initialization of value in the function that creates array as well
EDIT: stop creation of array if length is 0
EDIT2: fixed code to consider 0 as an element
EDIT3: Fixed code with suggestion from #CraigEstey in comments, tested and working
EDIT4: fixed for loop and removed cast on mallock
The function
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
is wrong.
According to the output in your question, it seems that you have defined value as 4 (you are not showing us the code with the definition). In that case, your code for the mentioned function is equivalent to the following:
int createDescendingArray(int a[])
{
printf("\nDescending array is created.\n");
a[4] = 4;
a[3] = 3;
a[2] = 2;
a[1] = 1;
printArray(a); // print of created array
}
I did nothing else to the code than unroll the loop.
Since the array a has a size of 4 elements, valid indices are from 0 to 3. Therefore, by writing to a[4], you are writing to the array out of bounds, causing undefined behavior.
If you had written
for (i = value - 1; i >= 0; i--)
instead of
for (i = value; i > 0; i--)
then the unrolled loop would be:
a[3] = 3;
a[2] = 2;
a[1] = 1;
a[0] = 0;
This is better, because now we have fixed the undefined behavior; you are no longer writing to the array out of bounds. However, this is still not what you want. If you want descending output, your unrolled loop must look like this instead:
a[0] = 3;
a[1] = 2;
a[2] = 1;
a[3] = 0;
This can be accomplished by changing your function to the following:
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
Here is a small test program:
#include <stdio.h>
//NOTE: It is customary for constants to be written upper-case,
//not lower-case, so the line below should normally not be used.
#define value 4
void printArray (int arr[]) {
int i;
printf( "\n" );
for( i = 0; i < value; i++ )
printf("%3d ", arr[i]);
}
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
int main( void )
{
int array[value];
createDescendingArray( array );
}
The output is:
Descending array is created.
3 2 1 0
In this test program, I took over most of your other code, but I did not take over the function main, because it was also causing undefined behavior:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
In the line
arr1[value] = createDescendingArray (arr1);
you are assigning the return value of the function to a variable, although the function did not return a value. This causes undefined behavior. You may want to consider changing the return type to void in the function declaration, if it does not return a value.
Also, even if the function did return a value, arr1[value] would be writing to the array out of bounds, as valid indices are from 0 to value - 1.
So I have a function prototype find all products from two numbers whether it has 2 or 3 digits. I believe that function can only return one value. So how do I print out all possible values in main using printf statement?
int find_largest_products(int ndigits){
int min = 1;
int max;
int smallest_num;
int largest_num = 0;
int product = 0;
int max_min_product = 0;
//Finding the minima. 1 digit = 1; 2 digits = 10; 3 digits = 100
smallest_num = min * pow(10, ndigits-1);
//Finding the maxima. 1 digits = 9; 2 digits = 99; 3 digits = 999
for (int i = 0; i < ndigits; i++){
max = 9 * pow(10, i);
largest_num += max;
}
for (int x = largest_num; x >= smallest_num; x--){
for (int y = smallest_num; y <= largest_num; y++){
product = x * y;
max_min_product = product;
}
}
return max_min_product;
}
int main() {
int num = find_largest_palindrome(2);
printf("Results: %d\n", num);
return 0;
}
Callback function:
int find_largest_products(int ndigits, int (*callback)(int, void *), void *baton){
//...
//max_min_product = product;
int r= callback(product, baton);
if (r) return r;
//...
return 0;
}
int print_product(int product, void *ignored) {
printf(" %d", product);
return 0;
}
int main()
{
//...
printf("Results:");
find_largest_products(2, print_product, NULL); // Invocation is here
printf("\n");
//...
}
What about commas? What about newline every so many? We can adapt the callback.
int print_product(int product, void *baton) {
int *counter = baton;
if (counter % 8 == 7) {
printf(", %d\n", product);
else if (counter % 8 == 0)
printf("%d\n", product);
else
printf(", %d\n", product);
++*counter;
return 0;
}
But now the invocation should look like:
int counter = 0;
find_largest_products(2, print_product, &counter); // Invocation is here
Notice how this keeps state between invocations. Here it's an int, but it could easily be a struct or a pointer thereof to enable keeping arbitrary amounts of state.
So this is the pattern of a callback function that can do whatever it wants. The callback function takes the accumulating argument found by find_largest_products and the state argument baton from find_largest_products, and returns 0 to continue or nonzero to bail. Here the callback function only prints the value out and never fails. I also consider this lower-skill-level than dynamic memory. We only need to learn the somewhat annoying syntax for function pointers and the rest easy concepts. Note that we don't take the address of a function pointer with &; it's like an array in that regard.
To make the point this is the general form; here's the callback that could be passed to retrieve the list.
struct product_info {
int *products;
int nproducts;
int aproducts;
};
int gather_products(int product, void *baton)
{
struct product_info *info = baton;
// normal dynamic stretchy array zzzzz
if (info->nproducts == info->aproducts) {
if (info->aproducts == 0) {
info->products = malloc(sizeof(int)*4);
if (!info->products) return 1;
info->aproducts = 0;
} else {
void *more = realloc(sizeof(int) * (info->aproducts << 1));
if (!more) return 1;
info->aproducts <<= 1;
info->products = more;
}
}
// end stretchy array
info->products[info->nproducts++] = product;
return 0;
}
int main()
{
//...
printf("Results: ");
struct product_info info = { NULL, 0, 0 };
if (find_largest_products(2, gather_products, &info)) { // Invocation is here
fprintf(stderr, "Out of memory\n");
free(info->products);
}
for (int i = 0; i < info->nproducts; i++)
printf("%s%d", (i == 0) ? "" : ", ", info->products[i]);
free(info->products);
printf("\n");
//...
}
Returning the list requires dynamic memory. It's interesting to note that function pointers provides a separation of concerns that I've come to appreciate in these late days; we can separate the generating algorithm from the storing of the results.
Another sample: find biggest!
int biggest_product(int product, void *baton) {
int *biggest = baton;
if (*biggest < product) *biggest = product;
return 0;
}
int main()
{
int biggest = 0;
find_largest_products(2, biggest_product, &biggest); // Invocation is here
printf("Biggest product is: %d\n", biggest);
}
Notice how easy it is to swap what you do with the products as you generate them.
I need a way to see if all the numbers entered by the user are make up the numbers from 1 to 15. Wihout duplicates.
What I have so far is a program that will check if the numbers are over 15, or less then 1, but I don't have any idea of how to check every number entered into the array, and see if it's already been inputted into the array.
This is what I have so far.
#include <iostream>
using namespace std;
int main() {
bool somethingBadHappend=false; //booleans like this make it easy for the program to be read
int numbers[15]{};
cout << "enter 15 numbers:";
for (int i = 0; i < 15; i++)
{
cin>>numbers[i]; //entering them into the array
}
if (numbers[i] > 15|| numbers[i]<=0)
{
somethingBadHappend = true;
}
}
if (somethingBadHappend) //see the perfect use of code here?
{
cout<<"NOT GOOD"; // How elegant!
}
else
cout<<"GOOD";
return 0;
}
If i understood your question, you have to do another check into array to see the duplicate.
#include <iostream>
using namespace std;
int main() {
bool somethingBadHappend=false; //booleans like this make it easy for the program to be read
int numbers[15]{};
cout << "enter 15 numbers:";
for (int i = 0; i < 15; i++)
{
cin>>numbers[i]; //entering them into the array
}
//to find values >15 or <1
for (int i = 0; i < 15; i++)
{
if (numbers[i] > 15 || numbers[i]<=0)
{
somethingBadHappend = true;
}
}
//to find the duplicate into array
for (int i = 0; i < 15; i++){
for(int c=0; c<15; c++){
if(i!=c){ // check the different index
if(numbers[i]==numbers[c]){
somethingBadHappend = true; //found duplicate
break;
}
}
}
}
if (somethingBadHappend) //see the perfect use of code here?
{
cout<<"NOT GOOD"; // How elegant!
}
else
cout<<"GOOD";
return 0;
}
I'm getting an error saying no return for this function.
This function is supposed to return the number of even numbers in an array.
int even (int a[],int size){
int a;
for(a=0; a< size; a++)
{
if (abcdef[a] % 2 == 0)
{
printf("%d", abcdef[a]);
}
return 0;
}
If you want to return something, you have to
Calculate whatever you want to return
Add a return statement returning the result of your calculation.
In your code you are not doing either of these two things:
You have no variable that would keep count of even numbers, and
You are returning from the middle of your for loop.
To fix this, add an int count = 0 variable before the loop, increment it every time you print an even number, and move the return statement to the back of your code:
int count = 0;
for(...) { // Your "for" loop
if (...) { // if the number is even...
...
count++; // Increment the count
}
}
return count; // Return goes outside the loop
You should try something like this:
int even (int myArray[],int size){
int count = 0;
int a;
for(a=0; a<size; a++)
{
if (myArray[a] % 2 == 0)
{
printf("%d", myArray[a]);
count++;
}
}
return count;
}
I have implemented a solution for the N queens problem by using backtracking.
I am checking whether the position of every queen is safe or not by checking its top left, top right and top and then placing it in the row, otherwise I backtrack.
It is giving a correct solution for some values of N, such as 4 and 8, but incorrect for others, such as 6.
I don't know what I am missing. Any help would be highly appreciated.
Here's the code:
int S;
static int cnt=0;
int safepos(int board[][S+1],int i,int j)
{
if(i==1)
return 1;
int a,b;
a=i-1;
b=j-1;
//checking for top-left side
while(a>0 && b>0 )
{
if(board[a--][b--]==1)
return 0;
}
a=i-1;
b=j+1;
//checking for top-right side
while(a>0 && b<=S )
{
if(board[a--][b++]==1)
return 0;
}
//checking for the same column
for(a=1;a<i;a++)
if(board[a][j]==1)
return 0;
return 1;
}
void Nqueens(int board[][S+1],int N,int n) //n is the number of the rows
{
if(n==N+1) //for those which reaches the last position we will have a solution
{
cnt++;
return;
}
int i;
for(i=1;i<=N;i++) //for every column
{
if( safepos(board,n,i) )
{
board[n][i]=1;
Nqueens(board,N,n+1); //checking for next row
}
board[n][i]=0;
}
}
int main()
{
int N=6;
S=N;
int board[N+1][N+1];
Nqueens(board,N,1);
printf("%d",cnt);
return 0;
}
Your implementation of the backtracking idea is correct, the problem comes from the fact that the values of the array 'board' have to be initialized to zero manually, by default the array comes with undefined values. If you do that, you should get the correct answer, I tested the code. For more information related to array initialization, see http://www.fredosaurus.com/notes-cpp/arrayptr/array-initialization.html
I know this has an accepted answered but wanted to share my implementation that uses a vector initialized to -1 and not zero as to not interfere with zero offset for row = 0
#include <iostream>
#include <vector>
const int GRID_SIZE = 8;
bool isValid ( int queenNum, int col, std::vector<int>& cols )
{
// check for other queen number that collide with this one
for ( int queenRow = 0; queenRow < queenNum; ++queenRow )
{
int queenCol = cols[queenRow];
if ( col == queenCol )
return false; // same col
if ((queenNum - queenRow) == abs( queenCol-col))
return false; // same diagonal
}
return true;
}
void solve( int queenNum, std::vector<int>& cols, std::vector<std::vector<int> >& results )
{
if ( queenNum == GRID_SIZE)
{
// we have a solution
results.push_back (cols);
}
for ( int i = 0; i < GRID_SIZE; ++ i)
{
if ( isValid(queenNum,i,cols) )
{
cols[queenNum] = i;
solve(queenNum + 1,cols, results);
}
}
}
void drawLine() {
std::string line;
for (int i=0;i<GRID_SIZE*2+1;i++)
line.append("-");
std::cout << line << std::endl;
}
void printBoard(std::vector<int>& cols)
{
drawLine();
for(int i = 0; i < GRID_SIZE; i++){
std::cout << "|";
for (int j = 0; j < GRID_SIZE; j++){
if (cols[i] == j) {
std::cout << "Q|";
} else {
std::cout << " |";
}
}
std::cout << std::endl;
drawLine();
}
std::cout << "" << std::endl;;
}
void printBoards(std::vector<std::vector<int> >& boards) {
for (int i = 0; i < (int)boards.size(); i++)
{
printBoard(boards[i]);
}
}
int main ()
{
std::vector<int> cols ( GRID_SIZE, -1);
std::vector<std::vector<int> > results;
solve(0, cols, results );
printBoards(results);
std::cout << results.size() << std::endl;
return 0;
}