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;
}
Related
I'm a student, and my task is "An integer X is given, find the maximum of the numbers included in its composition." For example X is 786534, so maximum number is "8". The task have to be done with function on c. I make some notes but it doesn't work correctly. There are two functions.
First function is for input number a check it for right size.
The second is for the calculating the max digit.
I have a problem with calling the function.
What is my mistake?
#include <conio.h>
#include <stdio.h>
#define MAX_N 999999999999
int inputNumber()
{
int number;
printf("Input number:\n");
scanf_s("%d", &number);
while (number = 0 && number > MAX_N)
{
// Number is not equal 0
printf("Repeat input:\n");
scanf_s("%d", &number);
}
return number;
}
int findMax(int number)
{
int max_number; //intermediate variable
int a = number;
max_number = a % 10;
a = a / 10;
while (a > 0)
{
if (a % 10 > max_number)
max_number = a % 10;
a = a / 10;
}
return max_number;
}
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
Okay, let's look at this:
int main()
{
inputNumber();
findMax();
printf("The maimum number is %d\n", max_number);
_getch();
return 0;
}
inputNumber returns an int, but you don't store it somewhere. So this might work better for you:
int number = inputNumber();
findMax expects an argument, so this might work better:
int max_number = findMax(number);
That should get you further.
You need to save the return value of inputNumber() to a variable and pass that as the parameter to findMax(); variables such as "max_number" are limited by function scope.
I hope this helps!
Basically I'm just trying to sort all user input numbers by positive or negative. So far I'm just trying to create an array of only positive integers, but can't seem to get it right.
Been stuck on this for a while and can't quite understand why my program is allocating negative integers to my array that's supposed to be for positive integers only, despite my if statements instructing otherwise. Any input would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
int main() {
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
int positive_total = 0, negative_total = 0;
int negative_elements[20];
int positive_elements[20];
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
for (i=0; i<num_of_elements; i++) {
printf("\nEnter element a%d. \n:", i+1);
scanf("%d", &elements[i]);
}
for (j=0; j<num_of_elements; j++)
{
if (elements[j] > 0)
{
positive_elements[positive_total] = elements[j];
positive_total++;
} else if (elements[j] < 0) {
negative_elements[negative_total] = elements[j];
negative_total++;
}
}
int num;
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
int MAX_pos_element = 0;
for (x=0; x<=positive_total; x++) {
if (MAX_pos_element < positive_elements[x]) {
MAX_pos_element = positive_elements[x];
printf("\n%d is larger than %d", MAX_pos_element, positive_elements[x]);
printf("\nelement[%d] has the largest value: %d", x, MAX_pos_element);
}
}
return 0;
}
With:
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
you are allocating an array of zero length because num_of_elements is still zero.
Use the following:
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Now num_of_elements is initialized.
(Note: you should also check the return value of scanf to be sure a number was read.)
The program is initially invalid and has undefined behavior.
You may not declare a variable length array with zero number of elements as you are doing
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
You should declare the array after you entered a positive value of the variable num_of_elements.
For example
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Also in loops like this
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
you have to use the condition num < positive_total instead of num <= positive_total.
The program "reads" non negative integers and fills an array of MAX size 100 until it is filled or the user gives -1.Then, function range finds the min and max values and "sends" them to the program.For example,if the user gives 67 54 78 85 -1 the range of values is 54-85.
Problem is, main doesn't print the range. Instead, it prints: "The range of values is 2 - 24576000"
#include <stdio.h>
#include "simpio.h"
int read_data(int A[]);
void range(int sum,int A[100], int *r1, int *r2);
int main()
{
int A[100], sum, max, min,i;
int *r1,*r2;
r1 = &max;
r2 = &min;
printf("Enter the elements of the array, one per line.\n");
printf("Use -1 to signal the end of the list.\n");
sum=read_data(A);
range(sum,A, &max, &min);
printf("The number of elements is: %d\n",sum);
printf("The range of values is %d - %d",min ,max);
}
int read_data(int A[])
{
int i,sum,value;
sum=value=i=0;
while ( i<100 && value !=-1)
{
printf("? ");
value = GetInteger();
if (value != -1)
{
A[i] = value;
value = A[i];
sum+=1;
}
i++;
}
return sum;
}
void range(int sum,int A[100], int *r1, int *r2)
{
int i,max,min;
max =0;
min = 32767;
*r1 = min;
*r2 = max;
for(i=0;i<sum;i++)
{
if (A[i]!=-1)
{
if (A[i]>max)
max = A[i];
if (A[i]<min)
min = A[i];
}
}
*r1 = max;
*r2 = min;
}
One of the problems is that you are not incrementing the value of i in function read_data.
The other problem is that the 4th printf
printf("%The number of elements is: %d\n",sum);
in the function main has a "%T" which is considered by the printf function to be a format specifier(like the one you use for the integer "%d"). If you really want to write % there you should use the format
printf("%%The number of elements is: %d\n",sum);
and it will print only one %.
If you would like to know more about the format specifiers accepted by printf http://www.cplusplus.com/reference/cstdio/printf/ .
I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
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