Generating and storing random numbers in array in c - c

I have to make an array containing 25 random numbers using a function to define the random numbers but keep getting it to either display only one number at a time (instead of all of them cell by cell) or simply displaying incorrectly i.e. 0. Here is what I have so far.
edit Code changed to correct stupid mistakes I missed rushing, however still unsure how to call funct as I am getting "too few arguments for funct 'get_value', apologies if this seems trivial but I am extremely new to coding thank you for your time.
int get_value (int t);
int main()
{
srand(time(NULL));
int temp[25], n;
for(n=0; n<25; n++)
{temp[n] = rand() %(40)+60;
printf("value of %d at cell %d \n", n, temp[n]);}
return 0;
}
//function get_value()
//needs to return rand # <-> 60 and 100 seed rand
//use rand %40+60 to ensure value is <-> 60 and 100
int get_value (int t)
{
return rand() %(40)+60;
}

You have some syntax errors
for loop should be like this
for(n=0; n<25; n++)
{
temp[n] = get_value(n); //in your prog u have written temp[t], t isnt defined
printf("value at cell %d is %d \n", n, temp[n]);
} // you also missed the braces

You are assigning value to temp[t], but you haven't declared t. In any case, it should be temp[n].
The scope of the variable t is only in your get_value function.
For more information about scopes

//I think here's what you want to do.
#include <stdio.h>
#include <time.h>
int main()
{
srand(time(NULL));
int temp, i, j, h;
int num_array[40];
int i_need_25[25];
//here's how im getting random numbers without repeating a number.
//first, fill the array with numbers between
for(i = 0; i < 41; i++)
{
num_array[i] = i + 60;
}
//then here's how we shuffle it
for(i = 0; i < 41; i++)
{
j = rand() % 41;
temp = num_array[j];
num_array[j] = num_array[i];
num_array[i] = temp;
}
//final process is to print the first 25 elements as you have said you need 25.
for(i = 0; i < 25; i++)
{
printf("%d ", num_array[i]);
}
printf("\n\n");
//or you can also store the first 25 elements on separate array variable.
for(i = 0; i < 25; i++)
{
i_need_25[i] = num_array[i];
printf("%d ", i_need_25[i]);
}
return 0;
}

Related

Is there a way to make a function for calculating 10 to the x exponent in C? "ten_to_the(x exponent)"

I need to multiply a number by 10 to the (x) power, depending on the exponent I may require.
I know there is a function, in the <math.h> library, but I was wondering if I could make my own function to achieve basically the same but only for 10, not any number. It´s for course homework, but since we haven´t been told about this library, I want to try to achieve it without said power() function.
Here's my code; it does compile, but I get some weird number instead of the intended 5000.
#include <cs50.h>
#include <stdio.h>
int ten_to_the(int n);
int main(void) {
int x = 50;
x *= ten_to_the(2);
printf("%.i\n", x);
}
int ten_to_the(int n) {
n = 1;
for (int i = 0; i < n; i++) {
n *= 10;
}
return n;
}
Because you multiple n by 10 on each iteration of the loop, i < n can never become true. In practice, n keeps getting bigger until it overflows and becomes negative.
Use another variable to keep track of the result separate from the number of iterations you need to calculate.
Instead of this:
int ten_to_the(int n)
{
n = 1;
for (int i = 0; i < n; i++)
{
n *= 10;
}
return n;
}
This:
int ten_to_the(int n)
{
int result = 1;
for (int i = 0; i < n; i++)
{
result *= 10;
}
return result;
}

Does this code have anything to do with pointers?

Could somebody help me with this piece of code.
I have no idea that what it does.
#include <stdio.h>
int main()
{
int arr[5],i;
int a = 1, n = 5;
for (i=0; i<5;a+= arr[i++]);
int d = a;
printf("%d",d);
}
technically this code has pointers. That is because arrays are pointers to the values that are stored in it(arr[0-5]). Every Element of the array points to a Adress anywhere in the memory.
int main()
{
int arr[10];
unsigned int x;
for(x = 0; x < 9; x++)
{
arr[x] = x;
printf("%d ", *(arr+x));
}
return 0;
}
in this code you can see that you can use an pointer notation to navigate trough an array.
now to your second question. the code that you gave us here is first initializing a array with 5 elements, a int named 'i', a int named 'a' with the value 1, and a int named 'n' that has the value 5.
then you go into a for loop that repeats 5 times. in the for loop you give a the value of the array[i]. but because the array is not filled with numbers it comes a number that is anywhere in the memory.
next you give the variable 'd' the value of 'a'. and at least you print 'd'.
I think that you want it so that you go into a loop and it prints the elements of the array.
int main()
{
int arr[5], i, a = 1, d;
for(i = 0; i < 5; i++)
arr[i] = i;
for(i = 0; i < 5; i++)
{
a = arr[i];
d = a;
printf("%d ", d);
}
return 1;
}
i think that is what you want.
Of note, we've not put anything of interest into arr, however notice the semicolon on the end of this line:
for (i=0; i<5;a+= arr[i++]);
That's a succinct (confusing?) way of saying
for (i=0; i<5; i++)
{
a += arr[i];
}
So a is summing up whatever is in arr.

