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
Related
I have to make a Floyd Triangle that prints in this order:
7 8 9 10
4 5 6
2 3
1
But currently my code print like this:
1
2 3
4 5 6
7 8 9 10
CODE:
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ", a);
a++;
}
printf("\n");
}
return 0;
}
Can someone help me?
Here you are.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
int width = 0;
for ( unsigned int tmp = n * ( n + 1 ) / 2; tmp != 0; tmp /= 10 )
{
++width;
}
putchar( '\n' );
for ( unsigned int i = 0; i < n; i++ )
{
unsigned int value = ( n - i ) * ( n - i + 1 ) / 2 - ( n - i - 1 );
for ( unsigned int j = 0; j < n - i; j++ )
{
printf( "%*u ", -width, value++ );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 10
46 47 48 49 50 51 52 53 54 55
37 38 39 40 41 42 43 44 45
29 30 31 32 33 34 35 36
22 23 24 25 26 27 28
16 17 18 19 20 21
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 4
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 0
I solved it by hacking (i.e. trying different things and adjusting the code based on the output):
I started by moving the generation code to a separate function. I then cut and pasted the function, giving it a different name. I then started modifying the for loops.
I went through four versions until I hit the correct one:
#include <stdio.h>
#include <stdlib.h>
void
fwd(int n)
{
int i, c;
int a = 1;
for (i = 1; i <= n; i++) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev1(int n)
{
int i, c;
int a = 1;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev2(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", a);
a--;
}
printf("\n");
}
}
void
rev3(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", (c - i) + a);
a--;
}
printf("\n");
}
}
void
rev4(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", (c - i) + a);
}
a -= i;
printf("\n");
}
}
int
main(int argc,char **argv)
{
int n;
--argc;
++argv;
if (argc > 0)
n = atoi(*argv);
else
scanf("%d", &n);
printf("fwd:\n");
fwd(n);
printf("\nrev1:\n");
rev1(n);
printf("\nrev2:\n");
rev2(n);
printf("\nrev3:\n");
rev3(n);
printf("\nrev4:\n");
rev4(n);
return 0;
}
Here's the program output:
fwd:
1
2 3
4 5 6
7 8 9 10
rev1:
1 2 3 4
5 6 7
8 9
10
rev2:
10 9 8 7
6 5 4
3 2
1
rev3:
10 8 6 4
6 4 2
3 1
1
rev4:
7 8 9 10
4 5 6
2 3
1
The other answers are great, but no one posted a recursive function so I thought I'd add one.
#include <stdio.h>
void recursive(int n, int i);
void straight(int n);
// one way of doing it with a recursive function
void recursive(int n, int i) {
if(n <= 0)
return;
if(i <= n) {
printf( "%-3d", (((n * (n + 1) / 2) - n) + i) );
recursive(n, i + 1);
} else {
printf("\n");
recursive(n - 1, 1);
}
}
// straightforward nested loop way
void straight(int n) {
int i, j, row_sum;
for(i = n; i > 0; --i) {
// the sum: i + (i-1) + (i-2) + ... + 2 + 1 = (i * (i+1)) / 2
row_sum = (i * (i + 1)) / 2;
for(j = i; j > 0; --j) {
printf("%-3d", row_sum - j + 1);
}
printf("\n");
}
}
// entry point
int main(int argc, char **argv) {
int n = 0;
scanf("%d", &n);
printf("Recursive Output for n=%d\n", n);
recursive(n, 1);
printf("\nStraight Output for n=%d\n", n);
straight(n);
return 0;
}
Output:
Recursive Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Straight Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
C function.
Heres my working code. It shows this output when given a random array size;
Enter the size of the array: 20
What's in the array:
3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16
3 occurs 2 times.
6 occurs 4 times.
15 occurs 2 times.
6 occurs 3 times.
12 occurs 2 times.
6 occurs 2 times.
However I was wondering how you would go about implementing once a certain number has been searched for how to not repeat the loop?
#include <stdio.h>
#include <stdlib.h>
/* shows duplicate numbers in randomly generated array*/
void display_repeats(int *a, int n){
int i, j;
int count = 0;
for(i = 0; i < n; i++){
for(j = i; j < n; j++){
if(a[i] == a[j]){
count++;
}
}
if(count > 1){
printf("%3d occurs %3d times.", a[i], count);
printf("\n");
}
count = 0;
}
}
int main(void){
int array_size = 0;
int *my_array;
int i = 0;
printf("Enter the size of the array: ");
scanf("%d", &array_size);
/*initialises the array to the appropriate size */
my_array = malloc(array_size * sizeof my_array[0]);
if(NULL == my_array){
fprintf(stderr, "memory allocation failed!\n");
return EXIT_FAILURE;
}
for(i = 0; i < array_size; i++){
my_array[i] = rand() % array_size;
}
printf("What's in the array:\n");
for(i = 0; i < array_size; i++){
printf("%d ", my_array[I]);
}
printf("\n");
display_repeats(my_array, array_size);
/* release the memory associated with the array */
free(my_array);
return EXIT_SUCCESS;
}
You can sort the array and count runs of each number. Time complexity is O(n log(n)) but without a clean hashing solution, it should be reasonable and is the easiest approach.
As an aside, it's a good idea to separate printing (a side effect) from logic. Return results as a data structure and let the caller decide what to do with it. Keeping logic and printing tightly coupled harms reusability and prevents you from programmatically operating on the data after applying a function.
Here's a quick proof of concept. Plenty of room for improvement based on the above tips--and consider making a copy of the int array before sorting to keep the function idempotent if you do move this out of main.
#include <stdio.h>
#include <stdlib.h>
int cmp_ints(const void *a, const void *b) {
return *((const int *)a) - *((const int *)b);
}
int main(void) {
int nums[] = {1, 1, 5, 6, 1, 6, 2, 4, 6, 8};
int len = sizeof nums / sizeof nums[0];
qsort(nums, len, sizeof *nums, cmp_ints);
for (int i = 0; i < len;) {
int count = 1;
int num = nums[i++];
for (; i < len && nums[i] == num; i++, count++);
printf("%d => %d\n", num, count);
}
return 0;
}
Output:
1 => 3
2 => 1
4 => 1
5 => 1
6 => 3
8 => 1
The following proposed code:
cleanly compiles
properly initializes the rand() function via a call to srand()
properly checks for success/failure of the call to scanf() and properly handles any failure by informing the user via stderr and exiting the code
makes use of the Variable Length Array feature of C, so no need for dynamic memory
limits the scope of local variables when ever possible
does not repeat the examination for a value more than once
makes use of appropriate horizontal and vertical spacing for readability
outputs the values in the array in ascending order
Performs the desired functionality
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* shows duplicate numbers in randomly generated array*/
/* note: order of parameters in function
* so can clearly indicate the array sizing
*/
void display_repeats(int arraySize, int Array[ arraySize ] )
{
int minValue = 0;
int maxValue = 0;
for( int i = 0; i < arraySize; i++ )
{
if( Array[i] > maxValue )
{
maxValue = Array[i];
}
}
for( int j = minValue; j <= maxValue; j++ )
{
int count = 0;
for( int i = 0; i < arraySize; i++)
{
if( Array[i] == j )
{
count++;
}
}
if(count > 1 )
{
printf( "%d occurs %d times.\n", j, count );
}
}
}
int main( void )
{
int array_size = 0;
printf( "Enter the size of the array: " );
if( scanf( "%d", &array_size ) != 1 )
{
fprintf( stderr, "scanf for array size failed\n" );
exit( EXIT_FAILURE );
}
/* use VLA feature of C to declare array */
int my_array[ array_size ];
srand( (unsigned)time(NULL) );
for( int i = 0; i < array_size; i++ )
{
my_array[i] = rand() % array_size;
}
printf( "What's in the array:\n" );
for( int i = 0; i < array_size; i++ )
{
printf( "%d ", my_array[i] );
}
printf( "\n" );
display_repeats( array_size, my_array );
}
A typical run of the proposed code results in:
Enter the size of the array: 100
What's in the array:
19 69 68 90 25 8 44 64 33 3 28 4 4 43 22 6 19 93 70 63 34 96 42 31 74 9 72 49 34 12 12 53 33 80 95 10 40 39 74 26 94 55 82 98 98 56 56 69 49 78 33 35 75 75 19 1 36 91 50 70 55 63 76 40 95 71 51 88 63 25 14 9 80 48 8 30 4 16 0 5 95 33 93 22 60 12 23 96 3 74 19 58 89 95 50 84 18 1 24 33
1 occurs 2 times.
3 occurs 2 times.
4 occurs 3 times.
8 occurs 2 times.
9 occurs 2 times.
12 occurs 3 times.
19 occurs 4 times.
22 occurs 2 times.
25 occurs 2 times.
33 occurs 5 times.
34 occurs 2 times.
40 occurs 2 times.
49 occurs 2 times.
50 occurs 2 times.
55 occurs 2 times.
56 occurs 2 times.
63 occurs 3 times.
69 occurs 2 times.
70 occurs 2 times.
74 occurs 3 times.
75 occurs 2 times.
80 occurs 2 times.
93 occurs 2 times.
95 occurs 4 times.
96 occurs 2 times.
98 occurs 2 times.
An implementation of the first suggestion by ggorlen, creating an array that stores whether the number at each index has already been seen.
void display_repeats(int *a, int n){
int i, j;
int count = 0;
int seen[n]; //stores 1 if the number at this index has already been seen, 0 if not
for (int i = 0; i<n; i++) seen[i] = 0; //initializes values to 0
for(i = 0; i < n; i++){
if (seen[i]) continue; //skips this iteration of the for loop if this number has already been seen
for(j = i; j < n; j++){
if(a[i] == a[j]){
count++;
seen[j] = 1; //notes that we already seen the number at this index
}
}
if(count > 1){
printf("%3d occurs %3d times.", a[i], count);
printf("\n");
}
count = 0;
}
}
I'm trying to arrange numbers in a nxn(n is odd number) matrix with bow tie shapes. (like fig.)
Trying to 5x5 matrix set coordinates but no result.
my code:
bowtie {
int a[5][5] = {{
0,
},
{
0,
},
{
0,
},
{
0,
},
{
0,
}};
int i, j;
int num = 1;
for (i = 0; i < 5; i++) {
if (i <= 2) // y>=0 - coordinate(2d)
{
for (j = i; j <= 2; j++) // x<=0, y>=0 Quadrant 2
{
a[i][j] = num;
num++;
}
for (j = 4 - i; j > i; j++) // Quadrant 1
{
a[i][j] = num;
num++;
}
} else // y<0
for (j = 4 - i; j <= 4 - i; j++) // Quadrant 3
{
a[i][j] = num;
num++;
}
for (j = i; j >= i; j++) // Quadrant 2
{
a[i][j] = num;
num++;
}
}
for (i = 0; i < 5; j++) {
for (j = 0; j < 5; j++) {
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
The loop
for (j = 4 - i; j > i; j++) // Quadrant 1
is wrong because j starts at 4 (i valuing 0) being the last valid index then never stop to grow producing an undefined behavior when you go out of the array
The loop
for (j = 4 - i; j <= 4 - i; j++) // Quadrant 3
is strange because the last possible value is the first one, so this is not a loop but just its body executed with j = 4 - i
The loop
for (j = i; j >= i; j++) // Quadrant 2
is like the first and makes j incompatible with the array dimensions
A proposal where the size in given in argument and can be odd or even :
#include <stdio.h>
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Usage %s <size>\n", *argv);
else {
int n;
if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1))
fprintf(stderr, "invalid size %s\n", argv[1]);
else {
int a[n][n];
int v = 0; /* the value 1.. to put in the cells */
int empty; /* the empty height */
int i,j;
/* first half and may be center */
empty = -1;
for (j = 0; j <= (n-1)/2; ++j) {
empty += 1;
for (i = 0; i != empty; ++i)
a[i][j] = a[n - i - 1][j] = 0;
for (int k = n - empty*2; k; --k)
a[i++][j] = ++v;
}
if ((n & 1) == 0)
empty += 1;
/* second half */
for (; j < n; ++j) {
empty -= 1;
for (i = 0; i != empty; ++i)
a[i][j] = a[n - i - 1][j] = 0;
for (int k = n - empty*2; k; --k)
a[i++][j] = ++v;
}
/* show result */
for (i = 0; i != n; ++i) {
for (j = 0; j != n; ++j) {
if (a[i][j] == 0)
fputs(" ", stdout); /* witdh = 4 compatible with a size up to 43 */
else
printf("% 4d", a[i][j]); /* width = 4 compatible with a size up to 43 */
}
putchar('\n');
}
}
}
return 0;
}
Compilation and executions :
pi#raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall b.c
pi#raspberrypi:/tmp $ ./a.out 1
1
pi#raspberrypi:/tmp $ ./a.out 2
1 3
2 4
pi#raspberrypi:/tmp $ ./a.out 3
1 5
2 4 6
3 7
pi#raspberrypi:/tmp $ ./a.out 4
1 9
2 5 7 10
3 6 8 11
4 12
pi#raspberrypi:/tmp $ ./a.out 5
1 13
2 6 10 14
3 7 9 11 15
4 8 12 16
5 17
pi#raspberrypi:/tmp $ ./a.out 6
1 19
2 7 15 20
3 8 11 13 16 21
4 9 12 14 17 22
5 10 18 23
6 24
pi#raspberrypi:/tmp $ ./a.out 7
1 25
2 8 20 26
3 9 13 17 21 27
4 10 14 16 18 22 28
5 11 15 19 23 29
6 12 24 30
7 31
If you do not accept even size
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Usage %s <size>\n", *argv);
else {
int n;
if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1) || ((n & 1) == 0))
fprintf(stderr, "invalid size %s\n", argv[1]);
else {
int a[n][n];
int v = 1; /* the value 1.. to put in the cells */
int empty; /* the empty height */
/* first half more center */
empty = -1;
for (int j = 0; j <= n/2; ++j) {
int i;
empty += 1;
for (i = 0; i != empty; ++i)
a[i][j] = a[n - i - 1][j] = 0;
for (int k = n - empty*2; k; --k)
a[i++][j] = v++;
}
/* second half */
for (int j = n/2 + 1; j < n; ++j) {
int i;
empty -= 1;
for (i = 0; i != empty; ++i)
a[i][j] = a[n - i - 1][j] = 0;
for (int k = n - empty*2; k; --k)
a[i++][j] = v++;
}
/* show result */
for (int i = 0; i != n; ++i) {
for (int j = 0; j != n; ++j) {
if (a[i][j] == 0)
fputs(" ", stdout);
else
printf("% 4d", a[i][j]);
}
putchar('\n');
}
}
}
return 0;
}
Compilation and executions :
pi#raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall o.c
pi#raspberrypi:/tmp $ ./a.out
Usage ./a.out <size>
pi#raspberrypi:/tmp $ ./a.out 1
1
pi#raspberrypi:/tmp $ ./a.out 2
invalid size 2
pi#raspberrypi:/tmp $ ./a.out 3
1 5
2 4 6
3 7
pi#raspberrypi:/tmp $ ./a.out 5
1 13
2 6 10 14
3 7 9 11 15
4 8 12 16
5 17
pi#raspberrypi:/tmp $ ./a.out 17
1 145
2 18 130 146
3 19 33 117 131 147
4 20 34 46 106 118 132 148
5 21 35 47 57 97 107 119 133 149
6 22 36 48 58 66 90 98 108 120 134 150
7 23 37 49 59 67 73 85 91 99 109 121 135 151
8 24 38 50 60 68 74 78 82 86 92 100 110 122 136 152
9 25 39 51 61 69 75 79 81 83 87 93 101 111 123 137 153
10 26 40 52 62 70 76 80 84 88 94 102 112 124 138 154
11 27 41 53 63 71 77 89 95 103 113 125 139 155
12 28 42 54 64 72 96 104 114 126 140 156
13 29 43 55 65 105 115 127 141 157
14 30 44 56 116 128 142 158
15 31 45 129 143 159
16 32 144 160
17 161
pi#raspberrypi:/tmp $
From you remark
'int a[n][n];' has problem.
probably you compiled in C++ rather than C, but it is easy to change that :
replace int a[n][n]; by int * a = malloc(n*n*sizeof(int));
replace each form a[x][y] by a[(x)*n+y]
add a free(a); at the end
For instance if I do that on the proposal only accepting odd size :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Usage %s <size>\n", *argv);
else {
int n;
if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1) || ((n & 1) == 0))
fprintf(stderr, "invalid size %s\n", argv[1]);
else {
int * a = malloc(n*n*sizeof(int));
int v = 1; /* the value 1.. to put in the cells */
int empty; /* the empty height */
/* first half more center */
empty = -1;
for (int j = 0; j <= n/2; ++j) {
int i;
empty += 1;
for (i = 0; i != empty; ++i)
a[i*n+j] = a[(n - i - 1)*n+j] = 0;
for (int k = n - empty*2; k; --k)
a[i++*n+j] = v++;
}
/* second half */
for (int j = n/2 + 1; j < n; ++j) {
int i;
empty -= 1;
for (i = 0; i != empty; ++i)
a[i*n+j] = a[(n - i - 1)*n+j] = 0;
for (int k = n - empty*2; k; --k)
a[i++*n+j] = v++;
}
/* show result */
for (int i = 0; i != n; ++i) {
for (int j = 0; j != n; ++j) {
if (a[i*n+j] == 0)
fputs(" ", stdout);
else
printf("% 4d", a[i*n+j]);
}
putchar('\n');
}
free(a);
}
}
return 0;
}
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
I have this problem where I need to compute the number of ways in which elements that are consecutive in a matrix can be summed in order to obtain a certain number. Let me give you an example :
Searched number = 42
Matrix :
00 03 07 09 10
09 13 20 05 20
12 11 33 00 12
17 39 22 03 18
12 15 31 01 17
There are 4 possibilities to obtain 42 : 42 = 10+20+12 =
9 + 13 + 20 = 9 + 11 + 22 = 20 + 0 + 22.
I don't succeed in checking the sum diagonally .I succeeded in transversing the matrix diagonally but my algorithm is not doing the correct sum:
int getNumbers(int **arr,int length,int number){
int count=0;
//check sum each row / horizontally
for(int i=0;i<length;i++){
for(int j=0;j<length;j++){
int sum=0;
int k=j;
do{
if(arr[k][j]!=number){
sum=sum+arr[i][k];
}
k++;
}while(sum<number && k<length);
if(sum==number){
count++;
}
}
}
//check sum each column/ vertically
for(int j=0;j<length;j++){
for(int i=0;i<length;i++){
int sum=0;
int k=i;
do{
if(arr[k][j]!=number){
sum=sum+arr[k][j];
}
k++;
}while(sum<number && k<length);
if(sum==number){
count++;
}
}
}
//check sum each diagonally
for (int j = 0; j < 2 * length - 1; j++) {
for (int i = 0; i < length; i++) {
int row = i;
int col = j - i;
int sum=0;
if (col >= 0 && col <= length - 1) {
do{
if(arr[row][col]!=number){
sum=sum+arr[row][col];
}
}while(sum<number && row<length && col<length);
if(sum==number){
count++;
}
}
}
}
for (int j = 0; j < 2 * length - 1; j++) {
int z = (j < length) ? 0 : j - length + 1;
int len = j + 1 - 2 * z;
for (int i = 0; i < len; i++) {
int sum=0;
int row = length - 1 - i - z;
int col = j - i - z;
do{
if(arr[row][col]!=number){
sum=sum+arr[row][col];
}
}while(sum<number && row<length && col<length);
if(sum==number){
count++;
}
}
}
return count;
}
For a working solution it is enough to replicate the stretegy that you used for the horizontal and vertical cases, that is:
Consider each cell as a possible starting point, except the ones at the borders
Traverse in the desired direction
A solution for left-right and top-bottom diagonals would be:
for(int j=0; j < length-1; j++)
{
for(int i=0; i < length-1; i++)
{
if(arr[i][j] == number)
continue;
int sum=0;
int localColumn = i;
int localRow = j;
do{
sum += arr[localRow][localColumn];
localColumn++;
localRow++;
}
while( sum < number && localRow < length && localColumn < length);
if(sum==number){
count++;
}
}
}
Note that I moved the check for the single 42 cell out of the do while loop: your code just skips it during the sum, making a sequence like 20 42 22 valid.