I am trying to make a program that takes 3 inputs from the user: row/columns count and number range start and number range end.
In my case and for example lets say 4 1 16 so it means 4 rows and columns print numbers from 1-16.
I have a problem accomplishing this.
#include <stdio.h>
#include <stdlib.h>
int num1,num2,count,i,y;
int main()
{
count = 4;
num1 = 1;
num2 = 16;
for(i=1; i<=count; i++){
for(y=num1; y<=num2; y++){
printf("%d ",y);
}
printf("\n");
}
return 0;
}
The output is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Whereas I want my output to be:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
for(y=1; y<=count; y++){
printf("%d ",num1++);
}
That way you will ensure that all the numbers will be printed. you can use num1 variable that you have declared and initialized with 1.
Don't use unnecessary global variables. And keep the declarations close to where you use them. That way you won't have to look in the top of the page to check the type or if you initialized or not.
for(i=1; i<=count; i++){
printf("%d ",i);
if( i % 4 == 0)
printf("\n");
}
Print 4*(i-1)+y instead of y:
printf("%d ",4*(i-1)+y);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an array with randomly generated numbers in it, and I need to find and store the numbers that are present at least x times. (I can easily find x, that is not important. It will be a set amount). The array will have around 100-200 elements.
I know I will have to use a loop, but I'm not sure how to structure the body of it. I'm relatively new to C programming, so this may be fairly trivial. Any help is appreciated.
I implemented two solutions, one in C and one in C++.
First solution in C:
It is simple:
Input array of numbers. Either it is inputed from console (when input = 1) or generated automatically by random generator (set constant input = 0 in first lines of main()). Input/generation is done by first loop. If generated automatically/randomly then set constants n (number of elements) and x (minimal allowed count) at first lines of main() function.
Sort them in ascending order by built-in function qsort. I provided compare() function for qsort to compare in ascending order.
Iterate through sorted array. On the way compute number c of consecutive equal numbers. If c >= x then it means we have at least x of consecutive equal numbers, it means this number occured at least x times, hence we output such number as matching our criteria.
Try it online!
#include <stdlib.h>
#include <stdio.h>
static int compare(void const * sa, void const * sb) {
int a = *(int*)sa, b = *(int*)sb;
return a < b ? -1 : a == b ? 0 : 1;
}
int main() {
// "n" - total number of integers, "x" - minimum count to find
// "input" - if 1 then read from console input array, else if 0 generate random
int const n = 50, x = 3, input = 1;
// Example of input: n = 50, x = 3, a = 3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16 11 8 7 9 2 10 2 3 7 15 9 2 2 18 9 7 13 16 11 2 9 13 1 19 4 17 18 4 15 10
// and output for this example: 2: 6 times, 3: 3 times, 6: 4 times, 7: 4 times, 9: 5 times, 10: 3 times, 13: 3 times, 15: 4 times,
if (input) {
printf("Input n and x: ");
scanf("%d %d", &n, &x);
printf("Input array: ");
} else
srand(0); // You may init this with some randomness
int * a = (int*)malloc(sizeof(int) * n); // Allocate memory for empty array
for (int i = 0; i < n; ++i) {
if (input)
scanf("%d", &a[i]);
else {
a[i] = rand() % 20; // Init numbers with random, you may input your numbers
printf("%d ", a[i]); // Print generated numbers
}
}
if (!input)
printf("\n");
qsort(a, n, sizeof(int), compare);
int c = 1;
for (int i = 1; i <= n; ++i) {
if (i == n || a[i] != a[i - 1]) {
if (c >= x)
printf("%d: %d times, ", a[i - 1], c);
c = 1;
} else
++c;
}
free(a);
return 0;
}
Input:
50 3
3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16 11 8 7 9 2 10 2 3 7 15 9 2 2 18 9 7 13 16 11 2 9 13 1 19 4 17 18 4 15 10
Second solution in C++:
Use std::map to count number of occurances of each number, by iterating (in a loop) over input array and incrementing by 1 count of current nummber inside map, then iterate (in a second loop) through this map and output those numbers that occur at least x times.
Also I used std::map specifically to have nice sorted output of numbers, if you don't need sorted order and need more speed then use std::unordered_map instead of std::map exactly same way (also do #include <unordered_map> instead of <map>).
Full code is below:
Try it online!
#include <iostream>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
int main() {
size_t const n = 50; // How many numbers
size_t const x = 3; // At least this many times
srand(0); // Use this if only deterministic randoms are needed
vector<int> a(n); // Numbers
for (size_t i = 0; i < a.size(); ++i) {
a[i] = rand() % 20; // Some random numbers
cout << a[i] << " "; // Output our input numbers
}
cout << endl;
map<int, size_t> cnt;
// Count number of occurances
for (auto x: a)
++cnt[x];
// Output numbers that occur at least "x" times
for (auto const & p: cnt)
if (p.second >= x)
cout << p.first << ": " << p.second << " times, ";
return 0;
}
Output:
3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16 11 8 7 9 2 10 2 3 7 15 9 2 2 18 9 7 13 16 11 2 9 13 1 19 4 17 18 4 15 10
2: 6 times, 3: 3 times, 6: 4 times, 7: 4 times, 9: 5 times, 10: 3 times, 13: 3 times, 15: 4 times,
I am trying to 4x4 input in an 5x5 array and get the sum of each lines on the fifth lines.
I'm sure if you read my code below, you'll know what I am trying to talk about.
For example if I type in:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The expected Result should be:
1 2 3 4 10
5 6 7 8 26
9 10 11 12 42
13 14 15 16 58
28 32 36 40 136
Instead, I am getting a result like:
1 2 3 4 10
5 6 7 8 32792
9 10 11 12 42
13 14 15 16 58
28 32 36 40 -501277720
I thought about why I get these random values, but couldn't find a solution. Why am I getting these values and what can I do to solve it?
#include <stdio.h>
int main ()
{
int gradeArr[5][5];
int i,j;
printf("Input grades:\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",&gradeArr[i][j]);
gradeArr[i][4] += gradeArr[i][j];
}
}
printf("%d\n", gradeArr[1][4]);
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
gradeArr[4][i] += gradeArr[j][i];
}
gradeArr[4][4] += gradeArr[4][i];
}
printf("Result: \n");
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("%d ",gradeArr[i][j]);
}
printf("\n");
}
return 0;
}
You need to initialize the array.
Try
int gradeArr[5][5] = {0};
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This code is designed by someone to change array [a1 a2...am b1 b2..bn ] to the array [b1 b2 ..bn a1 a2..am], but it involves the greatest common divisor which I can't get the point.
void Exchange(int a[],int m,int n,int s){
int p=m,temp=m+n;int k=s%p;
while(k!=0){temp=p;p=k;k=temp%p;}
for(k=0 ; k<p ;k++){ //below is where i cant't understand
temp=a[k];i=k;j=(i+m)%(m+n);
while(j!=k)
{a[i]=a[j];i=j;j=(j+m)%(m+n);}
a[i]=temp;
}
};
EDIT: "Properly" indented:
void Exchange(int a[], int m, int n, int s) {
int p = m, temp = m + n, k = s % p;
while (k != 0) {
temp = p;
p = k;
k = temp % p;
}
for (k = 0 ; k < p; k ++) { // below is where i cant't understand
temp = a[k];
i = k;
j = (i + m) % (m + n);
while (j != k) {
a[i] = a[j];
i = j;
j = (j + m) % (m + n);
}
a[i] = temp;
}
};
The code is using a single value of overhead to implement array rotation. If the lengths are mutually prime, a single pass suffices. If not, you have to repeat the shift cycle by the GCD of the lengths
I said earlier that there are other questions on SO that cover this. A look found SO 3333-3814 which deals with a single rotation. I did some messing with code to support that a while ago, demonstrating the need for GCD, but I didn't previously post it.
Here's the code — it uses C99 VLAs — variable length arrays.
#include <stdio.h>
static int gcd(int x, int y)
{
int r;
if (x <= 0 || y <= 0)
return(0);
while ((r = x % y) != 0)
{
x = y;
y = r;
}
return(y);
}
static void dump_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
printf("%4d", source[i][j]);
putchar('\n');
}
}
static void init_matrix(int m, int n, int source[m][n])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
source[i][j] = (i + 1) * (j + 2);
}
}
static void rotate_1col(int n, int vector[n], int z)
{
z %= n;
if (z != 0)
{
int c = gcd(n, z);
int s = n / c;
for (int r = 0; r < c; r++)
{
int x = r;
int t = vector[x];
for (int i = 0; i < s; i++)
{
int j = (x + z) % n;
int v = vector[j];
vector[j] = t;
x = j;
t = v;
}
}
}
}
static void rotate_cols(int m, int n, int source[m][n], int z)
{
for (int i = 0; i < m; i++)
rotate_1col(n, source[i], z);
}
int main(void)
{
int m = 3;
for (int n = 2; n < 9; n++)
{
int source[m][n];
for (int z = 0; z <= n; z++)
{
init_matrix(m, n, source);
printf("Initial:\n");
dump_matrix(m, n, source);
rotate_cols(m, n, source, z);
printf("Post-rotate %d:\n", z);
dump_matrix(m, n, source);
putchar('\n');
}
}
return 0;
}
The code demonstrates different sizes of rotation on different sizes of array. Example sections of the output:
…
Initial:
2 3 4
4 6 8
6 9 12
Post-rotate 1:
4 2 3
8 4 6
12 6 9
…
Initial:
2 3 4 5
4 6 8 10
6 9 12 15
Post-rotate 3:
3 4 5 2
6 8 10 4
9 12 15 6
…
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 1:
7 2 3 4 5 6
14 4 6 8 10 12
21 6 9 12 15 18
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 2:
6 7 2 3 4 5
12 14 4 6 8 10
18 21 6 9 12 15
Initial:
2 3 4 5 6 7
4 6 8 10 12 14
6 9 12 15 18 21
Post-rotate 3:
5 6 7 2 3 4
10 12 14 4 6 8
15 18 21 6 9 12
…
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 4:
6 7 8 9 2 3 4 5
12 14 16 18 4 6 8 10
18 21 24 27 6 9 12 15
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 5:
5 6 7 8 9 2 3 4
10 12 14 16 18 4 6 8
15 18 21 24 27 6 9 12
Initial:
2 3 4 5 6 7 8 9
4 6 8 10 12 14 16 18
6 9 12 15 18 21 24 27
Post-rotate 6:
4 5 6 7 8 9 2 3
8 10 12 14 16 18 4 6
12 15 18 21 24 27 6 9
…
First of all, to get the result you said you expected, I have set m and n to be half the array size. I also assumed that s would be initialised to zero, in which case, the first while loop does not iterate. Also, there are several declarations missing in your code so my explanation makes some assumptions.
The variable p holds the number of array elements to swap;
// This is to keep the value to be overwritten by the swap
temp=a[k];
// This is the array index of the bottom half element to write the top half element to
i=k;
// this is to get the current index of the top half;
j=(i+m)%(m+n);
// This assignes the bottom index value with the top half value
while(j!=k)
{
// Write top half element to corresponding bottom half element
a[i]=a[j];
// We can now overwrite top half element; this assignes the index at wich to copy the bottom half element
i=j;
// This is to get out of the loop
j=(j+m)%(m+n);
}
// The bottom half element held at the beginning is now written to the top half at the corresponding index
a[i]=temp;
Hope this is the answer you were looking for. I arrived at this result by using a debugger and by stepping in the code line by line. I don't know if you know how to use a debugger but if not, then I highly recommend your lean how to use one; it it time well spent and it returns an awesome dividend :-)
I don't get why sum == 105. For me it should be 100 but I can't get it to work that way. Can someone please explain?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum=0;
int t=0;
do{
t++;
sum= sum + t;
}
while(sum<100);
printf("sum:%d\n", sum); //prints 105
printf("t = %d\n", t);
return 0;
}
t starts at 0 and is incremented in each iteration of the loop.
sum starts at 0 and is increased by the value t in each iteration of the loop, until it is no longer smaller than 100. If we trace their values throughout the execution:
Iteration t sum
0 0 0
1 1 1
2 2 3
3 3 6
4 4 10
5 5 15
6 6 21
7 7 28
8 8 36
9 9 45
10 10 55
11 11 66
12 12 78
13 13 91
14 14 105
As you can see, 105 is the first value that sum gets that is not smaller than 100.
In your code: sum= 1+2+3+4+5+6+7+8+9+10+11+12+13+14 = 105.
Why am I getting a segmentation fault with this code?
/* solver.h header file */
10 struct options{
11 unsigned int one:1, two:1, three:1, four:1, five:1, six:1, seven:1, eight:1, nine:1;
12 };
13
14
15 /* structure to describe a cell */
16 struct cell{
17 short value;
18 struct options open_options;
19 };
solver.c:
5 #include <stdio.h>
6 #include "solver.h"
7
8
9
10
11
12 int main(){
13 struct cell board [9][9];
14 int i=0,j=0;
15
16
17 for(i = 1; i<10; i++)
18 for(j = 1; j<10; j++)
19 (board[i][j]).value = j;
20
21 for(i = 1; i<10; i++){
22 for(j = 1; j<10; j++)
23 printf(" %d",(board[i][j]).value);
24 printf("\n");
25 }
26 return 0;
27 }
output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
Segmentation fault: 11
Arrays are indexed from 0, so the loops should be for(i = 0; i<9; i++) and not for(i = 1; i<10; i++)
In your case, you probably override part of the stack, but in general, going out of boundaries results in undefined behavior.
some_type array[9]; defines array to be an array of 9 elements, with subscripts going from 0 to 8 inclusive. You can't use array[9].
board[9][9] will contain elements with indices in the range 0...8, not 1...9. When you assigned to board[9][whatever], you actually overwrote memory that didn't belong to you, and this happened to cause the program to explode when return 0 handed control back to the C runtime and it started walking its structures to perform shut down.