i'm learning C.
i'm using ubuntu and have Code::Blocks as IDE
i have this code:
#include <stdio.h>
int rev (int num);
int main (){
int numb = 0;
printf("%d\n\n", numb);
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
printf("there?");
printf("%d\n", numb);
while (numb != 9999){
printf("The reversed number is %d\n", rev(numb));
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
} /* end of while */
}
int rev (int num){
printf("here?");
int total = 0;
long max = 10;
long max_const = 10;
printf("here");
for (max; max < num; max *= 10);
printf("%ld", max);
max_const = max;
for (int i = 0; i <= max_const; i *= 10, max /= 10){
total += num / max * i;
} /* end for */
return total;
}
I'm doing it in this way cause my book isn't clear...however, the problem is that it raise a Floating Point exception, in scanf...i'm typing normal numbers... the strange thing is that if i type everything but 9999, the program crash. if i type 9999, it prints 'there?' (so scanf it's ok) and stop later, obviously. why?
Thank you.
The two existing (be sure to return the result in rev, and put \n on the ends of printfs to be sure they make it through the buffer) answers are good points, but not the thing that's actually triggering your floating point exception. Try running it in a debugger, and you'll see that your algorithm is bad: eventually max becomes zero and you divide by it. I'll leave fixing that as an exercise for the reader; the problem isn't anything to do with scanf.
Your rev function needs to return the reversed number.
Related
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
The Code is supposed to make change for a dollar and works fine. but the professor says that he will be enter random numbers along with letters. It works fine with numbers but when a letter is entered an infinite loop will occur any suggestions?
#include <stdio.h>
#include <stdlib.h>
#define amtPaid 1
#define SENTINAL -1
int quarters(int numChange);
int dimes(int numChange);
int nickels(int numChange);
int pennies(int numChange);
int main(void)
{
double amtDue = 0; // how much is paid
while(1){
printf("\nPlease enter the price less than 1 dollar: ");
scanf(" %lg", &amtDue);
int changeReturn = (amtPaid - amtDue) * 100 + 0.5; // convert decimal to whole number
int updated = 0; // remaining change after amt of change
int numberQuarters = quarters(changeReturn); // number of quarters needed
if(changeReturn >= 0 && changeReturn <= 100){ // if changereturn is between 0 and 100 execute code
printf("\nNice!");
printf("\nWe owe you %i cents" , changeReturn);
if(numberQuarters >= 0){ // get and print number of quarters
printf("\nQuarters: %i", numberQuarters);
updated = changeReturn % 25;
}
if(dimes(updated) >= 0){ // get and print number of dimes
printf("\nDimes: %i", dimes(updated));
updated = updated % 10;
}
if(nickels(updated)>= 0){ // get and print number of nickels
printf("\nNickels: %i", nickels(updated));
updated = updated % 5;
}
if(pennies(updated) >= 0){ // get and print number pennies
printf("\nPennies: %i", pennies(updated));
}
}
else if(amtDue == SENTINAL){
break;
}
else {
printf("That does not make sense to me. please type a valid number");
}
printf("\n %g", amtDue);
}
return 0;
}
int quarters(int numChange){
int numQuarters = 0;
numQuarters = numChange / 25;
return numQuarters;
}
int dimes(int numChange){
int numDimes = 0;
numDimes = numChange / 10;
return numDimes;
}
int nickels(numChange){
int numNickels = 0;
numNickels = numChange / 5;
return numNickels;
}
int pennies(numChange){
return numChange;
}
In case an inappropriate value is supplied other than the expected value of the format specifier with scanf(), the scanf() will fail and the inappropriate value will remain in the input buffer, providing the feed to next scanf(), only to cause successive failures. In that case, you need to clean up the input buffer before going for next input. You can use something like
check the return value of scanf()
In case of failure, use while( getchar() != '\n' ); to clean the input buffer.
That said, int nickels(numChange) is now invalid in c (C99 onwards). You have to make it as int explicitly.
Instead of using scanf(" %lg", &amtDue);, get the user input as a string, so you can do proper checking.
char input[500];
fgets(input, 500, stdin);
// do some input checking
double val = atof(input);
// do calculations on the number
To check, there's all kinds of functions to help you in ctype.h, one that you might find interesting is isalpha.
Manual References:
fgets
atof converts string to double
atoi converts string to integer
isalpha
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;
}
Im writing a C program that is supposed to add every number until it hits a sentinel value. Then average it all together.
Im not sure where the problem is but I think it might be that num never actually changes. Any help is appreciated.
#include <stdio.h>
int sentinal = 9999;
int iterations = 0;
int total = 0;
int average;
int num;
int main(void){
do{
printf("Enter a number to add:\n");
scanf("%d\n", num);
total = total + num;
iterations++;
}while (num != sentinal);
average = total/iterations;
printf("%d\n", average;
return 0;
}
Running version
#include <stdio.h>
int main(){
int sentinel = 9999;
int iterations = 0;
int total = 0;
float average;
int num;
while(1){
printf("\nEnter a number to add: ");
scanf("%d", &num);
if (num == sentinel){
break;
}else{
total = total + num;
iterations++;}
}
average = (float) total/iterations;
printf("%f\n", average;
return 0;
}
Your problem is in the line:
scanf("%d\n", num);
scanf requires a memory address of the variable where should put the value the was read. This is done using the operator &. Your code should be:
scanf("%d\n", &num);
scanf() takes a pointer to the value parsed from standard input. You're passing the actual value, not the pointer to the value.
There are many tools in Linux to find out Segmentation and other compilers as well. If you want to really debug where your code is popping segmentation fault , you can use GDB and valgrind .It exactly gives you where you have error in your code .
Provide address i.e. & when storing value using scanf.
Declare average as float, and while calculating average use average = (float) total / iterations and use %f while printing average.
Check your printf when you are printing average, closing bracket is missing.
I have a problem with this code.... The project should show me repeated number in the input number. For example:
$ ./a.out
Enter a number: 9893746595
Repeated: 9 5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a[10], b[10] ;
int n,t;
printf("Enter a number: ");
for(n=0; n<10;n++)
{
scanf("%d", &a[n]);
n=t;
a[n]=b[t];
}
for(n=0;n<10;n++)
{
for(t=n;t<10;t++)
{
if(a[n]=b[t])
printf("%d", a[n]);
}
}
return 0;
}
if(a[n]=b[t]) assigns b[t] to a[n].
You most likely wanted to use if(a[n] == b[t]) to compare those values.
It's a good idea to compile using the -Wall -Wextra -Werror flags so all warnings are enabled and treated like errors (so you can't simply ignore them). With those flags the compiler will yell at you for doing an accidental assignment.
Your code is bogus. ;-)
The usual approach here is to create an array of 10 ints, one for each digit, and count the occurrences of each digit in the user-supplied number.
There's an idiomatic technique to get the digits of a number num one at a time: use num % 10 to get the last digit, and num / 10 to get the number without its last digit. Then your program might look something like this:
int dcount[10] = {0}; // 10 ints, all initialized to 0
scanf("%d", &num);
while(num) {
dcount[num % 10]++; // increment dcount[i], where i is the last digit of num
num /= 10; // "remove" last digit from num
}
for (int i = 0; i < sizeof(dcount)/sizeof(dcount[0]); i++)
printf("%d occured %d times\n", i, dcount[i]);
I didn't test the above code, so there may be some minor flaws. The general principle should be clear, though.
Hope that helps.
Your code assigns t to n before t has been initialized.
This is bound to cause problems. I haven't fully studied the rest of your code but you should start by initializing t before using it. If that still doesn't work, provide information such as what it does or doesn't do.
You might want to look at the first for loop. t is read from without ever being written to. Same for b. And, you are overwriting the just read in variable a[n] with b[t]. In the conditional for if, you meant == where = is written.
If you turn on every option in your compiler to emit warnings and strictly check for standard language compliance, it would have caught these.
int main()
{
int i, number, digitCount[10];
// Before starting, set the digit count for each digit to 0
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
// Store the entire number in one int
printf("Enter a number: ");
scanf("%d", &number);
// Find the remainder of number / 10 in order to get the last digit
// Divide number by 10 in order to remove that digit
// Continue to peel off digits until you reach zero
while (number != 0)
{
digitCount[number % 10]++;
number /= 10;
}
// For each digit which is counted more than once, print it
printf("Repeated: ");
for (i = 0; i < 10; i++)
{
if (digitCount[i] > 1)
{
printf("%d ", digitCount[i]);
}
}
return 0;
}