C Print value in main() is different if I don't print some values in a different function [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 2 years ago.
I am trying to print the values that are in an array. Inside ascii(), I printed the values to check if the values are getting transferred to the main function without any problems. I also made random_values so that all integers inside the array are between 33 and 126.
Everything looked fine, but the problem is that when I comment that part code that I wrote to check inside ascii(), the values in the main function gets messed up. It gives me values like 384, 386, 387.
I think this is some kind of memory problem but I don't know much about memory and pointers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
void random_values (int a[], int l) {
for (int i = 0; i < l; i++) {
a[i] = (rand() % 94 + 33);
}
}
void set_length () {
//generates random integer between 8 and 15 which is used as the length of the array[]
length = (rand() % 8 + 8);
}
int ascii (int **pass)
{
int array[length];
//for assigning random values to the array []
random_values(array, length);
//the printed output from the main fuction is different if I comment this part - random_values() don't work
for (int i = 0; i < length; i++)
{
printf("%d ", array[i]);
}
*pass = array;
return 0;
}
int main () {
//to prevent rand() from producing the same value every time
srand(time(NULL));
set_length();
int *password = malloc(sizeof(int) * length);
ascii(&password);
for (int i = 0; i < length; i++) {
printf("%d ", password[i]);
}
//just to check
printf("\nlength is %d", length);
printf("\n");
}
You are sending the pointer of a local variable.
I would change ascii function to:
int ascii (int *pass)
{
//for assigning random values to the array []
random_values(pass, length);
//the printed output from the main fuction is different if I comment this part - random_values() don't work
for (int i = 0; i < length; i++)
{
printf("%d ", pass[i]);
}
return 0;
}

How to return a double pointer from a function and send it as input into another function?

