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 10 months ago.
Improve this question
I am beginner in C. I have been writing a program code to find largest element in Array.
Passed Value is not able to store in array of type: float.
Instead default Value:0 is being stored.
What to do?
#include <stdio.h>
// Largest Element
int main() {
int n,i;
float arr[100];
printf("Enter Element Count in range(1,100):-");
scanf("%d",&n);
while(n>100 || n<1){
printf("Enter Element Count in range(1,100) again:-");
scanf("%d",&n);
}
for(i=0; i<n;i++){
printf("Enter Element:-");
scanf("%f",&arr[i]);
}
for(int k=0;k<n;k++){
printf("Element-%d:-%d\n",k+1,arr[k]);
}
for(int j=0;j<n;j++){
for(int k=j+1;k<n;k++){
if (arr[j] < arr[k]){
break;
}
else{
printf("Largest Element:-%d\n",arr[j]);
break;
}
}
continue;
}
return 0;
}
OUTPUT SCREEN
Explanation
In the two cases below you are using %d to print a float number. That's why you are getting 0 printed and not the actual number.
Use %f like you did for reading the value on scanf earlier instead of %d for the float values.
printf("Element-%d:-%d\n",k+1,arr[k]);
printf("Largest Element:-%d\n",arr[j]);
To output values of the type float you have to use the conversion specifier f. The conversion specifier d is designed to output integer values.
So these calls of printf
printf("Element-%d:-%d\n",k+1,arr[k]);
and
printf("Largest Element:-%d\n",arr[j]);
are incorrect. You have to write
printf("Element-%d:-%f\n",k+1,arr[k]);
and
printf("Largest Element:-%f\n",arr[j]);
Also if you are going to find the largest element in the array then these for loops do not make a sense.
for(int j=0;j<n;j++){
for(int k=j+1;k<n;k++){
if (arr[j] < arr[k]){
break;
}
else{
printf("Largest Element:-%d\n",arr[j]);
break;
}
}
continue;
}
At least for example the continue statement is redundant. And the inner for loop is also redundant because it is interrupted at once due to break statements in the if-else statement.
The largest element is searched the following way using only one for loop.
int largest = 0;
for ( int i = 1; i < n; i++ )
{
if ( arr[largest] < arr[i] ) largest = i;
}
printf( "Largest Element:-%f at position %d\n",arr[largest], largest );
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 1 year ago.
Improve this question
My code:
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
printf("%d", menu[i]);
}
I'm trying to ask the user for input and add it to the array and then at the end to output the whole array e.g 1,2,3,4....16, however as of now it always returns the value 16 no matter what the user input.
You need to run loop twice. Once for taking inputs and then for displaying all numbers.
#include <stdio.h>
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
{
printf("%d\n", menu[i]);
}
}
Your code has an array index bound check failure.
printf("%d", menu[i]);
The value of i here is going to be 16 because you are using it after the loop. The loop terminal condition is i == 16. The menu array is only defined for index values of [0..15]. The value you see in the output is entirely random depending on the state of the execution stack. You could test this by printing instead menu[65] and see random data or maybe a segmentation fault.
Printing out the array to the console is the same loop as your input, but with the printf embedded in it instead. So your code should have 2 loops in it. One loop to gather input, and the other loop to output the input.
The answer is in the comments.
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for(i = 0; i < 16; i++)
printf("%d ", menu[i]);
you can add a loop at the end of your code like this
int main()
{
int menu[16];
int i;
for(i = 0; i < 16; i++)
{
printf("Input array value");
scanf("\n%d", &menu[i]);
}
for (i = 0;i<16;i++)
{
printf("%d ",menu[i]);
}
}
"I'm trying to ask the user for input and add it to the array and then at the end to output the whole array"
Just because it has not been suggested yet...
This can be done using a single loop, or with no loops at all.
(The looping option below is an adaptation of your code with comments describing differences.)
//The following items, are optionally
//defined here instead of in-line with code.
//they are used to clean up the scanf() and sprintf() calls below
#define data menu[0],menu[1],menu[2],menu[3],menu[4],menu[5],menu[6],menu[7],menu[8],menu[9],menu[10],menu[11],menu[12],menu[13],menu[14],menu[15]
#define input_data &menu[0],&menu[1],&menu[2],&menu[3],&menu[4],&menu[5],&menu[6],&menu[7],&menu[8],&menu[9],&menu[10],&menu[11],&menu[12],&menu[13],&menu[14],&menu[15]
const char input_format[] = {"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d"};
const char format[] = {"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n"};
//it also preferred to avoid magic numbers when possible
#define ELEMENTS 16
#define MAX_LEN_INT 11
//to demonstrate both looping and sequential methods to input and output the same thing
#define USE_LOOP 1 //change to zero for doing this with no loops
int main(void)//added void
{
int menu[ELEMENTS] = {0};
//char buffer `output` should accommodate room for max number of
//characters expressed in 32bit `int` data type: `11` (from the value: `-2147483648`)
//times count of elements to be output: ELEMENTS plus NULL terminator + punctuation.
//This should do it:
int size = ELEMENTS*MAX_LEN_INT+ELEMENTS + 1;
char output[size];//buffer for outputing final line showing user input values
memset(output, 0, sizeof(output));
#if USE_LOOP
int i;
printf("Input array values:\n");//moved outside the loop to display only once
for(i = 0; i < ELEMENTS; i++)
{
printf("enter value %d:\n", i+1);//prompt user for each input value
scanf("%d", &menu[i]);//scan value into array element
}
#else //Use sequential data entry
printf("Enter %d space delimited integer values (eg: 1 2 -45 78... 123) then <enter>:\n", ELEMENTS);
scanf(input_format, input_data);
#endif
//again, outside the loop to display only once
//place all data into printable buffer
sprintf(output, format, data);//using short representations of format specifier and data for readability
printf("%s", output);
return 0; //added return to comply with int function type.
}
Tested with largest possible number of digits using sequential method:
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 4 years ago.
Improve this question
Following code:
#include <stdio.h>
int izbaciSveProste(int n, int x[], int y[])
{
int i;
int flag=0;
for(i=2; i<n/2; i++)
{
if(n%i ==0)
{
flag =1;
break;
}
}
if(flag==1)
return 0;
else
return 1;
}
int main()
{
int i,j,n,x[100],y[100];
printf("Koliko elemenata zelite u polju?\n");
scanf("%d", &n);
printf("Enter elements in array:- ");
for(i=0;i<n;i++)
{
scanf("%d",&x[i]);
}
int len = sizeof(x)/sizeof(x[0]);
for(i=0; i<len; i++)
{
if(izbaciSveProste(x[i]))
{
for(j=i; j<len; j++)
{
x[j] = x[j+1];
}
i--;
len--;
}
}
printf("Elementi nakon brisanja su:\n");
for(i=0; i<len; i++)
printf("%d\n",y[i]);
printf("\n");
return 0;
}
Purpose of this program should be to delete all prime numbers from array x[] with n elements, remaining elements should be rewritten in array y[] and show count of elements in array y[] in the end.I believe that function is okay and error is in main() specifically in storing y[].
Your function int izbaciSveProste(int n, int x[], int y[]) requires three arguments. Your code izbaciSveProste(x[i] passes one argument. That's not much enough. The compiler tells you that fact with the error message:
error: too few arguments to function 'izbaciSveProste'
Your function prototype has 3 parameters:
int izbaciSveProste(int n, int x[], int y[])
When you call the function, you only provide 1:
if(izbaciSveProste(x[i]))
The compiler wants to get all 3.
As your function doesn't even touch the 2 array parameters, you might simply remove them from the function definition and only take 1 integer.
Another problem:
You print y[i] in your loop but you never assign any value to that array.
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
For some reason when I reallocate the size of the array created using calloc it deletes the values that have already been inputted, maybe something else is happening but i don't understand why. I have changed the code so that it includes everything it needs to work, sorry i forgot about that
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned int arraySize; // size of array
int moreElements; // stores user input whether more elements are to be
int additionalElements = 0; // number of elements to be added to array
unsigned int type; // stores the type of array
float sum = 0; // the sum of the elements
float *floatArrPtr; // pointer to a flaot
floatArrPtr = calloc(arraySize, sizeof(float));
for(size_t i = 0; i < arraySize; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
printf("%f\n", floatArrPtr[i]);
}
for(size_t i = 0; i < arraySize; i++)
{
sum += *(floatArrPtr+i);
}
sum /= arraySize;
printf("The average of the elements of the array is %lf\n", sum);
do
{
printf("if there are more elements to be added enter 1 and 0 if not: ");
scanf("%d", &moreElements);
} while (moreElements != 0 && moreElements != 1);
if (moreElements == 1) {
printf("please enter the number of additional elements you want to add: ");
scanf("%d", &additionalElements);
floatArrPtr = realloc(intArrPtr,(arraySize+additionalElements) * sizeof(float));
for (size_t i = arraySize; i < arraySize+additionalElements; i++)
{
printf("Please enter a number for the array: ");
scanf("%f", &floatArrPtr[i]);
}
sum = 0;
for(size_t i = 0; i < arraySize+additionalElements; i++)
{
sum += *(floatArrPtr+i);
printf("%zu, %lf, %d\n", i, floatArrPtr[i], arraySize + additionalElements);
}
sum /= (arraySize + additionalElements);
printf("The average of the elements of the array is %lf\n", sum);
}
}
That calloc code at the top is wrong. For an arraySize of 1000 it allocates a million floats, or 4MB. Look that up.
Then I assume the real problem is the intArrayPtr that slipped in from earlier code.
Use functions, they pay off. – I mean make all your code no more than 4 lines or so long per function, this will stop old variables from earlier from slipping in.
The wrong line is
floatArrPtr = realloc(intArrPtr...
You need
floatArrPtr = realloc(floatArrPtr...
I don't know the purpose of intArrPtr, but it looks like if that code compiles that its coming in from code above.
You have global variables. One must be very careful with them as they are a pain at best, at worst they cause unforeseen edge case bugs, which is what you have.
Make your project two files, one for integer and one for float, and you will see your mistake in the compiler.
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 6 years ago.
Improve this question
#include <stdio.h>
#include <conio.h>
int main(void){
int n, i, a[10], sum = 0;
for(i = 0; i < 10; i++){
printf("Enter the marks of %dth student ", i + 1);
scanf("%d", a[i]);
sum = sum + a[i];
}
printf("The total sum is %d", sum);
return 0;
}
Is there an error in my program?
Everytime I run the program, after entering the marks for the first student, I get an error saying that my program has stopped working!
This happens for most of my programs where I have used arrays!
It should be
scanf("%d",&a[i]);
Pass-by-pointer, not by value. Unfortunately, some compilers cannot perform compile-time type safety checks on calls to scanf(). So basically scanf() is treating your (uninitialized value in) a[i] as a pointer, which leads to undefined behavior.
Try this:
#include <stdio.h> //stdio not Stdio
int main(void){
int n,i,a[10],sum=0;
for(i=0;i<10;i++){
printf("Enter the marks of %dth student ",i+1);
scanf("%d",&a[i]); // &a[i] not a[i]
sum=sum+a[i];
}
printf("The total sum is %d\n",sum);
return 0;
}
scanf needs a pointer, not the value.
You invoked undefined behavior by passing data having the wrong type to scanf(). You have to pass int* to scanf(), not int, for %d.
I also corrected the #includes and added input error check.
Try this:
#include<stdio.h>
int main(void){
int n,i,a[10],sum=0;
for(i=0;i<10;i++){
printf("Enter the marks of %dth student ",i+1);
if(scanf("%d",&a[i])!=1){
fputs("read error\n",stdout);
return 1;
}
sum=sum+a[i];
}
printf("The total sum is %d\n",sum);
return 0;
}
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 8 years ago.
Improve this question
I'm a newbie in programming.
I've tried this code to find out the maximum value in an array. I've also drawn the logic of this code on paper & it's coming out valid.
I'm wondering why this code is printing garbage value instead of max value.
Here is the code:
void main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d", &a[i]);
}
for(i=0; i<size; i++){
if(a[i]<a[i+1]){
max=a[i+1];
}
}
printf("\nMax value is %d", max);
}
You can try this code..
int main(){
int size, i, max=0;
printf("Enter the size of the array:\n");
scanf("%d", &size);
int a[size];
printf("Enter the elements:\n");
for(i=0; i<size; i++){
scanf("%d",&a[i]);
}
// Search Max Value
max = a[0];
for (i = 0; i < size; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
printf("\nMax value is %d", max);
return 0;
}
You need to initialize max somewhere prior to searching the array (which the current copy of the post does do ... but the first one did not). However, if negative values are entered, it probably makes sense to use INT_MIN.
max = INT_MIN;
And then you need to compare the current max value against the array elements (rather than the array elements against themselves.
At this point, in your code, you're going outside of your array. You're also not comparing the element of the array to the current max, but to the next element in the array. This would be for sorting an array, but not finding the maximum value.
for(i=1; i<=size; i++){ /* i<=size */ you go one beyond
if(a[i]<a[i+1]){ /* when i==size, you're 2 outside of your array */
max=a[i+1];
}
}
You can have i<(size-2), but it's not very pretty.
You can also set max to the first element of the array, and loop from the second element.
max = a[0];
for(i=1 ; i<size ; i++){ /* loop to the end of the array */
if(a[i] > max){ /* compare current space to max */
max = a[i];
}
}
main has return type int, always. Valid prototypes:
int main()
int main(int argc, char* argv[])
Starting with 0 as initial value for maxinstead of INT_MIN means you have an implicit element of value 0.
Always test the return value of scanf, it might not succeed.
Your second loop tries reading a[size] and a[size+1], while your array only goes to index size-1.
Correct the termination condition to <.
Correct the comparison to compare a[i] with max.