I am creating a function to read in inputs from the user and put them into a floating point array of numbers with predetermined fix size of 25. It also returns the total amount of items that the user enters. However, for some reason this code will not terminate when I enter 999. I know it is something to do with that it is an int and input is a float, but I don't really know how to fix this (only been learning C for five days).
int readArray(float a[]){
//accepts inputs and puts items in a predefined array of size 25
int index = 0;
float input;
printf("Enter 25 or less elements for array (999 to finish):\n");
scanf("%d", &input); //accept initial response; priming prompt
printf("1st Prompt accepted");
while (input != 999 && index < 25) {
printf("In while loop");
a[index] = input;
index++;
scanf("%d", &input);
}
return (index);
}
The proper format specifier matters a lot here.For float it is %f.So change your scanf() to
scanf("%f", &input);
Related
For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}
I have an assignment and I was wondering why when I compile this code and run it, the scanf("%d", &temp_pin) doesn't store the data in an address. I know this because in the next statement of printf("%d", temp_pin) I'm just given random variables. I have another scanf statement in the earlier lines of code that work and I`m just stumped as to why this one doesn't. Many thanks!
#include <stdio.h>
int main()
{
//Deceleration of Variables
int option;
int pin [4]={1, 2, 3, 4};
int temp_pin [4];
int new_pin [4];
int temp_new_pin [4];
int correct;
int incorrect;
do
{
printf("Please enter which option you wish to operate\n\n");
printf("1. Enter your pin\n");
printf("2. Change your pin\n");
printf("3. Display the number of times the PIN was entered: \n Successfully\n Unsuccessfully\n");
printf("4. Exit Program\n\n");
scanf("%d", &option);
if (option == 1)
{
printf("\nPlease Enter Your PIN\n");
for (int i = 0; i < 4; i++)
{
scanf(" %d", &temp_pin);
printf(" %d", temp_pin);
if (temp_pin==pin)
{
printf("\nYour PIN is correct\n");
}
if (temp_pin != pin)
{
printf("\nYour PIN is incorrect\n");
}
}//End For
}//End If
} // end do
while(option != 4);
return 0;
}
If I could make one suggestion it would be changing all the integer arrays into integers. This would fix all of your problems. However, if your assignment requires the use of integer arrays please follow the code below.
Currently you are setting only the first element of temp_pin equal to the user input. The line scanf(" %d", &temp_pin); actually stores an integer into temp_pin[0].
Since the pin size is 4, you would need to read in 4 separate integers to store in the array. I would suggest using a for loop that can set the values of temp_pin[0], temp_pin[1], temp_pin[2], temp_pin[3]
Logically, I would also suggest error checking each integer, since an integer can be from size -32,768 to 32,767. Currently an integer array with the elements 3300,55,12,15 would be a valid pin.
The value you are given in this line printf(" %d", temp_pin); is not random variables. This is the address of temp pin. In order to print the values stored in temp_pin you would need to iterate through each element in the array and print it individually.
For your compare statement if (temp_pin==pin), this would never result in true since it is comparing addresses. Again the proper fix for this would be to iterate through both lists simultaneously and compare each element.
You have temp_pin declared as an array of integers, so &temp_pin is a pointer to an array and has type int (*)[4]. The %d format specifier expects an int *.
Similarly, when printing you pass the array temp_pin which decays to a pointer to the first element, and that address is what is being printed.
Change the type of temp_pin and the other variables declared as arrays to int and remove the loop.
int pin = 1234;
int temp_pin;
int new_pin;
int temp_new_pin;
...
if (option == 1)
{
printf("\nPlease Enter Your PIN\n");
scanf(" %d", &temp_pin);
printf(" %d", temp_pin);
if (temp_pin==pin)
{
printf("\nYour PIN is correct\n");
}
else
{
printf("\nYour PIN is incorrect\n");
}
}//End If
You attempt to read an array with one scanf call, but it does work like that in c. Note that temp_pin is already an address of the first element in the array.
The line
scanf("%d", temp_pin);
is equivalent to the line
scanf("%d", &(temp_pin[0]));
and it reads the value and stores it at temp_pin[0].
In order to read the whole array you'll need to do something like this:
for (int i=0; i<4; i++) scanf("%d", &(temp_pin[i]));
The same story with the comparison. You can't compare two arrays with one == operation. The expression temp_pin == pin compares the addresses which will always be different despite the actual values that are stored in those arrays. In order to compare two arrays you'll need to do something like this:
int isEqual = 1; // a flag for whether arrays are equal
for (int i=0; i<4; i++) {
if (temp_pin[i] != pin[i]) {
isEqual = 0;
}
}
if (isEqual) printf("pins are the same\n");
else printf("pins are not the same\n");
Im using online GeeksforGeeks for learning how to code. I just started learning but for some reason the compiler return garbage when the sum of my input exceeds 3616. Can any pro please explain to me why and how to improve my code?
Eg. input: 1 2 3 4 5 0 output:increasing order //sum of input< 3616
input: 1 2 3614 0 output:not increasing order //sum of input> 3616
This was the question:
Write a program check_order.c to read in a list of positive integers. The program is to continue asking for the next positive integer as long as the integers entered are in increasing order. The moment the input data are not in increasing order, or the input value is zero, the input ends. The program should then report whether the input data are in increasing order or not.
You may assume that at least one positive integer will be entered. If there is only one positive integer in the list, we will treat the list as it is in increasing order.
You may write all the code in the main() function.
#include <stdio.h>
int main(void){
int input, input2;
do{
input2 = input;
scanf("%d", &input);
printf("Enter positive integer: %d\n", input);
}
while(input> input2);
if(input< input2){
if(input == 0){
printf("Data are in increasing order.");
}
else{
printf("Data are not in increasing order.");
}
}
else{
printf("Data are in increasing order.");
}
return 0;
}
Resolved. thanks all!!! :)
When you don't initialize input it gets a garbage value. it can be positive or negative- and you can never know which value. To avoid that situation, you have to give an initialize value, so you can almost always be in fully control on your variables. It is alway recommended to set an initialize value to your variables.
#include <stdio.h>
int main() {
int input = 0, input2;
do {
input2 = input;
scanf("%d", &input);
printf("Enter positive integer: %d\n", input);
}
while(input > input2);
if (input < input2) {
if(input == 0) {
printf("Data are in increasing order.");
}
else {
printf("Data are not in increasing order.");
}
}
else {
printf("Data are in increasing order.");
}
return 0;
}
int main(){
char students_number[30], students_grade[30];
char *number, *value;
int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
float sum=0;
while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
{
printf("Please enter the number of students (It must be between 1-100): ");
scanf("%s",&students_number); // This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..
if(students<=100 && students>0)
{
for(i=1;i<=students;i++)
{
printf("Please enter %d. student's grade (in integer form):",i);
scanf("%s",&students_grade);// This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..
if(grade<0 || grade>100 || grade=='\0')
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
else if(grade<=60 && grade>=51)
d++;
else if(grade<=73 && grade>=61)
c++;
else if(grade<=85 && grade>=74)
b++;
else if(grade<=100 && grade>=86)
a++;
sum += grade;
}
}
sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..
printf("\nThe average result of the class is %.2f..\n",sum);
printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
}
else // This if command controls the number of students wheter was given right or not..
{
printf("Please enter a proper number of students.\n");
flag = 0;
}
}
return 0;
}
Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.
How can i make this correct?
You can use scanf to read a number and check that scanf done correctly its work:
from man scanf:
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...
for(i=1;i<=students;i++)
{
int ok;
printf("Please enter %d. student's grade (in integer form):",i);
/* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
if (NULL == fgets(students_grade, sizeof students_grade, stdin))
{
perror("fgets");
exit(1);
}
/* **try** to parse what have been read */
ok = sscanf(students_grade, "%d", &value);
/* check that scanf has done its work */
if (1 != ok)
{
printf("The grade of the student was given incorrect!\n");
i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
}
else
{
if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
f++;
/* ... */
}
I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.
I'm studying loops in class and for one of the labs, I have to figure out a way for the user to enter an unspecified number of integers to calculate the average. I know I can have the user enter the number of integers to be averaged in order for the loop to be terminated like below:
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
So basically I could have a user input the number of integers to be averaged in order for the loop to terminate, but there has to be another way to make the loop terminate without having the user input it?
Normally you'd use a predetermined "illegal" number like (say -1)
input = read_a_value();
while(input != -1)
{
// do something with input
input = read_a_value();
}
scanf returns the number of successful entries.
This may solve your issue.
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
A downfall is that the scanf will continue to prompt for input if a user presses the Enter Key repeatedly. In fact you might wish to replace the scanf with fgets. Have a look here.
If you are sure that the user doesn't enter too many numbers, use a string.
Length of string, you can choose according to you and split it using spaces to get the numbers