I am new to programming and am trying to use two functions for matrix (2D array) operations, where the output of one function is the input for the next.
However, I do not find a way to correctly deliver the values from one function to another. When I print the outputs of the first function in main (), they are correct, but when I input them into the 2nd function and print them, the values make no sense. I have tried it a lot of ways, but it probably fails due to my lack of understanding double pointers.
I am thankful for any hint or advise!
#include <stdio.h>
#include <stdlib.h>
int** td (int r_in, int c_in, int r_p, int c_p, int input[][c_in],int params[][c_p]){
int i, j, k;
int**y_td;
// memory allocation
y_td = (int*)malloc(sizeof(int*)*r_in);
for (i=0; i < r_in; i++){
y_td[i] = (int*)malloc(sizeof(int)*c_p);
}
//
for (i=0; i < r_in; i++){
for (j=0; j < c_p; j++){
y_td[i][j]=0; // Initialization
for (k=0; k < c_in; k++){
y_td[i][j]+= input[i][k]*params[k][j];
}
}
}
return y_td;
}
int** cnv (int r_in, int c_in, int filter, int f_size, int input[][c_in], int params[][f_size][c_in]){
int x,i,j,k,l,m,n;
int min_len = ((r_in < f_size)? r_in:f_size);
int max_len = ((r_in > f_size)? r_in:f_size);
int r_out = max_len - min_len + 1;//rows_out
int kernel;
int** y_cnv;
// Print input to check if it was correctly transmitted to the function
printf("Input CV (should be equal to TD result):\n");
for (i=0;i<r_in;i++){
for (j=0;j<c_in;j++){
printf("%d ", input[i][j]);
}
printf("\n");
}
printf("\n\n");
//memory allocation
y_cnv = (int*)malloc(sizeof(int*)*r_out);
for (i=0; i < r_out; i++){
y_cnv[i] = (int*)malloc(sizeof(int)*filter);
}
//
for (i=0; i < filter; i++){
for (k=0; k < r_out; k++){
y_cnv [k][i]=0; //initialize
}
for (j = 0; j < c_in; j++){
for (n = min_len-1; n < max_len; n++){
x = n-min_len+1;
for (m= 0; m < r_in; m++){
kernel = (((n-m) < min_len && (n-m) >= 0)? params[i][n-m][j]:0);
y_cnv[x][i] += input[m][j]*kernel;
}
}
}
}
return y_cnv;
}
int main() {
// create test arrays
int A [4][2]= {{1,1},{2,2},{3,3},{4,4}};
int B [2][3]= {{1,2,3},{2,3,4}};
int C [2][2][3]= {{{1,1,1},{2,2,2}},{{3,3,3},{4,4,4}}};
int** matrix;
int i, j;
matrix = td(4,2,2,3,A,B);
// print the result of first function, which is input in 2nd function
printf("The TD result is:\n");
for (i=0;i<4;i++){
for (j=0;j<3;j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
printf("\n\n");
matrix = cnv(4,3,2,2,matrix,C);
return 0;
}
I expect the matrix printed in main () after the first function td () to be the same as when I read it in the second function cnv () and print it there, but it is not.
take a look at this question. You were hit by the same underlying problem.
Turning
int** cnv (int r_in, int c_in, int filter, int f_size, int input[][c_in], int params[][f_size][c_in])
into
int** cnv (int r_in, int c_in, int filter, int f_size, int** input, int params[][f_size][c_in])
fixes the problem you asked for.
The reason is that you allocate an array of pointers called y_td in your first function. Each of this pointers is a number naming a memory segment where you stored some real numbers. By using int input[][c_in] you tell the computer to interpret these pointers as integer numbers and when you print them you get the addresses in memory instead of the expected values, because then input[x][y] is translated to *((int *)input+x*c_in+y).
Please allow me one more comment: You should follow the comments below the question and care for all compiler warnings: If there is a warning you should treat it as an compiler error unless you exactly know what you are doing, especially in C. Your code contains some possible problem sources like the one above.

2 Dimensional Array sorting in c

Here is a segment of my (incomplete) code
int rows(int board[][9]){
int badUnits = 0, i = 0, n = 9, j, z = 0;
int (*temp)[9];
//Sort each row of 2d array
for (z; z < n; z++){
for (i; i < n; i++){
for (j = i; j < n; j++){
if (board[z][i] > board[z][j]){
temp = board[z][i];
board[z][i] = board[z][j];
board[z][j] = temp;
}
}
}
}
printf ("%d\n", temp[1][0]);
printf ("%d\n", temp[1][1]);
return badUnits;
}
The function takes a 9*9 array.
I get a segmentation fault when the print statements are executed.
I believe my sort code is correct because it is similar to what I use for 1d arrays and I think everything else is correctly assigned.
So the culprit would be my temp variable. I have gone through and tried to assign values to it, tried to change the type, and have taken into account that the 2d array decays into a pointer but is not actually a pointer.
The conclusion I am left with is that this is a dynamic allocation issue. Can someone please lend a hand and assist me in fixing this? I have exhausted my knowledge base and am stuck.
To clarify: I decided to print the temp variable because I thought it would lend some information. The main problem was that the swap was not working, and I was still left with an unsorted array when I originally attempted to print out the board[][]. I know that board is what I am SUPPOSED to be printing.
Thank you for any help!
You assign an int value to temp
temp = board[z][i]; // Temp now is a what ever value was at
// That location in the array e.g. 42
You then treat temp as if it was the address in memory of an integer array
temp[1][1] // treat temp as a pointer and find the integer
// 10 integers further along then temp.
Also sometime temp will not have been initialised (never assigned to) in this case your going to get unexpected behaviour depending on what the last value stored where temp is now (Lets call it a random number).
Did you mean to output the values in board?
printf ("%d\n", board[1][0]);
printf ("%d\n", board[1][1]);
One thing to notice is that the variable temp will only get assigned to if a swap occurs, if the sorting algorithm was correct that is still a situation that could occur with a input corresponding to a sorted board.
But more importantly, the variable temp is used as an int during the swap. Later that integer value is interpreted as a pointer in the expressions temp[1][0] and temp[1][1], which in all likelihoods is not a valid address. You may want to change temp to be declared as:
int temp;
And figure out exactly what you would like to print. If it is whatever one of the two swapped values was (for the last swapped pair in the loop), then you would print it as:
printf("%d", temp);
Else, you would have to add logic according to what you really want to do.
Note that a single pass of this algorithm would not perform a complete sort, but I guess that's one of the reason why you said the provided code was not complete.
Something like this?
#include <stdio.h>
#include <stdlib.h>
void printArray(int** arr, int w, int h) {
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void sortArray(int** arr, int w, int h) {
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
for (int i = 0; i < w; ++i) {
if (arr[row][i] > arr[row][col]) {
int tmp = arr[row][col];
arr[row][col] = arr[row][i];
arr[row][i] = tmp;
}
}
}
}
}
int main() {
int w = 9, h = 9;
int** arr = (int**)malloc(sizeof(int*) * w);
for (int i = 0; i < w; ++i) {
arr[i] = (int*)malloc(sizeof(int) * h);
for (int j = 0; j < h; ++j) {
arr[i][j] = rand() % 10;
}
}
printf("Unsorted:\n");
printArray(arr, w, h);
sortArray(arr, w, h);
printf("Sorted:\n");
printArray(arr, w, h);
for (int j = 0; j < h; ++j) {
free(arr[j]);
}
free(arr);
return 0;
}

Resources