Why is the output junk value [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
In the below code, When I did the same logic without using functions it gave correct answer.
But with using functions its giving some junk value. The question was to print the sum of diagonal matrix in array using c using functions.
#include<stdio.h>
int read(int a[][100],int,int);
int displayres(int a[][100],int,int);
int main()
{
int m,n,a[100][100];
printf("Enter the number of rows: ");
scanf("%d",&m);
printf("Enter the number of columns: ");
scanf("%d",&n);
if(m==n)
read(a,m,n);
displayres(a,m,n);
}
int read(int a[][100],int m,int n)
{
int i,j;
if(m==n)
printf("Enter the elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
}
int displayres(int a[][100],int m,int n)
{
int i,j,abc;
for(i=0,j=0;i<m,j<n;i++,j++)
{
abc = abc + a[i][j];
}
printf("%d\n",abc);
}

As the diagonal is processed for quadratic matrices then these declarations of the functions
int read(int a[][100],int,int);
int displayres(int a[][100],int,int);
do not make a great sense. One parameter is redundant. The functions can be declared like
void read(int a[][100], size_t );
int displayres(int a[][100], size_t );
correspondingly instead of these two prompts
printf("Enter the number of rows: ");
scanf("%d",&m);
printf("Enter the number of columns: ");
scanf("%d",&n);
you should use only one prompt and also you need to check that the entered number (for example n) is not greater than 100.
As the function read returns nothing its return type should be void.
Its definition can look like
void read(int a[][100], size_t n )
{
printf("Enter the elements:\n");
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ )
{
scanf("%d",&a[i][j]);
}
}
}
Within the function displayres you forgot to initialize the variable abc. And the function should not output anything. It should return the calculated value. The function can look the following way
int displayres(int a[][100], size_t n )
{
int abc = 0;
for ( size_t i = 0; i < n; i++ )
{
abc += a[i][i];
}
return abc;
}
And in main you can write
printf( "The sum is %d\n", displayres( a, n ) );
If you want to calculate the sum for a matrix of any sizes then the function displayres can look the following way
int displayres( int a[][100], size_t m, size_t n )
{
int abc = 0;
for ( size_t; i < m && i < n; i++ )
{
abc += a[i][i];
}
return abc;
}
As for your for loop then you are using the comma operator in the condition
for(i=0,j=0;i<m,j<n;i++,j++)
It is the same as to write
for( i=0, j=0; j < n; i++,j++ )
because the value of the first operand of the comma operator is discarded.

Related

Reason and solution of my code which is giving segmentation fault in C program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
#include <stdio.h>
int display(int arr[], int n);
int main()
{
int i, n;
printf("\nEnter the Size of Array:");
scanf("%d", &n);
int arr[n];
printf("\nEnter the %d Values of Arrays", n);
for (i = 0; i < n; i++)
{
scanf("%d", arr[i]);
}
display(&arr[0], n);
return 0;
}
int display(int arr[], int n)
{
int i;
printf("\nThe %d elements are:\n");
for (i = 0; i < n; i++)
{
printf("Array [%d]= %d\n", i, arr[i]);
}
}
This is the code for printing the array values using function. And in Run-time it gives Segmentation fault error. Help me to fix this.
You have to pass the address of the variable when calling scanf() in the loop, just as you do when reading n.
When passing an array to a function, we usually just write the name of the array. This is equivalent to passing &arr[0], but we don't normally write that out.
#include <stdio.h>
int display(int arr[], int n);
int main()
{
int i, n;
printf("\nEnter the Size of Array:");
scanf("%d", &n);
int arr[n];
printf("\nEnter the %d Values of Arrays", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
display(arr, n);
return 0;
}
int display(int arr[], int n)
{
int i;
printf("\nThe %d elements are:\n");
for (i = 0; i < n; i++)
{
printf("Array [%d]= %d\n", i, arr[i]);
}
}

Code to find max number from array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wrote the following code to find the max number from a array of numbers. Apparently there is an error in my code.It is a segmentation error. Please help me identify it.
#include <stdio.h>
void max(int n,int A[n]);
int main()
{
int n;
int A[n];
max(n,A[n]);
}
void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements in your array\n");
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
if(A[i]>max)
{
max=A[i];
}
}
printf("%d",max);
}
int n;
int A[n];
You have to initialize n otherwise it contains garbage value. And now after this point you run into undefined behavior.
Correct code would be
#include <stdio.h>
#include <stdlib.h>
void printMax(int n,int A[]);
int main()
{
size_t n;
printf("Enter the number of elements you want in your array\n");
if( scanf("%zu",&n) != 1){
fprintf(stderr,"Error in input");
}
if( n <= 0){
fprintf(stderr, "%s\n", "Error in input : Enter number >= 0 .");
}
int a[n];
printf("Enter the elements in your array\n");
for(size_t i = 0; i < n; i++)
{
if( scanf("%d",&a[i]) != 1){
fprintf(stderr,"%s\n","Error in input");
exit(1);
}
}
printMax(n,a);
return 0;
}
void printMax(size_t n,int A[])
{
int max=A[0];
for(size_t i = 1; i < n; i++)
if(A[i] > max)
max = A[i];
printf("%d",max);
}
In main() you declare n but it has no value, so likely defaults to 0. You then declare and define an array A and give it size n, which as I say is likely zero.
Within max() you then read in a value and assign it to n but your array A is size zero.
So change main() to
/* Get the number of items to store in the array */
int n;
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
/* Create the array of the given size */
int A[n];
/* Now find the max value in that array */
max(n,A);
And remove the setting of n from max().

