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;
}
Related
Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...
I want to print a sequence of 1 4 9 16 25...n by inputting any number which is equal to the number of terms I want as an output.
For example: if I input 4, it should print 1 4 9 16
but I can't seem to get the result I want using this program I have made. The result goes like 0 1 4 9. I want to eliminate the first term zero, Can someone pls help me see what's wrong with my program?
int result,n;
for (int i = 1; i <= n; i++){
scanf("%d", &n);
printf("%d ", result);
result = pow(i,2);
}
#include <stdio.h>
int main()
{
int result, i, n;
printf("Input n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
result = i*i;
printf("%-3d", result);
}
}
OUTPUT: 1 4 9 16... n^2
Probably, you want this.
You should scan the value of n before the loop. Otherwise, the behavior of your program would be unpredictable. Second, it is wise to avoid floating-point calculations when possible and here you want to print the series of square of integers. i.e. 1,4,9,... so you shouldn't use
double pow(double a, double b)
function. Also as Fred said, "Calculate result before you print it."
How to make a program to read elements from input like:
1 3
and give me the summation of that:
4
#include <stdio.h>
int main(void){
char x[3];
scanf(" %c",&x);
printf("%d\n",x[0]+x[2]);
}
In your approach you seem to read in a string and treat several positions of that string as numbers. Besides the fact that there are several mistakes in implementing this approach, the main thing actually is that you've taken the wrong approach. Drawbacks (not all, just some) are: you only consider numbers of exactly one digit; you assume that user input is exactly mapped to your array with exactly one "blank" position between the numbers of interest (as you access x[0]+x[2] with hard-coded indexes 0 and 2); you are limited to exactly two "numbers" to be summed up; ...
I'd rather scan integral values (i.e. using %d and data type int) within a loop until one enters something that is not a valid number. This solves all of above mentioned issues:
int main() {
int sum=0;
int num=0;
printf("type in numbers to be summed up (type a non-number to exit):\n");
while (scanf("%d",&num)==1) {
sum += num;
}
printf("sum: %d\n",sum);
}
Intput/Output:
type in numbers to be summed up (type a non-number to exit):
10 20 30 x
sum: 60
There's a few things missing here.
For one thing, you're only reading one character with %c. You're storing it in &x, which, though confusing, is technically legal: since it's a sequence of 3 char-sized elements in memory, &x is a valid character address. However, x[1] and x[2] remain uninitialized; you're not setting them anywhere.
Secondly, you're not converting it to an integer value so it still has the value of the character '1' not decimal 1. '1' + '1' (note single quotes) will evaluate to 49 + 49 (note lack of quotes), 49 being the ascii equivalent to the character '1' - very different from the decimal value 1.
Finally, you're only summing the first and third character (the latter, being uninitialized, has an unknown value, certainly not one from your input). The second character is not a part of the final result.
If you want to read 3 integers, you should scan for ints, not characters, and you should scan for the number of them you wish to read. That would allow you to read numbers above 9 correctly.
But perhaps you do want to scan for one digit at a time; in which case, you'll certainly want to convert each digit character to it's integer equivalent. Since the digits 0 to 9 are contiguous and in ascending order in ascii, you can simiply subtract '0' from the character to get its decimal equivalent ( '1' - '0' == 1, '9'-'0'==9, etc.) But for this to work, you must ensure that you really have read a digit and not just any char. You might do so by verifying that its value was between '0' and '9', inclusive.
Regardless of whether you wish to sum integers or digits, you'll want to ensure you're reading each value you're going to sum before computing the final sum.
It might make more sense, given your use case, to keep scanning for ints in a loop until you run out of ints on the input stream. You don't really need to store them each; you can read one int at a time and add it to a running total.
Putting that all together, you might end up with something like this. Take these ideas and implement your running sum, and you'll have what you want for characters.
#include <stdio.h>
int main() {
char c; // we'll store our input here as we go
while( scanf(" %c", &c) == 1 ) { //one thing matched
if(c >= '0' && c <= '9'){ // it's a digit
printf("Read %c, decimal value of digit is %d\n", c, (int)(c-'0') );
}else {
printf("Invalid digit %c\n", c);
}
}
}
I run like this:
$ gcc -o t t.c && echo '1 2 3 4 5' | ./t
Read 1, decimal value of digit is 1
Read 2, decimal value of digit is 2
Read 3, decimal value of digit is 3
Read 4, decimal value of digit is 4
Read 5, decimal value of digit is 5
Change to scanf("%d") like described below to read multi-digit integers instead, changing the code accordingly.
#include <stdio.h>
int main() {
int c; // we'll store our input here as we go
while( scanf(" %d", &c) == 1 ) { //one thing matched
printf("Read %d; wasn't that easy?\n", c);
}
}
$ gcc -o t2 t2.c && echo '1 2 3 4 5' | ./t2
Read 1; wasn't that easy?
Read 2; wasn't that easy?
Read 3; wasn't that easy?
Read 4; wasn't that easy?
Read 5; wasn't that easy?
That approach can read any integer repesentation up to the min/max size of int, including multiple digits and even negative numbers:
$ gcc -o t2 t2.c && seq -1 -10 | ./t2
Read -1; wasn't that easy?
Read -2; wasn't that easy?
Read -3; wasn't that easy?
Read -4; wasn't that easy?
Read -5; wasn't that easy?
Read -6; wasn't that easy?
Read -7; wasn't that easy?
Read -8; wasn't that easy?
Read -9; wasn't that easy?
Read -10; wasn't that easy?
You could try:
int n1;
int n2;
scanf("%d %d", &n1, &n2);
int sum = n1 + n2;
printf("%d\n", sum);
If you want to add more than two numbers together, you could try:
printf("Enter how many numbers you want to add:\n");
int n;
scanf("%d", &n);
int sum;
for (int i = 0; i < n; i++) {
int in;
scanf("%d", &in);
sum += in;
}
printf("%d\n", sum);
Note:
At first the answer had C++ in the title and so I answered with C++ like this:
If you don't mind using cin and cout, you could try:
int n1;
int n2;
cin >> n1 >> n2;
cout << n1 + n2;
Running this program with n integers will return their sum by iterating from argv[1] to argv[n]. argv[0] is the name of the program.
Example:
./sum 1 3 returns 4
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int sum;
if (argc > 1)
{
for (i = 1; i < argc; i++)
{
sum += (int)strtol(argv[i], NULL, 10);
}
printf("%d\n", sum);
}
else
{
fprintf(stderr,"Invalid number of arguments\n");
return(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
You could use an array and a loop. This is a simple method.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0, allocation[5],i,num;
printf("enter the number of elements");
scanf("%d",&num); // how many numbers are there??
printf("Enter the elements");
for(i=0;i<num;i++)
{
scanf("%d",&allocation[i]); //allocate the elements in the array say 3,4,5
sum=sum+allocation[i];
//0+3, sum=3
//3+4, sum=7
//7+5, sum=11
}
printf("Sum= %d",sum); //print Sum=11
getch();
}
#include <stdio.h>
int main () {
int num1,num2;
printf("Enter two numbers");
scanf("%d %d", &num1 &num2);
printf("Sum is = %d", num1+num2);
return 0;
}
Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8
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.