No output in c program? - c

I made a 2 dimension array where I have to type 16 numbers and the program should return me the biggest value and its location (This is just an exercise, I know I can just use an array with 16 values instead of 4x4)
#include <stdlib.h>
#define CONSTC 4
#define CONSTL 4
int main ()
{
int i=1;
int e;
int k;
int c;
int a;
int A [CONSTR][CONSTC];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
printf ("%2d - Type number\n", i);
scanf ("%d", &A [k][c]);
}
}
e = Matriz [0][0];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
if (e>A[k][c])
{
e = A [k][c];
return k;
return c;
}
}
}
printf ("\t\tBiggest Value = %d\nValue Location = %d %d", e, k, c);
}

I corrected some stuff in your code
#include <stdlib.h>
#include <stdio.h> //you need to include this to use printf and scanf
#define CONSTC 4
#define CONSTL 4
int main()
{
int i=1;
int e;
int k;
int c;
int a;
int A [CONSTL][CONSTC];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
printf ("%2d - Type number\n", i);
scanf ("%d", &A [k][c]);
}
}
e = A[0][0];//Not sure what Matriz was, you meant A right?
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
if (e>A[k][c])
{
e = A [k][c];
//return k;
//return c;
}
}
}
printf ("\t\tBiggest Value = %d\nValue Location = %d %d", e, k, c);
return 0;
}
The main problem was that you let return k and return c in the middle of the loop, return stops the whole process and the whole program.
So you never get to the last printf.
Also, if you need the biggest value, you would need your if statement to be if(e < A[k][c]).

There are several problems in the code:
The return statement would return the given code to the main(), which makes no sense.
Some variables aren't declared which is a huge error.
Defined stdlib.h but I/O operations does exists in stdio.h library.
After the first return statement, the second will never get executed.
Code redefined:
#include <stdio.h>
#define MAX_ROWS 4
#define MAX_COLS 4
int main(void) {
int mat[MAX_ROWS][MAX_COLS];
int max = 0;
int posM, posN;
printf("Enter [4 x 4] Matrix below: \n");
for (int i = 0; i < MAX_ROWS; i++)
for (int j = 0; j < MAX_COLS; j++)
scanf("%d", &mat[i][j]); // getting the values of i * j positon
for (int i = 0; i < MAX_ROWS; i++)
for (int j = 0; j < MAX_COLS; j++)
if (mat[i][j] > max) {
max = mat[i][j]; // if max is lesser than the current one, then assign
posM = i + 1; // we had started the counting from 0, so increased 1
posN = j + 1;
}
printf("The largest element in the matrix: %d\n", max);
printf("The position is: %d x %d\n", posM, posN); // simply get the value
return 0;
}
The program simply asks the user to fill 4 ✕ 4 multidimensional array values. And then a loop is executed once as soon as the first loop quits.
The second loop tries to find the maximum value held by the matrix array. If the current value is lesser than the previously scanned value, it's then assigned. This process continues until the loop ends and finally displays the results.
A sample output:
Enter [4 x 4] Matrix below: // --- INPUT
1 2 3 4
4 3 2 1
3 3 3 4
5 4 3 1
The largest element in the matrix: 5 // --- OUTPUT
The position is: 4 x 1

The return; statement ends the function. When there's an expression afterwards, e.g. return k;, the result of the function is k.
Since the return statement exits from the function main, no more code runs after that point. This is why no output is printed.

Related

C program shows different result in Linux and online compiler

