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;
}
Related
Here's my code:
#include <stdio.h>
#include <ctype.h>
main(){
float input;
printf("Input: ");
scanf("%f", &input);
if (isalpha(input) || (input) < 0)){
printf("Input is an alphabet or is lesser than 0");
} else {
printf("Input is correct. %f is a number larger than 0", input);
}
}
I want the code to detect if input is a number larger than 0, or is it an alphabet. However, I am getting this error:
8: error: identifier expected
What does it mean to my code's execution? How am I supposed to run the code successfully?
Correct parentheses in if:
if ( isalpha(input) || (input < 0) )
In addition, you need to check the return value of scanf() whether there was input or not. In the case of no input, the return value would be 0 or in case of multiple inputs how many succeeded. In your case, you can use the return value to determine whether a float was input or not.
The main() should return an int and always initialize your variables.
Example (live):
#include <stdio.h>
#include <ctype.h>
int main()
{
float input = 0.0f;
printf("Input: ");
int ret = scanf("%f", &input);
if ( ret == 0 )
{
printf("ERROR: Input is NOT a float!\n");
return -1;
}
if ( input < 0.0f )
{
printf("Input is less than 0");
}
else
{
printf("Input is correct. %f is a number larger than 0", input);
}
return 0;
}
Your parentheses aren't opened/closed properly.
Maybe your ide/compiler is taking care of it, but it should be int main()
isalpha() will behave unexpectedly with float values. Try avoiding that.
First of all you are missing int declaring main,
int main()
Also,you have excessive bracket in line
if (isalpha(input) || (input) < 0)){
Scanf uses %f to read floats. What your program will do is accept any ascii character and I suppose that wasn't your intention.
I am still not sure what you need, but you could try something like this as a starting point. It does not handle all possible inputs, and will erroneously classify an input such as #42 as alphabet or lesser than 0, which is questionable, but you can iterate on this and hopefully get to a more polished version.
#include <stdio.h>
#include <ctype.h>
int main(){
float input;
printf("Input: ");
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
} else {
printf("Input is an alphabet or is lesser than 0");
}
}
Explanation
We save the value in input, if compatible with the %f format:
float input;
Prompt for the user:
printf("Input: ");
This condition is made of two parts; the first part is the scanf, that will try to read input, and if successful will evaluate to 1, which is true, so the second part input >= 0 will be evaluated, and if input is indeed >= 0 we print the first message.
if (scanf("%f", &input) && input >= 0){
printf("Input is correct. %f is a number larger than 0", input);
Else we print the second message.
} else {
printf("Input is an alphabet or is lesser than 0");
}
I am trying to work with binary numbers AND logical operator without using &. When I entered the example 1111 and 1000, a floating point exception (core dumped) occurred. I am waiting this code same length two binary numbers and after print for example print:1001 and 1111 = 1001
#include<stdio.h>
int length(int a,int b);
int andop(int a,int b);
int main(){
int first,sec;
do{
printf("First integer: ");
scanf("%d",&first);
printf("\nSecond integer: ");
scanf("%d",&sec);}
while(andop(first,sec)==0);
printf("\n%d AND %d= %d",first,sec,andop(first,sec));
return 0;
}
int andop(int a,int b){
int a_1,b_1;
int result=0;
a_1=a;
b_1=b;
while(a_1>1){/*Checking if first is binary or not,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (a_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
a_1=a_1/10;
}
while(b_1>1){/*Checking if first is binary ,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (b_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
b_1=b_1/10;
}
while (length(a,b)>0){
result=result+(a%10)*(b%10);
a=a/10;
b=b/10;
if(length(a,b) == 0){
break;
}
result=result*10;
}
return result;
}
int length(int a,int b){
if(a == 0 || b == 0){
return 0;
}
int temp_a,temp_b;
int length_a=0,length_b=0;
temp_a=a;/*i assign the number into the temporary variable _a and _b*/
temp_b=b;
while(temp_a>0){//checking how many digit a is
temp_a=temp_a/10;
length_a++;
}
while(temp_b>0){//checking how many digit b is
temp_b=temp_b/10;
length_b++;
}
if(length_!=length_b){/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
return length_a;
}
The following code is the source of the problem:
while(length_a/length_b!=1){/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
You are using a very strange way to test if two variables (length_a and length_b) are the same! Further, if length_b is zero (as it appears to be, at some stage), then the division will cause the error.
You can just use a simple comparison of the two variables:
if (length_a != length_b) {/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
EDIT: There are a number of other errors in your code but the suggestion I have given will address the specific error you have asked about.
In your program, the floating point exception occurs because of division by zero in function length.
You should check if a or b is 0 before doing anything in length().
Try adding this at the start of length
if(a == 0 || b == 0)
return 0;
Also, check if length() returns 0 before multiplying result by 10 in andop
i.e. change length(a, b) to
if(length(a, b) == 0)
break;
Even after this, your program will print the result in reverse order, so you will have to print the result in reverse order. Try creating a function for that.
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 have an assignment which required me to sort any random numbers. The code below is weird. The reason is after clicking running the program, if I type 5 at the beginning, it does not work perfectly, however, it works correctly with other numbers. Please help me to fix this error. I also attached the pictures to prove what I said above.
Image when enter number 5
Image when enter number 10
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany-1 ;i++){
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany-1;i++){
printf("The sorted number: %d\n",number[i]);
}
}
The issue is because you are reading and printing one less than the actual size of the array. So the last entry of the array will have some junk value which you don't know. But while sorting you are using it and it gets sorted. Sometimes the junk value is lower than the other random values and it gets printed.
I have made the fix. Please check all the for loops.
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany ;i++){ //Read howmany values and print
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany;i++){ //Print howmany values
printf("The sorted number: %d\n",number[i]);
}
}
My program prompts the user for two positive integers to compute their GCD. From the scanner, the program does not accept any input that is not a positive integer and instead prompts the user again.
Most of my code already works correctly. My issue is that my program takes two negative integer inputs before asking for another positive integer. Other characters work just fine. Any tips to solve this minor issue?
Source code
#include <stdio.h>
#include <stdlib.h>
int main() {
int temp1, temp2, A, B, C;
char str[256];
while(1){
printf("Enter a positive integer: ");
while(scanf(" %d", &A)!=1 || A <= 0) {
scanf(" %s", str);
printf("Please enter a positive integer: ");
}
if(A > 0){
break;
}
}
//same loop to get B
//compute GCD of A and B
//print out answer
return 0;
}
Sample Output
Enter a positive integer: -5
-6
Please enter a positive integer: -7
-8
Please enter a positive integer: k
Please enter a positive integer: s
Please enter a positive integer: d
Please enter a positive integer: 5
Your program wants to read something because you told so.
Try this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int temp1, temp2, scanf_ret, A, B, C;
while(1){
printf("Enter a positive integer: ");
while((scanf_ret=scanf(" %d", &A))!=1 || A <= 0) {
if(scanf_ret<0) {
puts("got unexpected EOF");
return 1;
}
if(scanf_ret==0)scanf(" %*s");
printf("Please enter a positive integer: ");
}
if(A > 0){
break;
}
}
//same loop to get B
//compute GCD of A and B
//print out answer
return 0;
}
In this code,
If scanf_ret is 1, it means the read was successful and there is no need to consume garbage.
If scanf_ret is 0, it means there are some obstacles that cannot be read as integer, so remove them.
If scanf_ret is negative, it means it is the end of input, so exit program.
Also note that you are not to store the garbage, so buffer overrun can be avoided.