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().
Related
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]);
}
}
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last year.
Improve this question
I have written a C code to accept values via an array of structures which asks the user in the main function to choose whether he/she wants to input char or int values and sort the array via insertion sort and print it, but I am getting an
error from the compiler: {error]: expected expression before i
#include<stdio.h>
int n;
typedef struct ls{
int a;
char l;
}i[50],ls;
int main(){
printf("Enter the value\n");
scanf("%d",&n);
ls int1;
int ans;
printf("Main Menu\n");
printf("1.)integer sort \n2.)Characrter sort\n");
scanf("%d",&ans);
if(ans==1){
intSort(i.a);
}
else if(ans==2){
charSort(i.l);
}
else{
exit(0);
}
int ans1;
printf("Would you like to print the array\n");
scanf("%d",&ans1);
if(ans==1 && ans1==1){
display(i.a);
}
else{
display(i.l);
}
}
int intSort(int a[]){
int j;
printf("Enter the values into the array \n");
for(j=0;j<n;j++){
scanf("%d",&a[j]);
}
// insertion sort function call
insertionSort(a);
return 1;
}
int charSort(char a[]){
int j;
printf("Enter the values into the array \n");
for(j=0;j<n;j++){
scanf(" %c",&a[j]);
}
insertionSort(a);
return a;
}
int insertionSort(int a[]){
int temp,i,j;
for(i=1;i<n;i++){
temp= a[i];
j=i-1;
}
while(j>=0 && temp<a[j]){
a[j+1]=a[j];
j-=1;
}
a[j+1]=temp;
return 1;
}
int display(int a[]){
int i;
printf("Sorted array:");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
}
You are defining the type incorrectly. If I understand correctly, you want do have a typedef ls and then initialize an array of your newly defined structures. You would want to do something like this:
#include <stdlib.h>
#include <stdio.h>
typedef struct ls {
int a;
char l;
} ls;
int main() {
int i;
ls *array_of_ls = malloc(50*sizeof(*array_of_ls));
for (i = 0; i < 50; i++) {
array_of_ls[i].a = i;
array_of_ls[i].l = 65+i;
printf("ls[%d] = (%d, %c)\n", i, array_of_ls[i].a, array_of_ls[i].l);
}
free(array_of_ls);
}
Of course, make sure you handle exceptions, etc. But this should get you going.
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.
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;
}