scanf("%1c%2c %d %d %d %d %d %d %d %d %d %d",
&x, &y, &arr[0], &arr[1], &arr[2], &arr[3], &arr[4],
&arr[5], &arr[6], &arr[7], &arr[8], &arr[9]);
strcpy(string, x);
value1 = atoi(string);
strcpy(string, y);
value2 = atoi(string);
value_final = value1 + value2;
I'm trying to get the ascii values for the -l or -s then pass them through the switch with the ascii values added but I'm getting errors when I use atoi and I'm not sure as to if you are supposed to be adding the ascii values when the user enters the -l or -s or if their is another way to do this?
Your code has several problems:
Major: the switch cases do not have a break; clause. Control falls into the next clause and finally into the default statement.
Major: your show confusion between char arrays and single char variables: strcpy(string, x); should not even compile.
Your method for parsing -l or -s is very convoluted and probably erroneous. You should use character literals.
You do not need a double loop to find the smallest or the largest element in an array. A single loop suffices, and the printf statement should be outside the loop. max and min are uninitialized, the loops invoke undefined behavior.
the title says using atoi(): if this was your assignment, you should not use scanf().
Here is a simplified version:
int main(void) {
char option[3], buffer[32];
int i, min, max, value;
min = max = 0;
if (scanf("%2s", option) == 1) {
for (int i = 0; i < 10 && scanf("%31s", buffer) == 1; i++) {
value = atoi(buffer);
if (i == 0) {
min = max = value;
} else {
if (min > value)
min = value;
if (max < value)
max = value;
}
}
if (!strcmp(option, "-l")) {
printf("output: The largest number is %d\n", max);
return 0;
} else
if (!strcmp(option, "-s")) {
printf("output: The smallest number is %d\n", min);
return 0;
}
}
printf("You have entered an invalid option, try again next time.\n");
return 0;
}
Related
I have to create a function in c that one value and two pointers, verify if the value is a prime number or if it is a composite number, show the maximum and minimum divisors and return 1 for composite and 0 for prime. The problem is the minimum value is returned correctly but the maximum value returns something out of for loop restriction, for example:
n = 12
min is 2 max is 61
Why *max = i is returning a number bigger than the variable "value"?
Here is the code:
#include<stdio.h>
int divs(int value, int *max, int *min)
{
for (int i = 2; i < value; i++)
{
if (value % i == 0){
if (*max == 0){
*min = i;
}
*max = i;
}
}
if (*max != 0)
return 1;
else
return 0;
}
int main(void)
{
int n,max = 0,min = 0,result;
printf("type a number bigger than 2\n");
scanf("%d",&n);
divs(n,&max, &min);
result = divs(n,&max, &min);
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
return 0;
}
Your code is fine, you just left out a \n in your printf statement in main, change to this:
printf("min is: %d max is: %d\n",min,max);
Which caused your next printf ('1') to print right next to it.
You did not print a new line:
if (result == 1)
printf("min is: %d max is: %d",min,max);
printf("%d\n",result);
When result is 1, you first print min is: 2 max is: 6, and then you print 1.
Change the first part to:
if (result == 1)
printf("min is: %d max is: %d\n", min, max);
I'm experimenting with a simple C program that should prompt user to enter a chosen number of positive integers. I'm having an issue getting the maximum and minimum of the set of integers I input without the use of an array.
The way that I currently have it is that it will update the max and min among the last two entered values. If someone wouldn't mind looking to see what I'm doing wrong, it would be appreciated.
take a look here:
#include<stdio.h>
int main()
{
int N ,i, value=0, min=0, max=0, sum=0, oldmin=0, Newmin=0, oldmax=0, Newmax=0;
double mean;
do{
printf("How many values are to be entered?: ");
scanf("%d", &N);
printf("\n");
if (N>0){
do{
if (N>0){
// 1st value updated
for (i=1;i<=N;i++)
{
printf("Value %d:\n",i);
scanf("%d", &value);
sum = sum+value;
}
mean = (double)sum/(double)N;
//max
if(oldmax<Newmax){
max = Newmax;
}
else max = oldmax;
//min
if(oldmin>Newmin){
min = Newmin;
}
else min = oldmin;
}
else printf("INPUT ERROR!\n");
}
while(N<0);
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf.",min,max,mean);
}else printf("INPUT ERROR!\n");
} while(N<0);
return 0;}
some remarks :
you need to set the min/max value from value in the same loop you do sum = sum+value; , this is the reason of your problem about min/max
check the scanf result to be sure a number was enter
if (N>0){ do{ if (N>0){ so two check but N never change
if (N > 0) { do { ... } while (N<0); } that has no sense
the embedded loops have no sense, only 1 loop is needed
A proposal removing the problems :
#include<stdio.h>
int main()
{
int N;
fprintf(stderr, "How many values are to be entered?: ");
if ((scanf("%d", &N) != 1) || (N <= 0))
printf("INPUT ERROR!\n");
else {
int i, min, max, sum = 0;
for (i = 0; i < N; ++i) {
int value;
fprintf(stderr, "Value %d:\n",i);
if (scanf("%d", &value) != 1) {
printf("INPUT ERROR!\n");
return -1;
}
sum = sum+value;
if (i == 0) {
min = max = value;
}
else {
if (value < min)
min = value;
if (value > max)
max = value;
}
}
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf\n",
min,max, (double)sum/(double)N);
}
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi#raspberrypi:/tmp $ ./a.out
How many values are to be entered?: 3
Value 0:
1
Value 1:
2
Value 2:
3
The minimum value is 1, the maximum value is 3, and the average value is 2.00
I used fprintf to flush the message with a \n, and I set the first min and max value on the first turn to not have to use the MIN_INT MAX_INT may be not defined for you
if(oldmax<Newmax){
Don't compare newmax and oldmax. Compare max and value. Same with min.
I'm not even sure about the purpose of Newmax and oldmax. Remove these variables all-together, as it will just confuse you.
Just use min, max, and value. It will sort out.
I can't for the life of me figure out why C is ignoring my if statement.
I'm trying to skip all the procedures in the while statement when the input is -1000 (so that it doesn't print before exiting the program). Here is my code:
int main()
{
int count = 1;
int grade1;
int grade2;
double sum;
double average;
printf("Please input a number of grades: \n");
scanf("%d", &grade1);
printf("Sum is: %d.000000 \n", grade1);
printf("Average is: %d.000000 \n", grade1);
count++;
sum = grade1;
while(grade2 != -1000)
{
if(grade2 != -1000)
{
scanf("%d", &grade2);
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
return 0;
}
Here is a link to an image of my output. As you can see, even when grade2 is given -1000, the if statement is ignored, and another 2 lines are printed to the screen before the program exits. How can I fix this? Is this some sort of oddity of how C works?
When you do this the first time
while(grade2 != -1000)
the variable grade2 is uninitialized.
Consequently your code has undefined behavior
Make sure to initialize it like:
int grade2 = 0; // To zero or whatever you want
Further - always check the value returned by scanf. So instead of
scanf("%d", &grade1);
do
if (scanf("%d", &grade1) != 1)
{
// Add error handling here
}
Your next problem is that you don't scan grade2 before checking whether it is -1000. Move the scan before the if-statement.
Maybe what you want to do is:
int grade2 = 0;
while(grade2 != -1000)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 != -1000)
{
...
so that you scan for the first grade2 before you do the if(grade2 != -1000) and enters the calculation code
Written differently this could be:
while(1)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 == -1000) break; // Terminate the while
sum = sum + grade2;
....
While it's true that grade2 should be initialized and the return for scanf() should be checked, that's not the main problem the poster is running into. The problem is that he checks
if(grade2 != -1000)
AFTER he has already processed grade2. He should move
scanf("%d", &grade1);
before
if(grade2 != -1000)
The if statement in your while loop is redundant because, the loop will not iterate unless the condition that controls it is true, and the if statement comes directly after that, checking for the same condition, whilst grade2 is unchaged.
Instead, you need to move it to after the scanf() call because that will modify the variable grade2, and don't forget to initialize your variables before using them or else you'll have undefined behavior.
int main(void)
{
//....
int grade2 = 0; // initialized...
//....
while (grade2 != -1000)
{
scanf("%d", &grade2);
if (grade2 != -1000)
{
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
}
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)
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