Can somebody please help me with the mistake in algorithm [closed]

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 7 years ago.
Improve this question
Problem Link: https://www.codechef.com/problems/PERMUT2
Problem : Getting non ambiguous for all test cases. There is absolutely no problem in executing the program, no errors.
Can you please point out the mistake in my code/algorithm:
#include <stdio.h>
#include <stdlib.h>
int index_func(int number, int *array, int x);
int main(){
int n;
scanf("%d", &n);
int *nums = (int*)malloc(n*sizeof(int));
int i;
for(i=0; i<n; i++){
scanf("%d", &nums[i]);
}
int j;
int counter = 0;
for(j=0; j<n; j++){
if(nums[j] != index_func(j+1, nums, n)){
counter = 1;
break;
}
}
if(counter == 0){
printf("ambiguous\n");
}else{
printf("non ambiguous\n");
}
return 0;
}
int index_func(int number, int *array, int x){
int z, index;
for(z=0; z<x; z++){
if(number == array[z]){
index = z;
return z;
}
}
}
The numbers in the array start with one, but the indices in C arrays start with 0. A quick fix to your program would be to add one to the returned index when you compare it to the current number:
if (nums[j] != index_func(j + 1, nums, n) + 1) ...
An alternative solution is to adjust the array data by subtracting one after you scan it, so that the array contains zero-based numbers.
A problem may arise with larger arrays, because every call to index_func scans the whole array from the beginning and will traverse half of it on average. The solution will be correct, but very slow.
But you don't have to determine the index to do the comparison. It is sufficient to check whether the number at the index of the current number is the current index. That leads to this function:
int is_ambiguous(const int *array, int n)
{
int i;
for (i = 0; i < n; i++) {
if (array[array[i] - 1] != i + 1) return 0;
}
return 1;
}
Some notes on your original code:
You should return an invalid index, probably −1, from index_funct when the nuber isn't in the array. I know, this shouldn't happen here, but next time you copy and paste the code and the missing return value might bite you.
You don't really need the variable index in index_funct. Separating pieces of code into small functions can make the program control easier. Compare the above function is_ambiguous with your inline solution with a counter variable and a break.
When you allocate, you must also free, which you don't.
try this solution:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int index_func(int number, int *array, int x);
int main(){
int n;
scanf("%d", &n);
int *nums = (int*)malloc(n*sizeof(int));
int i;
for(i=0; i<n; i++) {
scanf("%d", &nums[i]);
}
int j;
int counter = 0;
for(j=0; j<n-1; j++){
if((abs(nums[j+1] - nums[j]) != abs(n-1)) && (abs((nums[j+1] - nums[j]) != 1)))
{
counter = 0;
}
else
{
counter = 1;
}
}
if(counter == 0){
printf("ambiguous\n");
}else{
printf("non ambiguous\n");
}
free(nums);
return 0;
}

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

Passing a row in a 2D array to a function using a pointer in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I need to write a program that scans in a 2D array and then finds the minimum value in each row by using a function.
The prototype int RowMin(int *prow, int ncols) was given in the instructions. My problem is that I don't know for sure how to use the pointer. This was my best guess and it's not correct. The program crashes after I enter in the values of the array.
This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int RowMin(int *prow, int c);
int main()
{
int a[MAX][MAX];
int r, c, min;
int i = 0, j = 0;
printf("Enter number of rows & columns of array:\n");
scanf("%d %d", &r, &c);
printf("\nEnter elements of 2-D array:\n");
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d", &a[i][j]);
}
}
for(i=0;i<r;i++)
{
min = RowMin(i, c);
printf("The min in row %d is %d",i, min);
}
return 0;
}
int RowMin(int *prow, int ncols)
{
int temp, i;
int a[*prow][ncols]; //this is where it is messing up
temp = a[*prow][0];
for(i=0; i<ncols; i++)
{
printf("Good5");
if(temp > a[*prow][i])
{
temp = a[*prow][i];
}
}
return temp;
}
Pass the address of the each row:
min = RowMin(a[i], c);
Then do this in your routine in order to find min in each row
int RowMin(int *prow, int ncols)
{
int min=prow[0], i;
for(i=0; i<ncols; i++)
{
if(min > prow[i])
{
min = prow[i];
}
}
return min;
}
The function call should look like this
min = RowMin(&a[i],c)
You should pass the address of each row.
The function should be modified like this
int minRow(int *ptr, int columns)
{
//ptr has the address of each row
int minElt = ptr[0]; //Contains the first Element
for(int i = 0; i < columns; ++i)
{
if( minElt > ptr[0] )
minElt = ptr[0]
}
return minElt;
}
In this loop
for(i=0;i<r;i++)
{
min = RowMin(i, c);
printf("The min in row %d is %d",i, min);
}
you have to pass a row of the array to the function. So the call will look like
min = RowMin( a[i], c );
Take into account that you should check that entered values of rows and columns are not greater than MAX. Or if your compiler supports variable length arrays you could use a variable length array when its sizes are set by entered values of r and c.
The function itself is also invalid. It can be written the following way
int RowMin( const int *prow, int ncols )
{
int i = 0;
int min = prow[i];
while ( ++i < ncols )
{
if ( prow[i] < min )
{
min = prow[i];
}
}
return min;
}
Correspondingly the function have to be declared like
int RowMin( const int *prow, int c );

Resources