I created an 2D array, each line receiving 6 random different values between 1-60.
#define QTE 50
#define NUM 6
void mostrar();
int main(void)
{
int sorteios[QTE][NUM], repeticao[61] = {};
srand(time(NULL));
for (int i = 1; i < QTE; i++)
{
for (int j = 0; j < 6; j++)
{
int gerado = rand() % 60 + 1;
for (int k = j; k > 0; k--)
{
if (j == 0)
{
break;
}
while (gerado == sorteios[i][k])
{
gerado = rand() % 60 + 1;
}
}
sorteios[i][j] = gerado;
int aleatorio = sorteios[i][j];
repeticao[aleatorio] += 1;
}
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", i, sorteios[i][0], sorteios[i][1], sorteios[i][2], sorteios[i][3], sorteios[i][4], sorteios[i][5]);
}
mostrar(sorteios[QTE][NUM]);
}
This code itself is working if there's a for loop inside the main function but using the function to execute causes segmentation fault(core dumped).
void mostrar(int *array[QTE][NUM])
{
printf("Mostrando..\n");
for (int p = 0; p < QTE; p++)
{
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", p, *array[p][0], *array[p][1], *array[p][2], *array[p][3], *array[p][4], *array[p][5]);
}
}
A piece of the console result..
...
Sequência 0043: 35 59 08 31 16 40
Sequência 0044: 26 47 27 52 32 08
Sequência 0045: 35 34 26 35 31 14
Sequência 0046: 07 44 13 22 35 46
Sequência 0047: 50 17 16 53 49 29
Sequência 0048: 27 39 37 50 10 44
Sequência 0049: 29 35 30 55 18 53
Mostrando..
Segmentation fault (core dumped)
Aside from the way you pass the array to the function, already discussed in the comments, there are some other issues in your code, here is a corrected version with comments where fixes are needed:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define QTE 50
#define NUM 6
// if you want the access the array, jut use that as an argument, no pointer needed
void mostrar(int array[][NUM])
{
printf("Mostrando..\n");
for (int p = 0; p < QTE; p++)
{
// correcting the dereference to match the argument...
printf("Sequência %04d:\t %02d\t%02d\t%02d\t%02d\t%02d\t%02d\n", p, array[p][0], array[p][1], array[p][2], array[p][3], array[p][4], array[p][5]);
}
}
int main(void)
{
int sorteios[QTE][NUM], repeticao[61] = {0};
srand(time(NULL));
// beginning at index 1 would leave the first index empty, also messing up the
// indexing in the function, so start at index 0
for (int i = 0; i < QTE; i++)
{
for (int j = 0; j < 6; j++)
{
int gerado = rand() % 60 + 1;
for (int k = j; k > 0; k--)
{
if (j == 0)
{
break;
}
while (gerado == sorteios[i][k])
{
gerado = rand() % 60 + 1;
}
}
sorteios[i][j] = gerado;
int aleatorio = sorteios[i][j];
repeticao[aleatorio] += 1;
}
}
// pass only the array, if you include indexes you are just passing an element
// of the array, and sorteios[QTE][NUM] would be outside of the bounds of the array
// and wouldn't match the original function argument either
mostrar(sorteios);
}
Live demo
Related
The code works fine but why are my answers wrong in the int result?
in output:
3
10
2 3 5 7: 17 //correct
30
2 3 5 7 11 13 17 19 23 29: 146 //incorrect
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: 474 //incorrect
Here is the code:
#include <stdio.h>
int main() {
int y, n, i, fact, j, result = 0;
scanf("%d", &y);
for (int x = 1; x <= y; x++) {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact = 0;
for (j = 1; j <= n; j++) {
if (i % j == 0)
fact++;
}
if (fact == 2) {
result += i;
printf("%d ", i);
}
}
printf(": %d\n", result); //Not Getting correct answer please HELP!
}
return 0;
}
You forgot to initialize result before each calculation.
for(int x=1;x<=y;x++){
scanf("%d", &n);
result = 0; // add this for initialization
for (i = 1; i <= n; i++) {
/* ... */
}
/* ... */
}
The variable result is initialized only once
int y, n, i, fact, j, result = 0;
So it will accumulate values calculated in the loop
for(int x=1;x<=y;x++){
//...
}
Move the declaration of the variable result in the body of the loop
for(int x=1;x<=y;x++){
int result = 0;
//...
}
To avoid such an error you should declare variables in the minimum scope where they are used.
Also this loop
for (j = 1; j <= n; j++)
{
if (i % j == 0)
fact++;
}
does not make a great sense. Change the condition in the loop the following way
for (j = 1; j <= i; j++)
{
if (i % j == 0)
fact++;
}
substituting the variable n for the variable i.
Also you should use an unsigned integer type instead of the signed integer type int because prime numbers are defined for natural numbers.
The program can look for example the following way
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
scanf( "%u", &n );
while ( n-- )
{
unsigned int max_value = 0;
scanf( "%u", &max_value );
unsigned long long int sum = 0;
for ( unsigned int i = 1; i <= max_value; i++ )
{
size_t count = 0;
for ( unsigned int j = 1; j <= i; j++ )
{
if ( i % j == 0 ) ++count;
}
if ( count == 2 )
{
printf( "%u ", i );
sum += i;
}
}
printf( ": %llu\n", sum );
}
return 0;
}
If to enter
3
10
20
100
then the output will be
2 3 5 7 : 17
2 3 5 7 11 13 17 19 : 77
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 : 1060
I was supposed to fill an nxn matrix in spiral order from 1 to n² using functions and then print its result but I don't know why my code doesn't function can anyone help please?
The principle was to create different functions, each filling the matrix at different time intervals then calling those functions in the main program which prints them in a spiral matrix.
#include <stdio.h>
#include <stdlib.h>
/* initializing the array and variables for the whole program*/
int A[5][5],top,bottom,left,right;
int FillRowForward(int A[5][5],int top,int left,int right,int z)
/*function that fills the top of the matrix from left to right*/
{ left = 0;
for(top=left,right=0;right<=4;right++)
{
A[top][right]=z;
z++;
}
return A[top][right];
}
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int z)
/*fills the lower part from right to left*/
{ bottom =4;
for(left=bottom,right=4;right>=0;right--)
{
A[left][right-1]=A[left][right]+z;
}
return A[left][right-1];
}
int FillColumnDownward(int A[5][5],int top,int bottom,int left,int z)
/*fills the last column from top to bottom*/
{
left=0;
for(top=left,bottom=4;top<=4;top++)
{
A[top+1][bottom]= A[top][bottom]+z;
}
return A[top][bottom];
}
int FillColumnUpward(int A[5][5],int top,int bottom,int left, int z)
/*fills the first column from bottop to top*/
{
left =0;
for(bottom=left,top=0;bottom>=1;bottom--)
{
A[bottom-1][top]=A[bottom][top]+z
}
return A[bottom][top];
}
int main()
{
int i,j,k=1;
while(k<5*5){
int FillRowForward(int A[5][5],int top,int left,int right,int k);
top++;
int FillColumnDownward(int A[5][5],int top,int bottom,int right,int k);
right--;
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int k);
bottom--;
int FillColumnUpward(int A[5][5],int top,int bottom,int left,int k);
}
//prints the matrix
for(i=0;i<=4;i++)
for(j=0;j<=4;j++)
printf("%d",A[i][j]);
return 0;
}
You have a number of problems like:
int FillRowForward(int A[5][5],int top,int left,int right,int k);
not being a function call and that you you never change k, i.e. you have an endless loop.
This solution uses a variable direction to track the current direction of filling the matrix.
#include <stdio.h>
#define ARRSIZE 10
int main()
{
int A[ARRSIZE][ARRSIZE] = { 0 };
int i=0, j=0;
int direction = 0;
for(int k = 1; k <= (ARRSIZE*ARRSIZE); ++k)
{
A[i][j] = k;
switch (direction)
{
case 0 : // Go rigth
if (((j + 1) == ARRSIZE) || (A[i][j+1] != 0))
{
// Switch direction
direction = 1;
++i;
}
else
{
++j;
}
break;
case 1 : // Go down
if (((i + 1) == ARRSIZE) || (A[i+1][j] != 0))
{
// Switch direction
direction = 2;
--j;
}
else
{
++i;
}
break;
case 2 : // Go left
if (((j - 1) == -1) || (A[i][j-1] != 0))
{
// Switch direction
direction = 3;
--i;
}
else
{
--j;
}
break;
case 3 : // Go up
if (((i - 1) == -1) || (A[i-1][j] != 0))
{
// Switch direction
direction = 0;
++j;
}
else
{
--i;
}
break;
}
}
for(i=0; i<ARRSIZE; i++)
{
for(j=0; j<ARRSIZE; j++)
printf("%4d",A[i][j]);
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
You have a couple of problems here:
I suppose there is no need for global variables, so you can define everything in the main() function
As already pointed out "In main() you are only providing declarations of the functions, not calling them. "
You have an infinite loop in main() function because you never increased var k
Try to avoid using numbers in your function, use variables or symbolic constants instead. No difference on such small projects, but in bigger projects, you can easily confuse them, also if you want to change, you must change every value, etc.
Your functions are not doing what they are supposed to do. You can write something like this (I found my old program and modified it a bit):
#include <stdio.h>
void print_mat(int mat[][5], int m, int n)
{
int i,j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n\n");
}
printf("\n");
}
void spiral(int mat[][5], int m, int n)
{
int i, k = 0, l = 0;
int counter = 1;
while(k < m && l < n)
{
for(i = l; i < n; i++)
{
mat[k][i] = counter++;
}
k++;
for(i = k; i < m; i++)
{
mat[i][n-1] = counter++;
}
n--;
if(k < m)
{
for(i = n-1; i >= l; i--)
{
mat[m-1][i] = counter++;
}
m--;
}
if(l < n)
{
for(i = m-1; i >= k; i--)
{
mat[i][l] = counter++;
}
l++;
}
}
}
int main()
{
int mat[5][5];
int n = 5;
spiral(mat,n,n);
print_mat(mat,n,n);
return 0;
}
Since you need to create different functions, you can try to divide this spiral() function into several smaller functions, it can be a good exercise.
I want to print the first 49 numbers with 5 rows and 10 columns.
I've tried using certain width implications and trying to make it aligned but I couldn't figure out how.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int count = 50;
int r = 5;
int c = 10;
for (i = 0; i <= r; i++)
{
for(int j = 1; j <=count; j++)
{
printf("%9d", i);
i++;
}
}
return (0);
}
I was able to print from 0-49 but it wasn't aligned correctly, can someone help? Thank you.
No need to use two loops, one will do fine.
Use "%2d" to reserve two digits for each number.
Don't increase for loop variable inside loop. It isn't of much use here.
Code
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i, j;
int count = 50;
int c = 10;
for (i = 0; i < count; i++)
{
printf("%2d ", i);
if (i%c == 9) printf("\n");
}
return (0);
}
You only need one loop and can use the remainder operator to detect when a new line is needed.
#include <stdio.h>
int main()
{
int count = 50;
int columns = 10;
for (int i = 0; i < count; i++)
{
printf("%9d", i);
if ((i % columns) == 9)
{
printf("\n");
}
}
return 0;
}
Output is:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
You will need to know if the column has printed 10 values,you will need a offset to remind you that, where the last element occured which was the last 10th value, so we assign the offset variable to that element value based on 10 columns per row, so we take modulus if its the completely divisible by 10, then we will move to next row
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
int row = 5;
int column = 9;
int offset = 0;
for (int outer = 0; outer <= row; outer++)
{
for(int inner = offset; inner <= column; inner++)
{
if(count>=50){
break;
}
printf("%9d", count); // tab spaces between colums
count++;
}
printf("\n"); // new lines
}
return (0);
}
Adding space or any character before "%9d" fixes the problem.
printf(" %9d", i);
i have been trying to make an array of complitely diffrent random integers, 25 of them between 1-75. have been getting stuck in an infinite loop. help greatly appreciated!
ive tried to look up solutions but i either didnt understand them or just didnt find anything that suits my level.
btw i have made sure that i used srand(time(NULL));
for (i = 0; i < 25; i++)
{
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
}
k = 0;
}
whole code:
/*********************************
* Class: MAGSHIMIM C2 *
* Week: *
* Name: *
* Credits: *
**********************************/
#include <stdio.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int i = 0;
int j = 0;
int k = 0;
int arr[25] = { 0 };
for (i = 0; i < 25; i++)
{
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
}
k = 0;
}
for (i = 0; i < 25; i++)
{
printf("%d", arr[i]);
}
getchar();
return 0;
}
expecetd: a nice diffrent array but i got an infinite loop.
One way to do it is to make a pool or bag of numbers in the required range and pick from them. It is not much harder than repeated checking to see if the number has already been picked, and more efficient. Your modified program is now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ARRLEN 25 // how many to pick
#define NUMBERS 75 // range of available numbers
#if NUMBERS < ARRLEN // precaution
#error Impossible job!
#endif
int cmp(const void *a, const void *b)
// optional, for qsort
{
return *(int *)a - *(int *)b;
}
int main(void)
{
int arr[ARRLEN]; // final array
int bag[NUMBERS]; // bag of available numbers
int avail = NUMBERS; // size of bag available
srand((unsigned)time(NULL));
// prepare the bag of available numbers
for(int i = 0; i < NUMBERS; i++) {
bag[i] = i + 1;
}
// fill the array with values from the bag
for(int i = 0; i < ARRLEN; i++) {
int index = rand() % avail; // random index into array
arr[i] = bag[index]; // take that number
avail--;
bag[index] = bag[avail]; // replace with the one from the top
}
// just to check, sort the array, can be deleted
qsort(arr, ARRLEN, sizeof arr[0], cmp);
// output the result
for (int i = 0; i < ARRLEN; i++) {
printf("%d ", arr[i]);
}
printf("\n");
getchar();
return 0;
}
I sorted the array to make it easy to see if there are duplicates. That qsort line and the cmp function can be deleted.
Program output from three runs
6 7 8 9 12 16 17 19 21 27 31 35 43 46 47 50 51 53 59 64 65 66 70 71 72
2 6 7 14 17 23 24 25 30 31 32 34 36 37 45 58 59 61 65 68 69 71 73 74 75
5 10 13 18 20 21 25 30 34 36 39 40 41 43 49 50 54 58 60 63 64 66 67 72 75
... but i got an infinite loop.
just replace
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++) {
...
}
}
k = 0;
by
do
{
k = 0;
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++) {
...
}
} while (k != 1);
Note it is also useless to check looking at all the array including the entries not set by a random value, so can be :
do
{
k = 0;
arr[i] = rand() % 75 + 1;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
} while (k != 0);
because now j cannot values i the test is (k != 0) rather than (k != 1)
or better because when an identical value is found there is no reason to continue
do
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
break;
}
} while (j != i);
To see well the values also add a space between them and add a final newline:
for (i = 0; i < 25; i++)
{
printf("%d ", arr[i]);
}
putchar('\n');
AFter these changes, compilation and executions :
pi#raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall r.c
pi#raspberrypi:/tmp $ ./a.out
74 60 16 65 54 19 55 45 41 24 39 59 66 36 27 22 68 49 29 14 28 5 71 56 72
pi#raspberrypi:/tmp $ ./a.out
16 34 62 29 74 41 3 43 69 17 61 22 28 59 7 65 5 46 60 20 66 14 49 54 45
pi#raspberrypi:/tmp $
edit
The implementation is simple but it can take time to find a not yet used value in that way, and the more the range of allowed values is closer to the number of values to return the higher the needed time is. So that solution is good when there are few values to return compared to the range of allowed values.
It is the reverse concerning the interesting proposal of Weather Vane, the number of call to rand is only equals to number of values to return, but the more the range of allowed values is large the more the array bag is large up to may be overflow the memory size.
Probably for 25 values from 1 to 75 the solution of Weather Vane is better ... even my proposal seems to need just 0.001 sec on my raspberry pi so almost nothing
int *fillint(int *arr, size_t size)
{
int added = 0;
int pos = 0
while(pos != size)
{
int rv;
do
{
added = 1;
rv = rand();
for(size_t index = 0; index < pos; index++)
{
if(arr[index] == rv)
{
added = 0;
break;
}
}
}while(!added)
arr[pos++] = rv;
}
return arr;
}
Another slight variation on Weather Vane's bag approach, is rather than preparing a bag of all available numbers, simply declare an array with the max number of elements equal to the range of numbers accepted initialized to all zero (e.g. int arr[75] = {0}; in this case). There is no need to populate the array, you will simply increment the element by 1 each time that number is used in filling your array.
To ensure you use only unique number you check whether the corresponding element of the array is zero, if it is, use that number and increment the element. If it is non-zero, you know that number has been used - generate another and try again.
For example with the number of integers for the array being 25 and the maximum value of any one integer being 75, you could do;:
#define NINT 25
#define MAXI 75
...
int arr[NINT],
seen[MAXI] = {0};
...
for (int i = 0; i < NINT; i++) { /* for each needed element */
int tmp = rand() % MAXI + 1; /* generate a random in range */
while (seen[tmp-1]) /* has been seen/used yet? */
tmp = rand() % MAXI + 1; /* if so, generate another */
seen[tmp-1]++; /* incement element */
arr[i] = tmp; /* assign unique value to arr */
}
(note: the seen indexes are mapped as tmp-1 to map to valid indexes 0-74 while the numbers generated for tmp will be 1-75 using rand() % MAXI + 1. You can accommodate any range needed by this type of mapping. Using a range of numbers from 1000001 - 1000075 would still only require a 75-element seen array.)
To output the numbers used in order, you simply need to output the index corresponding to each of the non-zero elements of the seen array (+1 to map back into the 1-75 values range), e.g.
for (int i = 0; i < MAXI; i++)
if (seen[i])
printf (" %d", i + 1);
putchar ('\n');
Putting it altogether in a short example you could do:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NINT 25
#define MAXI 75
int main (void) {
int arr[NINT],
seen[MAXI] = {0};
srand (time(NULL));
for (int i = 0; i < NINT; i++) { /* for each needed element */
int tmp = rand() % MAXI + 1; /* generate a random in range */
while (seen[tmp-1]) /* has been seen/used yet? */
tmp = rand() % MAXI + 1; /* if so, generate another */
seen[tmp-1]++; /* incement element */
arr[i] = tmp; /* assign unique value to arr */
}
puts ("array:");
for (int i = 0; i < NINT; i++) {
if (i && i % 5 == 0)
putchar ('\n');
printf (" %2d", arr[i]);
}
puts ("\n\nused:");
for (int i = 0; i < MAXI; i++)
if (seen[i])
printf (" %d", i + 1);
putchar ('\n');
}
(note: obviously the size of the seen array will be limited to the available stack size, so if your range of needed numbers exceeds the memory available for seen declared with automatic storage type, you will need to make seen an array with allocated storage type).
Example Use/Output
$ ./bin/randarr25-75
array:
1 18 70 26 75
29 31 58 22 9
5 13 3 25 35
40 48 44 57 56
60 50 71 67 43
used:
1 3 5 9 13 18 22 25 26 29 31 35 40 43 44 48 50 56 57 58 60 67 70 71 75
Whether you use a bag, or an array to track the numbers seen, the results are the same. No one better than the other. Add them both to your C-toolbox.
In the inner for loop, the one for j, iterate until j < i, to check if the value generated at step i has been already generated at a earlier step.
Also, initialize the value of k to be zero every time you check for previous occurrences, this makes the code more easy to read.
If one occurrence was found, just break, it make the algorithm to run faster, even if it only make a difference for big values.
Something like this:
for (i = 0; i < 25; i++)
{
k = 1;
while (k != 0)
{
arr[i] = rand() % 75 + 1;
k = 0;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
k++;
break;
}
}
}
}
Hi I have made a simple program to print primes between 1 and 100 but I cannot figure a way to assign these values to an array of size 25 as we all know there are 25 primes between 1 and 100:
#include <stdio.h>
int main() {
int i, k;
for (i = 3; i < 100; i = i + 2) {
for (k = 2; k < i; k++) {
if (i % k == 0)
break;
}
if (i == k)
printf("%d\n", i);
}
}
Just create an array at the top, write to it, and then read out of it after you've found all your primes. Note that this could definitely be done more efficiently, but given the number of calculations you're doing, that's beside the point.
Code
#include<stdio.h>
int main() {
int primes[25];
int i, k;
int j = 0;
// find primes
for(i = 2; i < 100; i++) {
for (k = 2; k < i; k++) {
if (i % k == 0) {
break;
}
}
if (i == k) {
primes[j] = i;
j++;
}
}
// print primes
for (j = 0; j < 25; j++) {
printf("%d\n", primes[j]);
}
return 0;
}
Also note that 2 is prime, so you'll want to make sure that that's included in your output.
Output
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Make an array before you begin, then create a variable that increments while each prime is found. It might look something like this:
#include <stdio.h>
int main() {
int primes[25];
primes[0] = 2;
int count = 1;
for (int i = 3; i < 100; i += 2) {
int k;
for (k = 2; k < i; k++) {
if (i % k == 0) break;
}
if(i == k) {
primes[count] = i;
count++;
}
}
}
Warning: this is a humorous answer, not to be taken seriously.
Just like we all know there are 25 primes between 1 and 100, we might as well know the magic value to avoid using an array at all:
#include <stdio.h>
int main() {
long long magic = 150964650272183;
printf("2");
for (int i = 3; magic; magic >>= 1, i += 2)
magic & 1 && printf(" %d", i);
printf("\n");
return 0;
}
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97