I wrote a program in C to arrange the data in ascending order. When I compiled the code it showed no error but when it runs it shows a very different result than expected. However, when I ran the code in online C compiler it shows the correct result. I entered 5 different numbers 2 ,3 ,1 ,5 ,4.
Result in Linux: 0 1 2 3 4
Result in online compiler: 1 2 3 4 5
Why is this happening?
#include<stdio.h>
int * array(int x[],int l){
int i,j,k;
for(i=0;i<l;i++){
for(j=0;j<l;j++){
if(x[j]>x[j+1]){
k=x[j];
x[j]=x[j+1];
x[j+1]=k;
}
}
}
return x;
}
void main(){
int i,n;
int *b;
printf("enter n\n");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
b=array(a,n);
printf("the ascending order is: ");
for(i=0;i<n;i++){
fflush(stdout);
printf("%d\t",b[i]);
}
}
Your code accesses memory beyond your array:
for(j=0;j<l;j++){
if (x[j] > x[j + 1]) {
x[j] = x[j + 1];
x[j + 1] = k;
In your case, when n = 5, you allocate the array for 5 elements with indices 0,1,2,3,4. The latest element of the array is x[4]. But when your code runs and j == l-1, you try to compare and even modify the element x[5]. In fact, your program should crash as it tries to access the "unallocated" memory. But probably because of aligning, the "x[5]" addresses the allocated memory. And, probably, x[5] = 0 on your computer, and your algorithm uses this element as a part of the sorting process. So your function array() returns the array of [0,1,2,3,4,5] and then your main() prints first five elements of this array.
That's why you've got sorted elements [0,1,2,3,4] instead of [1,2,3,4,5].
BTW, the bubble algorithm can be optimized to not touch already sorted elements.
Also, remember the array doesn't copy to pass into the function, the array always passes by its address, so it is not needed to "return" the modified array.
So, the final code can look like:
#include <stdio.h>
void array(int x[], int l)
{
int i, j, k;
for (i = l; i > 1; i--) {
for (j = 1; j < i; j++) {
if (x[j - 1] > x[j]) {
k = x[j - 1];
x[j - 1] = x[j];
x[j] = k;
}
}
}
}
void main()
{
int i, n;
printf("enter n\n");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
array(a, n);
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}
Of course, there are lots of things to be done in this code, like human-readable variables, formatting, further optimization. But I hope you can do it yourself.
You may find it easier to write programs to get their input from the command line instead of prompting for it. Using C11, you can allocate an array using the length provided by argc, and process the argv array directly:
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ) {
if( argc == 1 ) {
errx(EXIT_FAILURE, "syntax: %s values...", argv[0]);
}
int a[argc - 1];
for( int i=0; i < argc-1; i++ ) {
if( 1 != sscanf(argv[i + 1], "%d", a + i) ) {
errx(EXIT_FAILURE, "could not scan '%s'", argv[i + 1]);
}
}
array(a, sizeof(a)/sizeof(a[0]));
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}

Delete last input even number from array using stack

I'm a beginner at C programming. I'm making a program that will input numbers and delete the last input even number from the array using stack or the push-pop method.
The problem is I can't pop the last even number and I don't know what is wrong.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int top = -1;
int stack[MAX];
void deleteEven(int num[], int i);
int main() {
int num[100];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n");
printf("Even: ");
for (i = 0; i < size; i++) {
if (num[i] % 2 == 0) {
printf("%d, ", num[i]);
}
}
deleteEven(num, i);
return 0;
}
void deleteEven(int num[], int i) {
printf("\nAnswer: ");
if (num[i] % 2 == 0) {
stack[top--];
}
for (int j = top; j >= 0; --j) {
printf("%d, ", stack[j]);
}
}
I have implement the working one in C with implementing on your code, you can see below. I added int checkEven(int stack[], int stackSize) function which control the array if there is any even number or not. If not, so end the problem with returning 0 or whatever your error code is, other side if there is even number it returns the index of it and deleteEven function swipe the array (stack). It working for size of 5 array but you can fix it. I use 5 for easy testing.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
int top = -1;
int stack[MAX];
void deleteEven(int num[], int indexOfEven);
int checkEven(int stack[], int stackSize);
int main() {
int num[5];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n===stack===");
for( i = 0; i <size; i++){
printf("%d ", stack[i]);
}
int indexOfEven = checkEven(stack,5);
if(indexOfEven >= 0){
printf("This sequence has even number");
printf("the index => %d ",indexOfEven);
deleteEven(stack, indexOfEven);
}else{
printf("this sequence has no even number");
/*
no even number
exit
*/
return 0;
}
return 0;
}
int checkEven(int stack[], int stackSize){
for(int i = stackSize - 1; i >= 0; i--){
if(stack[i] % 2 == 0){
return i;
}
}
return -1;
}
void deleteEven(int num[], int indexOfEven) {
int simpleArray[5];
for(int t = 0; t < 5; t++){
simpleArray[t] = num[t];
}
int c;
for (c = indexOfEven; c < 4; c++)
simpleArray[c] = num[c+1];
for (c = 0; c < 4; c++){
printf("\n%d\n", simpleArray[c]);
}
}
So far you see the O(n) implementation of it with array but you describe that you want to implement it with push() - pop() - peek() stack mechanism. I want to write sudo code for fully Stack implementation.
let it inputs be 1 - 2 - 3 - 5 - 7
describe inputSize
describe mainStack
describe helperStack
read inputs to mainStack
show stacks
mainStack -> [1-2-3-5-7]
helperStack -> []
while mainStack.peek() != NULL :
if mainStack.peek() % 2 == 0: // even number
mainStack.pop()
break the loop
else:
describe popValue = mainStack.pop()
helperStack.push( popValue )
if inputSize == helperStack:
// no even number
// so nothing break the loop, every value is odd so, all there is another stack
// finish program with error code or return main array / inputs
show stacks
mainStack -> [ 1 ]
helperStack -> [ 3 5 7 ]
now pop() the all helperStack and push it to mainStack
while helperStack.peek() != NULL:
mainStack.push( helperStack.pop() )
show stacks
mainStack -> [ 1 3 5 7 ]
helperStack -> [ ]
Return mainStack as array format.
It seems that the last loop before the call to deleteEven will increment i until the end of the stack array regardless the last number is even or not, because all you do is checking if the current number is even and then printing it, and right after that going to the next one. that will iterate through all the numbers which will result in calling deleteEven with the last index of the array.
how about going from the last element of the array to index 0 (backwards) and printing the first encounter with even number?
Also, not really sure why you're using two different arrays and copying elements one by one after using scanf.

C - Getting the min and max of the randomly generated numbers

My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}
There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well
As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$
You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}
Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}
Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n

