I wrote a code which is supposed to count how many active bits (1s) are in a binary number that it gets from the user, considering the input is a correct binary number.
every time the code supposed to run the scanf() in main() it just get stuck , it does not stops running, it just feels like its thinking indefinitly and does not give any error
this is the code i wrote which in this situation prints "Please enter a binaric number: " and then it will get stuck
#include <stdio.h>
void count_bits(long int UserNum){
int cnt=0;
while(UserNum>0)
{
if (UserNum%10==1)
{
cnt++;
}
}
printf("there are %d active bits\n",cnt);
}
int main(){
long int UserNum=0;
printf("Please enter a binaric number: ");
scanf("%ld" , &UserNum);
count_bits(UserNum);
return 1;
}
if i write the scanf() first like this it won't even print:
scanf("%ld" , &UserNum);
printf("Please enter a binaric number: ");
what am i doing wrong here?
edit:
examples
input: 1101100
output:there are 4 active bits
input: 0110100111
output:there are 6 active bits
basically count how many ones there are in the number
I assume you want to interpret the decimal number entered by the user as a binary number. Your code does not check if your input follows this convention. If you enter a number that contains digits other than 0 or 1, every digit that is not 1 will be interpreted as 0. (UserNum%10==1)
Because of this assumption I don't discuss the fact that you normally would have to test bits with UserNum % 2 or UserNum & 1. (If you want to know how to enter or print a binary number instead of a decimal number, ask a separate question.)
Note that you may easily run in overlow issues if you enter a number that has too many digits.
Main problem: You have an endless loop in function count_bits because you don't update UserNum.
You can change it like this:
void count_bits(long int UserNum){
int cnt=0;
while(UserNum>0)
{
if (UserNum%10==1)
{
cnt++;
}
UserNum /= 10;
}
printf("there are %d active bits\n",cnt);
}
With this change the code works for me as expected.
Please enter a binaric number: 0110100111
there are 6 active bits
Example of a number that is too big. (I added a line printf("You entered %ld\n", UserNum);.)
Please enter a binaric number: 10110111011110111110
You entered 9223372036854775807
there are 0 active bits
If you swap the printf and scanf in main (with the endless loop in count_bits), the message "Please enter a binaric number: " is not printed because it does not contain a newline and the output is line-buffered by default. Apparently scanf leads to flushing the output.
If you change it to print a trailing newline like
printf("Please enter a binaric number:\n");
it should get printed before entering count_bits (with the endless loop).
As pointed out in multiple comments UserNum>0 stays always true, and thereforethe loop never stops.
But anyway, the count_bits function is wrong alltogether. Doing modulo 10 operations for counting bits is pointless.
You want this:
void count_bits(long int UserNum) {
int cnt = 0;
while (UserNum > 0)
{
if (UserNum % 2) // if UserNum is odd, then bit no. 0 is 1
cnt++;
UserNum = UserNum / 2; // division by 2 shifts bits to the right
}
printf("there are %d active bits\n", cnt);
}
As we are working on a bit level, it would be more idiomatic to use bit shift and bit mask operartions though:
void count_bits(long int UserNum) {
int cnt = 0;
while (UserNum > 0)
{
if (UserNum & 1) // mask all bits but bit no. 0
cnt++;
UserNum = UserNum >> 1; // shift bits to the right
}
printf("there are %d active bits\n", cnt);
}
There is still room for improvement though. Especially negative numbers won't work properly (I didn't test though, find out yourself).
There are more sophisticated methods for counting bits such as described here: How to count the number of set bits in a 32-bit integer?
Related
I am trying to find each digit of a number entered by the user.
The length of the number is up to the user.
So far I have:
managed to limit what the user enters by using long long card, meaning they cannot enter more than about 18 or 19 characters and only numbers are accepted.
managed to get the first and last digit of that number, as well as the count of the number.
Now I wanted to:
specifically ask for no more than 16 digits max - > but it keeps saying undeclared identifier and am not sure where I go wrong
be able to identify each digit, i.e.:
53689
1st digit:5
2nd digit:3
3rd digit:6
etc.
I learned about modulus but I can't figure out how to tell it to stop at the 2nd last/3rd last digit.
I feel it's something really simple but how? especially if I don't know if the user enters 5 numbers or 15, otherwise I could say (repeat modulus x-1 times) or something like that.
Just for now, my code in case you see anything for #1.
Before I tried to limit the entry-conditions, it worked fine showing me card, card length and 1st,last digit.
#include <cs50.h>
#include <stdio.h>
//finding first 2 numbers and last number and checking what card type
int main(void)
{
int count = 0;
do
{
long long card = get_long_long("Enter your card number: ");
}
while (card ! = 0)
{
card = card / 10;
count++;
}
printf("Card number: %llu\n", card);
printf("Number of digits: %d \n", count);
firstdigit = card;
while (firstdigit >= 20)
{
firstdigit = firstdigit / 10;
}
printf("First digit = %d \n", firstdigit);
lastdigit = card % 10;
printf("Last digit= %d \n", lastdigit);
return 0;
}
info: Yes it is from CS50 credit, I can't understand the full exercise yet so I decided to take it apart and only learn how to write a program that analyses the number for first 2 digits and tells me what card type it is. To do so I'm trying to learn how to count every number on any given number length for practice, for me to actually understand this slowly, so please don't share a full answer to the credit problem.
I also haven't learned arrays or more complex solutions yet either.
As others have advised, "break the problem down into smaller pieces".
Here's an example of that approach. Instead of dealing with a massive number all at once, this 'segments' the number into the typical 4 sections embossed into a credit card. This might give you a start toward a solution...
int main() {
int count = 0;
long long card = get_long_long("Enter your card number: ");
long long cpy = card;
int blk4 = cpy % 10000; // 4 rightmost digits as int
cpy = cpy / 10000; // shift right
int blk3 = cpy % 10000; // next 4 digits as int
cpy = cpy / 10000; // shift right
int blk2 = cpy % 10000; // next 4 digits as int
cpy = cpy / 10000; // shift right
int blk1 = cpy % 10000; // leftmost 3-4 digits as int
printf( "Card number: %04d %04d %04d %04d\n", blk1, blk2, blk3, blk4 );
return 0;
}
Having shown that, please be advised that a credit card "number" is not a "number" in the usual sense. It is a string made-up only of digits. Trying to solve this CV50 problem with "integers" is going to lead to tears. It's time to learn about arrays of characters (even if every character is an ASCII digit)...
I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.
Problem:
You are provided an array A of size N that contains non-negative integers. Your task is to determine whether the number that is formed by selecting the last digit of all the N numbers is divisible by 10.
Note: View the sample explanation section for more clarification.
Input format
First line: A single integer N denoting the size of array Ai.
Second line: N space-separated integers.
Output format:
If the number is divisible by 10 , then print Yes . Otherwise, print No.
Constraints:
1<=N<=100000
0<=A[i]<=100000
i have used int, long int ,long long int as well for declaring N and 'm'.But the answer was again partially accepted.
#include <stdio.h>
int main() {
long long int N,m,i;
scanf("%ld", &N);
long data[N];
for(auto i=0; i<N; i++) {
scanf("%ld", &data[i]);
}
// write your code here
// ans =
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
if(m%10!=0 && m==0) {
printf("Yes");}
else{
printf("No");
}
return 0;
}
Try making a test suite, that is, several tests for which you know the answer. Run your program on each of the tests; compare the result with the correct answer.
When making your tests, try to hit also corner cases. What do I mean by corner cases? You have them in your problem statement:
1<=N<=100000
0<=A[i]<=100000
You should have at least one test with minimal and maximal N - you should test whether your program works for these extremes.
You should also have at least one test with minimal and maximal A[i].
Since each of them can be different, try varying them - make sure your program works on the case where some of the A[i] are large and some are small.
For each category, include tests for which the answer is Yes and No - to exclude the case where your algorithm always outputs e.g. Yes by mistake.
In general, you should try to make tests which challenge your program - try to prove that it has a bug, even if you believe it's correct.
This code overflows:
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
For example, when N is 1000, and each of the input items A[i] (scanned into data[i]) ends in 9, this attempts to compute m = 99999…99999, which grossly overflows the capability of the long long m.
To determine whether the numeral formed by concatenating a sequence of digits is divisible by ten, you merely need to know whether the last digit is zero. The number is divisible by ten iff data[N-1] % 10 == 0. You do not even need to store these numbers in an array; simply use scanf to read but ignore N−1 numerals (e.g., scanf("%*d")), then read the last one and examine its last digit.
Also scanf("%ld", &N); wrongly uses %ld for the long long int N. It should be %lld, or N should be long int.
An integer number given in decimal is divisible by ten if, and only if, its least significant digit is zero.
If this expression from your problem:
the number that is formed by selecting the last digit of all the N numbers
means:
a number, whose decimal representation comes from concatenating the least significant digits of all input numbers
then the last (the least significant) digit of your number is the last digit of the last input number. And that digit being zero is equivalent to that last number being divisible by 10.
So all you need to do is read and ignore all input data except the last number, then test the last number for divisibility by 10:
#include <stdio.h>
int main() {
long N, i, data;
scanf("%ld", &N);
for(i=0; i<N; i++)
scanf("%ld", &data); // scan all input data
// the last input number remains in data
if(data % 10 == 0) // test the last number
printf("Yes");
else
printf("No");
return 0;
}
The title is kinda lame, but here's the explanation:
I want to check if the user input (integer) is in this form --> N = 4k + 1 (number 1, 5, 9, 13 and so on) and if the input isn't one of those numbers, I want keep asking the user to input the number until it's right.
I tried to do it like this:
I made a loop that checks if N-1 can be divided by 2, and if yes, that's my N. BUT, of course, it doesn't work. N-1 is supposed to be an even number (if the correct N is entered) so is there a way to check that somehow, and if it's not right to keep looping the "enter a number" part?
int N, k;
printf("Enter a number: ");
scanf("%d", &N)
k=(N-1);
/* checking */
while (k%2 != 0)
{
printf("Enter a number: ");
scanf("%d", &N);
}
The problem with this code is that when you enter the right number, it works fine, BUT when you input a wrong number, and afterwards the right number, it keeps looping the "Enter a number" part. How to fix this?
Put both the prompt and the check inside the same loop.
#include <stdio.h>
#include <stdlib.h>
int main (int args, char** argv) {
int N, k;
k = 1; // this is here just to get the loop going,
while (k%2 != 0) {
printf("Enter a number: ");
scanf("%d", &N);
k=(N-1);
}
return 0;
}
I'd like to point out, however, that your test is incorrect; half of all numbers that are divisible by 2 will not be correct answers to the task as-stated. I've only fixed the looping; not the logic. (There are several fine comments about fixing the math; take note of them.)
I've added a note about the purpose of the k = 1; line. As noted, it's there to prevent the while() loop from immediately exiting. I think you were hung up on calculating k from N, which is what you want to do in general, but you can supply a "fake" k so that k can serve as the loop condition before any input has been provided.
Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", ¤tNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}