i wrote the code but i dont get max value how to find max value
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k;
float sum=0;
float nu[c];
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
nu[c]=temp[0];
for (j = 0; i>=j; j++)
{
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
If you run your compiler with a -Wall (as you should always do), you should have seen the problems :
gcc -Wall -o foo foo.c
foo.c: In function 'main':
foo.c:35:14: warning: unused variable 'k'
foo.c:33:14: warning: unused variable 'min'
foo.c:62:1: warning: control reaches end of non-void function
foo.c:37:4: warning: 'c' is used uninitialized in this function
Here is the source code of a program that works :
#include <stdio.h>
int main(void)
{
float max = 0; // hypothesis : numbers keyed by the users are > 0
float min = 0; // hypothesis : numbers keyed by the users are > 0
int i, c;
float sum = 0;
float nu[100]; // hypothesis : no more than 100 numbers keyed by user
// hypothesis : float type is enough to store numbers keyed by user
printf("Number of values :");
scanf("%d",&i);
for (c = 0; c < i; c++)
{
printf("values=");
scanf("%f",&(nu[c]));
if (nu[c] > max) {
max = nu[c];
}
if (min == 0) {
min = nu[c];
} else if(nu[c] < min) {
min = nu[c];
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f \n", max);
printf("minimum value = %f \n", min);
return 0;
}
You need a single for loop and not nested for loop.
Get input using the first for loop
Assign first element of the input array to variable, call this max
Compare each element of the array using a for loop again
If you get a value greater than max then change max to this value using the below code
if(max< a[i])
max=a[i];
At the end of these steps you can get max value.
Try to put these steps into a C code and it should be fine. There are some problems with the code you have written. I have written a small snippet for you to get input for number of elements and store them into your array for floats.
int number_of_elements;
printf("Enter the number of elements:\n");
scanf("%d", &number_of_elements);
for(i=0;i<number_of_elements;i++)
scanf("%f",&a[i]);
Here's the code with some helpful pointers:
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k; // k isn't used anywhere.
float sum=0;
float nu[c]; // c isn't set at this point so the
// runtime couldn't create an
// array anyway.
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
// You should set min/max to nu[c]
// if c is 1 regardless.
nu[c]=temp[0]; // Why are you scanning into nu[c]
// then immediately overwriting?
for (j = 0; i>=j; j++) // Why figure out the max *every*
{ // time you enter a value?
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
I'd also suggest you go back to my original answer and create your code from that. It really is a much cleaner way of doing it than trying to fiddle around with arrays.
Let me emphasise that: if you're using an array, you're doing it the hard way!
Or this
#include <stdio.h>
int main(void)
{
float temp;
int val,i,j,k;
double sum = 0;
double number[val];
printf("Enter the number of values: ");
scanf("%d", &val);
double number[val];
for(i=1; i <= val ;i++)
{
printf("enter a value: ");
scanf("%lf", &number[i]);
sum = sum + number[i];
}
for(i=1;i<=val;i++)
{
for(j=i+1;j<=val;j++)
{
if(number[i] > number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sum = %.lf\n", sum);
printf ("Maximum element: %f\n",number[val]);
printf ("Minimum element: %lf\n", number[1]);
}
remove the temp (cant see the point of it)
set max to some initial value (e.g. first element of the array)
and change if statement to:
if (nu[c]> max)
{
max = nu[c];
}
This may not solve your question but nu[c] seems bad allocated to me since c value is undefined
Related
I just started learning C language. So, I am running into a lot of problems. I thought declaring i under for loop is enough, and I can use the value of i for outside too. But I think, that was not the case. Can someone explain the situation, please.
# include <stdio.h>
int main(void)
{
int x;
printf("Enter how many numbers in arrays you want to input : ");
scanf("%i", &x);
int score[x];
for(int i= 0; i <= x; i++)
{
printf("Enter the score : ");
scanf("%i", &score[i]);
}
// in the below line the output said "i" is undeclared.
float average = score[i] / x;
printf("The average score is : %f", average);
}
The answer is fairly simple
because of where you decalred i it is only visable to the for loop.
To make i visable to the whole function all you need to do is:
int i = 0;
for (; i <=x; i++){
printf("Enter the score : ");
scanf("%i", &score[i]);
}
this makes i avaliable throughout the function
i is declared in the initialization section of a for statement. That means the scope and lifetime of that variable is the expressions in the for statement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.
You need to declare i outside of the loop if you want to use it outside of the loop.
int i;
for(i= 0; i <= x; i++)
That being said, you don't actually need to use i outside of the loop.
There are security issues associated with using scanf so don't use it for anything serious. That said, I tried to re-write your program properly, and it still has pretty rubbish input validation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUTTEXTLEN 20
#define MAXINPUTINT 1000
int inputint() {
char inputtext[INPUTTEXTLEN + 1] = {0};
long inputval;
while (1) {
fgets(inputtext, INPUTTEXTLEN, stdin);
if (strlen(inputtext) > 0) {
inputval = atoi(inputtext);
if ((inputval < MAXINPUTINT) && (inputval >= 0)) break;
}
}
return (int)inputval;
}
int main(void)
{
int x = 0;
printf("Enter how many numbers in arrays you want to input : ");
//scanf("%i", &x);
while (x <= 0) {
x = inputint();
}
int score[x];
float average = 0;
for(int i= 0; i < x; i++)
{
printf("Enter the score : ");
//scanf("%i", &score[i]);
score[i] = inputint();
average += score[i];
}
average /= x;
printf("The average score is : %f\n", average);
}
I am very new to C and am having some issues with a function I am writing. The assignment is to write a function in which it prompts for height and width parameters to draw a box with. I have the function written and it compiles correctly, but the issue I'm having is that I need to call the function twice and save a width from the first call, and a height from the second. Now, this would be easy if I could use pass-by-reference, but I am not allowed to as the function has to be an int. Here is what I have so far.
//LaxScorupi
//11/21/2021
// C
#include <cstdio>
int GetSize(int min, int max)
{
int range;
while (range < min || range > max)
{
printf("Please enter a value between %d and %d: ", min, max);
scanf("%d", &range);
}
return range;
}
/*
This is where I think I am missing something obvious. Currently, I
have printf in place to
just read the value back to me, but I know my "range" will be saved as
whatever my second call
of GetSize is. I've tried creating variables for height and width, but
am unsure how to take
my return defined as range and store it as two different values.
*/
int main ()
{
int min;
int max;
int range;
range = GetSize(2, 80);
printf("Your width is %d\n", range;
range = GetSize(2, 21);
printf("Your height is %d\n", range);
return 0;
}
Thanks in advance- Lax Scorupi
struct
{
int height;
int width;
}range;
range.width = GetSize(2, 80);
range.height = GetSize(2, 21);
print("Height:%d, Width:%d\n", range.height, range.width);
Basically you can just save them in two different variables and store them in an array so u can use them later.I just added the names and the array into your code down here.
#include<stdio.h>
int GetSize(int min, int max)
{
int range;
while (range < min || range > max)
{
printf("Please enter a value between %d and %d: ", min, max);
scanf("%d", &range);
}
return range;
}
int main ()
{
int min;
int max;
int range1, range2;
range1 = GetSize(2, 80);
printf("Your width is %d\n", range1);
range2 = GetSize(2, 21);
printf("Your height is %d\n", range2);
int a[2] = {range1, range2};
printf("%d %d", a[0], a[1]);
return 0;
}
I'm taking CS courses, and wrote a simple program to find an average of the given (input) amount of inputs.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Please enter the number of scores: ");
int scores = [n];
for(int i=0; i<n; i++)
{
int scores[i] = get_int("Please, enter the score: ");
}
printf("Average: %f\n", average(n, scores));
}
float average(int length, int array[])
{
int sum = 0;
for(int i = 0; i < length; i++)
{
sum += sum + array[i];
}
return sum / (float)length;
}
When compiling, "expected expression" error occurs on line 10 (i.e. {int scores = [n];} —
any help or suggestions would be appreciated!!
This is invalid syntax:
int scores = [n];
If you want to define scores as an array of size n you want:
int scores[n];
Also, this doesn't do what you might expect:
int scores[i] = get_int("Please, enter the score: ");
This creates an array called scores of size i, masking the array defined previously, and attempts to initialize it with a single value instead of a list of values. If you want to assign to the existing array you want:
scores[i] = get_int("Please, enter the score: ");
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
system("pause");
}
The code runs fine and gives the correct average of the integers entered but the values that are less than the average comes out as -858993460
You are trying to print out ray[i], but i is currently 20which is outside the index of your array. Did you mean to copy your for loop around that if statement?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
average=(sum/20);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
}
printf("Average = %.2f", average);
system("pause");
}
This gives the "the following integers are below the average" part after each value that is lower than the then average, but I need it to show the values which are below the average together at the end.
The out-of-index issue
As the others have already pointed, your index is out of bounds.
That happens because you've iterated for (i=0; i < 20; i++), which means once you left the for statement you were at i == 20. Your array was allocated with 20 positions, so you can access it from index 0 to 19. The awkward value you get is given because you are accessing "trash", or in other words, invalid positions with unpredictable (or almost) values.
The algorithm issue
Ok, once you got that index thing right, you still need an algorithm that displays the numbers that are lower than the average. You can't just copy your if statement into the loop because you only know the true average value once you've iterated through all of the values (which you are doing just fine).
So what you want is another loop that iterates throughout the array and that if statement inside of it (well, there are other ways to do it without running all of the values again, like sorting the array)
So, this is the algorithm I'll propose you
#include <stdio.h>
#include <stdlib.h>
#define array_size 20
void main()
{
int i;
int ray[array_size];
int sum=0;
float average;
for (i=0; i<array_size; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum += ray[i];
}
average=(sum/(float)array_size);
printf("Average = %.2f\n", average);
printf("The following values are less than the average: ");
for (i = 0; i < array_size; i++)
{
if (ray[i] < average)
{
printf("%d ", ray[i]);
}
}
system("pause");
}
This Part in Your Code:
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
//Now i = 20,that is why it left loop
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average) //You are saying if ray[20]<average
{
printf("The following values are less than the average: %d", ray[i]);
}
Now ray[20] is outside the scope because there are 20 elements and array index starts from 0 and goes on to 19, so ray[20] is out of bound access.
I highly recommend you to see this question for better understaning How dangerous is it to access an array out of bounds?.
Secondly You want to print all ray[i] where ray[i] < average so you should run a loop like
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i])
}
}
All That makes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i]);
}
}
system("pause");
}