How to add integers in from two 2d arrays into a new 2d array with specified length by user?

I am fairly new around here and this year is the first time I am learning c. I have run into a problem concerning 2D arrays and such. The question is: Write a program that finds the sum of two 2D matrixes.
I can do this fairly easily but there is a problem I'm running into. For example I'll give the first set of arrays a length of 3x3.
If my first 2D array and the second array has:
{1,2,3; 4,5,6; 7,8,9} (1st array)
{0,0,0; 0,0,0; 0,0,0} (2nd array)
I am also given a the number of rows and columns by user. (User inputs 3x2) then it should appear like
{1,2; 3,4; 5,6} (OUTPUT)
but I am getting
{1,2; 3,5; 6,8}
Another example
User inputs 2x4 OUTPUT should be {1,2,3,4; 5,6,7,8}
What am I doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#define MAXROW 3
#define MAXCOL 3
int main() {
int ray1[MAXROW][MAXCOL], ray2[MAXROW][MAXCOL];
int r, c;
printf("Enter the number of ROWS: ");
scanf("%d", &r);
printf("Enter the number of COLUMNS: ");
scanf("%d", &c);
int sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(ray1);
printRay(ray1);
printf("Input integers for Array %d.\n", 2);
arrayIN(ray2);
printRay(ray2);
arraySUM(ray1, ray2, r, c, sumRay);
printSumRay(r, c, sumRay);
//printRay(sumRay);
}
void arrayIN(int ray[MAXROW][MAXCOL]) {
int r, c;
for (r = 0; r < MAXROW; r++) {
for (c = 0; c < MAXCOL; c++) {
printf("Enter Number for [ROW:%d COL:%d]: ", r, c);
scanf("%d", &ray[r][c]);
}
}
}
void arraySUM(int ray1[MAXROW][MAXCOL], int ray2[MAXROW][MAXCOL],
int r, int c, int sumRay[r][c]) {
int i, j;
int x, y;
i = j = 0;
int sum;
for (x = 0; x <= r; x++, i++) {
if (i < MAXROW) {
for (y = 0; y <= c; y++, j++) {
if (j < MAXCOL) {
sum = ray1[i][j] + ray2[i][j];
sumRay[x][y]= sum;
} else {
j = 0;
}
}
} else {
i = 0;
}
}
printf("\n");
}
void printSumRay(int r, int c, int sumRay[r][c]) {
int i, j;
for (i = 0; i < r; i++) {
printf("\n");
for (j = 0; j < c; j++) {
printf("%d\t", sumRay[i][j]);
}
}
}
void printRay(int ray[MAXROW][MAXCOL]) {
int i, j;
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf("%d\t", ray[i][j]);
}
}
printf("\n");
}
First off, you need to put function prototypes before main(), or at least move the function definitions before main(). It is not at all clear to me why you use a VLA for sumRay[][], but arrays of constant dimensions for ray1[][] and ray2[][]. Unless you have a compelling reason for doing so, it will be better to use VLA's all around.
You should be using the size_t type for variables that hold array indices. The scanf() and printf() statements that handle the size_t variables must then be modified to use the %zu conversion specifier.
The arraySum() function iterates over two pairs of duplicate array indices for reasons which are unclear. The logic here is convoluted and overly complex. The spurious output that you reported can be traced to this function; it is difficult to read and understand, which should be a sign that it needs to be rewritten. And if your intention is to add the input arrays only partially, the name does not reflect this intention. I have simplified this function, tightening the logic and removing the duplications. See the update below for a version that does partial array addition.
The printSumRay() function seems superfluous, since the printRay() function can do the same work, so I removed it, rewriting printRay() to use VLA's and tightening the code. The original code was using the magic number 3 in the controlling expressions of the loops here, instead of taking advantage of MAXROW and MAXCOL. But, even when not using VLA's, it is better practice to pass the dimensions to any function that will work with an array.
Here is a modified version of the original code:
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[r][c], ray2[r][c], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(r, c, ray1);
putchar('\n');
printRay(r, c, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(r, c, ray2);
putchar('\n');
printRay(r, c, ray2);
putchar('\n');
arraySUM(r, c, ray1, ray2, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
As a next step, you might add some error-checking to the input code, checking the return values from the calls to scanf(). And, as it is, it is awkward to enter the numbers for the arrays, being prompted for each element. You might experiment with ways to improve this.
Update
If your true goal is to combine only the initial rows and columns of your arrays, the above code works with only minor modification. You should still use VLAs, but instead of defining the global constants MAXROW and MAXCOL, define const size_t maxrow and const size_t maxcol within the body of main(). You should be passing these array dimensions to the functions anyway, not relying on global values.
A function has been added, partArraySUM(), with a name that more closely captures its purpose. The only difference between this function and arraySUM() is that the input arrays ray1[][] and ray2[][] have different dimensions than the array sumRay[][] which holds the results. There is no need to keep separate indices for this.
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
const size_t maxrow = 3;
const size_t maxcol = 3;
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[maxrow][maxcol], ray2[maxrow][maxcol], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(maxrow, maxcol, ray1);
putchar('\n');
printRay(maxrow, maxcol, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(maxrow, maxcol, ray2);
putchar('\n');
printRay(maxrow, maxcol, ray2);
putchar('\n');
partArraySUM(maxrow, maxcol, ray1, ray2, r, c, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
Sample interaction:
Enter the number of ROWS: 2
Enter the number of COLUMNS: 2
Input integers for Array 1.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 2
Enter Number for [ROW:0 COL:2]: 3
Enter Number for [ROW:1 COL:0]: 4
Enter Number for [ROW:1 COL:1]: 5
Enter Number for [ROW:1 COL:2]: 6
Enter Number for [ROW:2 COL:0]: 7
Enter Number for [ROW:2 COL:1]: 8
Enter Number for [ROW:2 COL:2]: 9
1 2 3
4 5 6
7 8 9
Input integers for Array 2.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 1
Enter Number for [ROW:0 COL:2]: 1
Enter Number for [ROW:1 COL:0]: 1
Enter Number for [ROW:1 COL:1]: 1
Enter Number for [ROW:1 COL:2]: 1
Enter Number for [ROW:2 COL:0]: 1
Enter Number for [ROW:2 COL:1]: 1
Enter Number for [ROW:2 COL:2]: 1
1 1 1
1 1 1
1 1 1
2 3
5 6
Just a minor change is needed. In arraySUM(), inside the else part you have re initialized
i=0 and j=0.
But after the re initialization they are incremented. So it will become 1 so while execution it will read ray[1], not ray[0].
Just re initialize them to -1.
i=-1 and j=-1

How to check if the elements in the main diagonal of a square matrix are the same?

I have to write a program which checks whether the elements (numbers) in the main diagonal of a square matrix (n x n) are the same (return 1 if they are, return 0 if they are not) using a function which is called by main(). The matrix is read from a file, done in main().
Here is my function so far: (The function checkdiag() does not seem to be working, only the main() function is printing out data)
#include <stdio.h>
int checkdiag(int matrix[][100], int size)
{
int i,j;
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
if (matrix[i][100]==matrix[j][100])
{
return (1);
printf ("\nThe elements in the main diagonal of the matrix are the same.\n");
}
else
{
return (0);
printf ("\nThe elements in the main diagonal are not the same.\n");
}
}
}
}
int main (void)
{
int matrix[100][100];
int size, diag;
int i,j;
FILE *data;
data= fopen("data10.txt", "r");`
fscanf (data, "%d", &size);
printf ("The size of the matrix is %dx%d, and the matrix is:\n", size, size);
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
fscanf (data, "%d", &matrix[i][j]);
printf (" %d% ", matrix[i][j]);
}
printf ("\n");
}
diag= checkdiag(matrix, size);
}
If someone could please help me see where I am going wrong, I would appreciate it!
P.S The file I'm using is:
3
4 5 6
7 8 9
3 6 7
Where the first value in the file (3) is the size of the matrix. (i.e 3x3)
#include <stdio.h>
int main (void){
FILE *file = fopen("data.txt","r");
int size, i, j;
fscanf(file, "%d" , &size);
int matrix[size][size];
// Read the data into the matrix
for(i=0; i<size; i++){
for(j=0; j<size; j++){
fscanf(file, " %d", &matrix[i][j] );
}
}
//determine if all diagonal entries in the matrix match the one at matrix[0][0]
i=matrix[0][0];
j=0;
while(j < size ){
if(matrix[j][j] != i)
break;
else{
j++;
}
}
//if j is equal to the size of the matrix then voila! diagonal entries match.
if(j==size){
printf("The diagonal is the same\n");
return 1;
}else{
printf("The diagonal is not the same\n");
return 0;
}
}
This returns: The diagonal is not the same. For the input:
5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 2
This returns: The diagonal is the same. For the input:
5
1 2 3 4 5
2 1 4 5 6
2 3 1 5 6
2 3 4 1 6
2 3 4 4 1
Your printf statements are after your return statements, so they'll never execute. A higher compiler warning level should warn you of code that cannot be reached. Also, you are using the value 100 where you mean to use the variable j.
However, you will find that your algorithm is incorrect in any case. It stops comparing after the first comparison. You need to check all diagonal elements.
Please try this checkdiag():
int checkdiag(int matrix[][100], int size)
{
int i;
for (i=1; i<size; i++)
{
if (matrix[i][i] != matrix[0][0])
{
printf ("\nThe elements in the main diagonal are not the same.\n");
return 0;
}
}
printf ("\nThe elements in the main diagonal of the matrix are the same.\n");
return 1;
}
As this function can only ever process square matrices, and you pass the size, maybe you should use it properly in the prototype: int checkdiag(int matrix[size][size], int size)
The elements in the main diagonal have the same column index and row index, thus you only need one loop.
You can return the moment you find the first element on the main-diagonal not the same as the element at [0][0], but you cannot conclude success if the first comparison is true. You must compare all elements.
No statement after a return statement is ever executed, unless there are control statements avoiding the return.
" %d% " is a bad format string for printf. You need to escape a literal % in a format string with a second %-character, like this: %%
Instead of cout<<; statements return 1 or 0 accordingly.
#include <iostream>
using namespace std;
int main(int arc, char *argv[]) {
int array[100][100];
int size;
cout << "Enter size\n";
cin >> size;
cout << "Enter matrix\n";
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cin >> array[i][j];
}
}
for (int i = 1; i < size; i++) {
if (array[i][i] != array[i-1][i-1]) {
cout << "Not Same ";
break;
} else if (i == (size - 1)) {
cout << "Same";
} else {
continue;
}
}
}

Resources