I am learning c language and i am confused about the code below. its a recursion but how come when i run this code, it won't run until i provided 2 different inputs but system only execute the first?
Thanks in advance.
#include <stdio.h>
long factor (float user_input)
{
if(user_input <=1)
return 1;
else
return (user_input * factor (user_input - 1));
}
int main ()
{
int user_input;
long factorial_calculation;
printf("what factorial number would you like to calculate?\n");
scanf("%d\n", &user_calculation);
factorial_calculation = factor (user_input);
printf("ld\n", factorial_calculation);
return 0;
}
Your user_input is int but you are passing variable as a float and running your factorial function on it. Factorials are undefined for non-integer nos, so you are better off using int.
In:
printf("ld\n", factorial_calculation);
ld is an invalid format specifer.
In
scanf("%d\n", &user_calculation);
I think you meant
scanf("%d", &user_input);
The following code works:
#include <stdio.h>
int factor (int user_input)
{
if(user_input <=1)
return 1;
else
return (user_input * factor (user_input - 1));
}
int main ()
{
int user_input;
long factorial_calculation;
printf("what factorial number would you like to calculate?\n");
scanf("%d", &user_input);
printf("%d\n",user_input);
factorial_calculation = factor (user_input);
printf("%d\n", factorial_calculation);
return 0;
}
scanf() is notoriously difficult to synchronize with user input. Instead, use fgets() and inspect the string for a number (or numbers if more than one is expected per line).
long factorial_calculation;
char buf [1000];
for (;;)
{
printf("What factorial number would you like to calculate?\n");
if (!fgets (buf, sizeof buf, stdin)) /* probably EOF, hangup, etc.: just exit */
return 0;
if (1 != sscanf(buf, "%ld", &user_calculation))
{
printf ("No number entered, please try again\n");
continue;
}
factorial_calculation = factor (user_input);
}
Related
#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.
I need help with error checking for my program. I'm asking the user to input a integer and I would like to check if the users input is a integer. If not, repeat the scanf.
My code:
int main(void){
int number1, number2;
int sum;
//asks user for integers to add
printf("Please enter the first integer to add.");
scanf("%d",&number1);
printf("Please enter the second integer to add.");
scanf("%d",&number2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0){
printf("The sum of these two integers is a multiple of 3!\n");
}else {
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
scanf returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2); returns 1. The trick, however, is to ignore invalid data when scanf returns zero, so the code would look like this:
while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}
Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main to avoid duplication.
Here is a solution of your problem. I just modified some of your code.
Read comments for any explanations.
#include<stdio.h>
#include<stdlib.h> //included to use atoi()
#include<ctype.h> //included to use isalpha()
#define LEN 3 //for two digit numbers
int main(void)
{
char *num1=malloc(LEN);
char *num2=malloc(LEN);
int i,flag=0;
int number1,number2;
int sum;
do
{
printf("Please enter the first integer to add = ");
scanf("%s",num1);
for (i=0; i<LEN; i++) //check for every letter of num1
{
if (isalpha(num1[i])) //isalpha(num1[i]) returns true if num1[i] is alphabet
{ //isalpha() is defined in ctype.h
flag=1; //set flag to 1 if num1[i] is a alphabet
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
do
{
printf("Please enter the second integer to add = ");
scanf("%s",num2);
for (i=0; i<LEN; i++)
{
if (isalpha(num2[i]))
{
flag=1;
}
}
if(flag)
{
printf("Not a valid Integer\n");
flag=0;
continue;
}
else
{
break;
}
} while(1);
//strings to integers
number1= atoi(num1); //atoi() is defined in stdlib.h
number2= atoi(num2);
//adds integers
sum = number1 + number2;
//prints sum
printf("Sum of %d and %d = %d \n",number1, number2, sum);
//checks if sum is divisable by 3
if(sum%3 == 0)
{
printf("The sum of these two integers is a multiple of 3!\n");
}
else
{
printf("The sum of these two integers is not a multiple of 3...\n");
}
return 0;
}
I designed this for only two digit numbers, but it is working fine for more than two digit numbers for me.
Please let me know that same is happening in your case.
And if you will find why this is happening please comment.
And you can also use strtol() instead of atoi(). I am not using it because of small values.
Difference between atoi() and strtol()
atoi()
Pro: Simple.
Pro: Convert to an int.
Pro: In the C standard library.
Pro: Fast.
Con: No error handling.
Con: Handle neither hexadecimal nor octal.
strtol()
Pro: Simple.
Pro: In the C standard library.
Pro: Good error handling.
Pro: Fast.
Con: Convert to a long, not int which may differ in size.
I would like to say that you have to make some custom validation to check if whether scanf read integer or not.I am used fgets not interested in scanf.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) ) return 1;
return 0;
}
int main ( void )
{
int i;
char buffer[BUFSIZ];
printf ( "Enter a number: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
buffer[strlen ( buffer ) - 1] = '\0';
if ( validate ( buffer ) == 0 ) {
i = atoi ( buffer );
printf ( "%d\n", i );
}
else
printf ( "Error: Input validation\n" );
}
else
printf ( "Error reading input\n" );
return 0;
}
A clean approach to this problem can be
read from stdin using fgets().
use strtol() to convert and store the value into an int. Then check for the char **endptr to determine whether the conversion is success [indicates integer] or not.
Perform remaining task.
So here is my code. Its a school assignment. I had to make a program to calculate the square root of a number using a method the Babylonians developed etc, that's not the important part. What I was wondering is if it's possible to ignore letters in my scanf so that when I input a letter it doesn't go berserk in my terminal. Any help is welcome and greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double root_Approach(double s); // defines the two functions
void ask_Number(void);
int main() {
ask_Number(); // calls function ask_Number
printf("\n\n");
system("pause");
return 0;
}
double root_Approach(double s) {
double approach;
approach = s;
printf("%.2lf\n", s); // prints initial value of the number
while (approach != sqrt(s)) { // keeps doing iteration of this algorithm until the root is deterimened
approach = (approach + (s / approach)) * 0.5;
printf("%lf\n", approach);
}
printf("The squareroot of %.2lf is %.2lf\n",s, sqrt(s)); // prints the root using the sqrt command, for double checking purposes
return approach;
}
void ask_Number(void) {
double number;
while (1) {
printf("Input a number greater than or equal to 0: "); // asks for a number
scanf_s("%lf", &number); // scans a number
if (number < 0) {
printf("That number was less than 0!!!!!!\n");
}
else {
break;
}
}
root_Approach(number);
}
Scanf reads whatever may be the input from the terminal (character or integer)
One way you can do is to check the return statement of scanf whether the read input is integer or not an integer.
Here is the sample code
int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");
`
this link may be helpful
Check if a value from scanf is a number?
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}