I am very new to C language. I have a little problem that I can't figure out. I made a lottery program which generates 6 random numbers to each columns, and repeats according to the row value entered. The only problem I am having is the program stops after 9 succesful rows even though the input is higher.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int KURE_SIZE = 50;
int ROWS = 0;
int i, j, a;
int lottery[ i ][ j ];
int kure[ KURE_SIZE ];
for( a = 1; a <= KURE_SIZE; ++a )
kure[a] = a;
printf("How many games do you want to play? (MAX.500) ");
scanf("%d", &ROWS);
printf("\n");
for( i = 0; i < ROWS; i++ ){
printf("Game %d :", i + 1);
srand ( (unsigned int) time(NULL));
for( j = 0; j < 6; j++ ){
int x = 1 + rand() % KURE_SIZE;
lottery[ i ][ j ] = kure[ x ];
printf("%5d", lottery[ i ][ j ]);
kure[x] = kure[ KURE_SIZE-- ];
}
printf("\n");
}
printf("\n\n");
system("pause");
return 0;
}
What might be the reason for this problem? I thought it may be a memory issue, but I don't know.
I'd be appreciated for some help. I love this site and the helpful community.
This definition of a variable length array
int lottery[ i ][ j ];
is incorrect because variables i and j are not initialized.
Also this loop is invalid
for( a = 1; a <= `KURE_SIZE`; ++a )
kure[a] = a;
there ia an attempt to access memory beyond the array. The valid range of indices for this array is [0, KURE_SIZE-1]
Thus this statement
int x = 1 + rand() % KURE_SIZE;
must be changed to
int x = rand() % KURE_SIZE;
because variable x used as an index for the array kure
Related
I am trying accomplish the following tasks using C and arrays:
This is what I could do for now. I also need to print the output. What should I do or edit, thanks.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
array0[i]= rand()%9 + 1;
}
int array1[10];
for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}
int index;
for(int i = 0 ; i < n ; i++)
{
index = array0[i];
array1[index-1]++;
}
}
It's fine, you just need to print the output after that:
for (int i = 1; i <= 9; ++i)
printf("\n%d appears %d times", i, array1[i - 1]);
Note:
It would be better to add srand(time(NULL)); once before calling rand() so that your code can generate different random numbers at different runtime.
rand() % 9 + 1 will generate numbers in the range [1, 9]. So int array1[10]; can be changed to int array1[9]; to save some memory. But if you need numbers in the range [1, 10] then don't change that but change rand() % 9 + 1 to rand() % 10 + 1 and let the printing loop run upto 10.
As mentioned in comments , if you want number in range 1 to 10 :
array0[i]= rand()%10 + 1;
I suggest int array1[10]={0}; instead of this loop:
for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}
and here is complete code with printing:
int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
array0[i]= rand()%10 + 1;//for your range
}
int array1[10]={0};
/*for(int i = 0 ; i < 10 ; i++)
{
array1[i]= 0;
}*/
int index;
for(int i = 0 ; i < n ; i++)
{
index = array0[i];
array1[index-1]++;
}
for (int i = 0; i < 10; i++)
{
printf("number %d appears:%d\n", i + 1, array1[i]);
}
}
also as #Ardent Coder said add srand(time(NULL)); bfeore rand() to generate different random numbers at different runtimes.
I have puzzles that looks like this:
=== ====
=== ===
=== ====
left edge has length from 0 to 10 000 and right also, middle part is from 1 to 10 000.
So the question is if i can build a rectangle? like first puzzle has length of left edge equal to 0 and the last puzzle has right edge of length 0 and in the middle they fit perfectly?
I am given the number of puzzle i have and their params like this:
6
1 9 2
0 3 1
0 4 1
8 9 0
2 9 0
1 5 0
and result can be any of that:
2
0 3 1
1 5 0
or
3
0 3 1
1 9 2
2 9 0
or
2
0 4 1
1 5 0
But if there is no result i have to printf("no result")
I have to do this in C, I thought about doing some tree and searching it with BFS where vertices would have edge lengths and edge would have middle length and when reached 0 i would go all way up and collect numbers but it's hard to code. So i decided to do recursion but im also stuck:
#include<stdio.h>
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int tab[a][3];//array for puzzles
int result[][3];//result array
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
int findx(int x, int a, int *tab[], int *result[], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[a][0] == x){//there i look for puzzles with x length at start
if(tab[a][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[a][m];
}
return print_result(result, k);//we will return result go to print_result function
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[a][m];
k += 1;
}
findx(tab[a][2], a, tab, result, k);
}
}
}
printf("no result");
}
int print_result(int *result[], int k){
printf("%d", &k);//how many puzzles i have
printf("\n");
for(int i = 0; i < k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", &result[i][j]);
}
printf("\n");//...in separate lines
}
}
I have an error that result array can't look like this int result[][3] because of of [] but I don't know how many puzzles I'm gonna use so?... and I have implicit declaration for both of my functions. Guys please help, I dont know much about C and its super hard to solve this problem.
I'm not sure I understand the overall logic of the problem, but you definitely are in need of some variable sized containers for result AND tab. Arrays are fixed size and must be defined at compile time. The following should at least compile without warnings:
#include<stdio.h>
#include<stdlib.h>
void print_result(int (*result)[3], int k){
printf("%d", k);//how many puzzles i have
printf("\n");
for(int i = 0; i <= k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", result[i][j]);
}
printf("\n");//...in separate lines
}
}
void findx(int x, int a, int (*tab)[3], int (*result)[3], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[i][0] == x){//there i look for puzzles with x length at start
if(tab[i][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[i][m];
}
print_result(result, k);//we will return result go to print_result function
return;
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[i][m];
k += 1;
///** Increase size of result **/
//int (*newptr)[3] = realloc(result, (k+1) * sizeof(int[3]));
//if (newptr)
// result = newptr;
}
findx(tab[i][2], a, tab, result, k);
}
}
}
printf("no result\n");
}
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int (*tab)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int (*result)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
Note that I changed the tab and result types to (*int)[3]. Due to order of operations, we need parentheses here. Because they are variable size, they require dynamic memory allocations. In the interest of brevity and readability, I did not check the returned values of malloc or realloc. In practice, you should be checking that the returned pointer is not NULL. Because we are using dynamic memory allocations, we should also use free if you plan on doing anything else with this program. Otherwise, it doesn't really matter because exiting the program will free the resources anyway. You actually don't want to free. because we are passing a pointer by value to findx and the realloc can change the address, it may come back with a different address. Also, take note that I needed to include <stdlib.h> for the dynamic memory allocations.
Additional Issues
Your functions print_results and findx are not declared when you call them in main. Your function either need to be above main or have "function prototypes" above main.
In the printfs you do not need the &. You do not want to send the address of the variable to printf. You want to send what will actually be printed.
Now what?
The program still does not provide you with the correct results. It simply outputs 0 as the result every time. This should at least give you a starting point. By changing this line in print_results:
for(int i = 0; i < k; i++){//printing puzzles...
to
for(int i = 0; i <= k; i++){//printing puzzles...
I was at least able to output 0 0 0. This seems more correct because if k is 0, we don't loop at all.
#include<stdio.h>
void findx(int x, int a, int tab[a][3], int result[200000][3], int puzzlesinresult) { //i am looking for puzzle with length x on start
for (int i = 0; i < a; i++) {
if (tab[i][0] == x) { //there i look for puzzles with x length at start
if (tab[i][2] == 0) { //if i find such puzzle i check if this is puzzle with edge length zero at the end
for (int m = 0; m < 3; m++) { //this for loop add to my result array last puzzle
result[puzzlesinresult][m] = tab[i][m];
}
return print_result(result, puzzlesinresult); //we will return result go to print_result function
} else { //if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
while (result[puzzlesinresult - 1][2] != tab[i][0] && puzzlesinresult > 0) {
puzzlesinresult -= 1;
}
int isusedpuzzle = 0;
for (int j = 0; j < puzzlesinresult; j++) {
if (result[j][0] == tab[i][0] && result[j][1] == tab[i][1] && result[j][2] == tab[i][2]) {
isusedpuzzle = 1;
} else {
//pass
}
}
if (isusedpuzzle == 0) {
for (int m = 0; m < 3; m++) {
result[puzzlesinresult][m] = tab[i][m];
}
puzzlesinresult += 1;
findx(tab[i][2], a, tab, result, puzzlesinresult);
}
}
}
}
}
void print_result(int result[200000][3], int puzzlesinresult) {
printf("%d\n", puzzlesinresult + 1); //how many puzzles i have
for (int i = 0; i < puzzlesinresult + 1; i++) { //printing puzzles...
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n"); //...in separate lines
}
exit(0);
}
int main() {
int a;
scanf("%d", & a); //here i get how many puzzles i have
int tab[a][3]; //array for puzzles
int result[100][3]; //result array
int puzzlesinresult = 0; //this will help me track how many puzzles has my result array
for (int i = 0; i < a; i++) { //upload puzzles to array
for (int j = 0; j < 3; j++) {
scanf("%d", & tab[i][j]);
}
}
for (int i = 0; i < a; i++) { //here i delete puzzles that doesnt contribute anything like 1 x 1,2 x 2,..
if (tab[i][0] == tab[i][2] && tab[i][0] != 0) {
for (int p = i; p < a; p++) {
for (int j = 0; j < 3; j++) {
tab[p][j] = tab[p + 1][j];
}
}
}
}
findx(0, a, tab, result, puzzlesinresult); //start of recursion, because start has to be length 0
printf("NONE");
}
This returns sometimes correct result. If you can find when this program fails I would rly appreciate sharing those cases with me :)
I want to define two variables called x and y.
Depending on that the program shall fill the array from 0 to x and from 0 to y.
I tried filling it with a for and it's kind of working, but I can't print it out properly.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
matrix[i][k] = k;
}
}
printf("\t\n%d\n", matrix[x][y]);
}
I expect an array looking like this in the console.
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
You see, in order to print an array you will have to loop over the whole data. You can't print an array in that simple a way in C.
What your code is printing is a garbage value, because at index 4,4 your array has no value. Its indexes go from 0,1..3 in both x and y direction.
Hope it helps.
#include <stdio.h>
#define x 4
#define y 4
void main(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i ;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}
In C there is no way to print an array in one go. You have to loop through each element of the array and print it.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
I have tried to guess at your misunderstandings and commented and edited your code to make an explanation of how it works and what you need to understand.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y]; // top allowed indexes are x-1 and y-1
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i; // first write getting ignored/overridden by next
matrix[i][k] = k;
// printing here gets you many values, note the removed \n
printf("\t%d", matrix[i][k]);
}
// printing line break here gets you lines instead of single values
printf("\n");
}
// not inside any loop, so only one %d value gets printed
// printf("\t\n%d\n", matrix[x][y]); // accessing beyond both dimension
// also your attempt to let printf figure out how to print the whole 2D array,
// at least that is what I think you try, does not work in C
}
This is fairly simple problem to print the integer array in reverse order. Although whenever i try printing, it ends up displaying garbage value. Below is my program.
#include <stdio.h>
#include <conio.h>
int main()
{
int temp = { '\0' };
int num[9];
int i;
int j = 8;
printf("Enter 8 numbers\n");
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
printf("\nThe numbers in reverse are\n");
for (i = 0; i <=8; i++)
{
printf("%d\n", num[i]);
}
_getch();
return 0;
}
Let just say i input numbers from 1 to 8, it does print the number in reverse but the first value it prints is a garbage value. I know i can use and If statement to counter the situation but is there a way to counter this problem without using if?
You've made two mistakes here:
With 8 numbers, the index of the highest item is 7, not 8. Set j to 7 on initialization to fix this.
When you iterate 8 numbers from index zero, use operator < or !=, not <= to avoid an off-by-one error. Your first loop does it right, but the last loop is broken.
In addition, you may want to reduce the size of the array to 8, because the ninth element is unused.
If you want to print the integers in your array in reverse, simply start at the last index, then work up to the top.
The third loop should look more like this:
int j = 7; // an array of size 8 starts at the 0th and ends at the 7th index.
while(j >= 0)
{
printf("%d", num[j]);
j--;
}
There are several logical inconsistences in your program,
You defined the array as having 9 elements
int num[9];
but enter only 8 elements
for (i = 0; i < 8; i++)
{
scanf_s("%d", &num[i], 1);
}
Thus the last element of the array with insex 8 is not initialized. Nevertheless in the loop that swaps elements of the array you access this uninitialized element
int j = 8;
//...
for (i = 0; i <= j; i++, j--)
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
There is also no need to use function scanf_s instead of scanf
Take into account that to output an array in the reverse order you need not to swap its elements.
The program that outputs an array in the reverse order without swapping its elements can look the following way
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int i;
printf( "Enter %d numbers\n", N );
i = 0;
while ( i < N && scanf( "%d", &num[i] ) == 1 ) i++;
printf( "\nThe numbers in reverse are\n" );
while ( i-- ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If to enter a sequence of numbers
1 2 3 4 5 6 7 8 9
then the output will look like
9 8 7 6 5 4 3 2 1
If you want to swap elements of the array then the program can look like
#include <stdio.h>
#include <conio.h>
#define N 9
int main( void )
{
int num[N];
int n;
int i;
printf( "Enter %d numbers\n", N );
n = 0;
while ( n < N && scanf( "%d", &num[n] ) == 1 ) n++;
for ( i = 0; i < n / 2; i++ )
{
int tmp = num[i];
num[i] = num[n - i - 1];
num[n - i - 1] = tmp;
}
printf( "\nThe numbers in reverse are\n" );
for ( i = 0; i < n; i++ ) printf( "%d ", num[i] );
printf( "\n" );
_getch();
return 0;
}
If the input is the same as above then output will be
9 8 7 6 5 4 3 2 1
You can also keep the for loop the same and change the indexing
#define ARRAY_SIZE 8
// print in reverse order
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%d\n", num[ARRAY_SIZE - i - 1]);
}
I used a #define to make it easier to change the program when you need a different array size: just change at one place rather than the 5 you currently need.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Help with C puzzle
The intention of the program was to print a minus sign 20 times, but it doesn't work.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
This is a classic puzzle!
The way I saw it was
"You can only change/insert/delete one character in the code to make the - print 20 times".
Some answers are (if I remember them correctly)
1)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; -i < n; i-- )
printf("-");
return 0;
}
Here you change the i < n to -i < n
2)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; n-- )
printf("-");
return 0;
}
Here you change the i-- to n--
3)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i + n; i-- )
printf("-");
return 0;
}
You change the i < n to i+n.
For a challenge, try changing/inserting/deleting one character to make it print the - 21 times. (Don't read the comments to this answer if you want to try it!)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i++ )
printf("-");
return 0;
}
You had -- instead of ++
Replace i-- with i++.
int main() {
int i;
int n = 20;
for( i = 0; i < n; i++)
printf("-");
return 0;
}
You had decrement instead of increment.
Have you tried changing the
i--
to
i++
You have the loop to print out a "-" for as long as "i" is less than 20.
After every loop you reduce the value of i by 1, it will continue to print
for a very long time. Changing the final part of the for loop to "i++" means it will perform one iteration each loop and stop once the twentieth iteration finished.
Change i-- to i++.
i-- decrements the value which at start is 0 and with subsequent reductions won't ever reach 20 (or +20).
the i-- needs to be i++
you could also do
int n = -20;
for( i = 0; i > n; i-- )
but that is bad coding practice
What exactly are you trying to do with this problem???
Here you are trying to decrement the value of a variable..a variable whose value will never reach the condition (i<20) you have provided... hence it will keep on printing '-' until what jamie wong specified, i.e. i= -2^31. It will become +ve. I just tried this program.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
According to the question you asked, i should be incremented, i.e. i++ instead of i--.
#jamie wong: thanx man..learnt a new thing about tht a wraparound....
You'll print no dashes. You can either go with Jaime Wong's solution or do this:
for (i = n; i >= 0; i--)