Segmentation fault in iterative summation [duplicate] - c++

This question already has answers here:
How does the scanf function work in C?
(7 answers)
Closed 8 years ago.
Write a program to read an integer number and keep on adding the digits till
we get a number with a single digit. For example, 7976 yields an output of 2
(7976 - - t 29 - - t 11 - - t 2).
For this, your main() function must call the function sumdigits(0) to solve
the problem, and then print the final result.
I have solved this problem and the logic is correct, I am not getting any output When i give my input it just move to next line.
#include <stdio.h>
sumdigits(int x)
{
int n = x;
int y = 0;
while(n>0) {
y = y + n % 10;
n = n / 10;
}
return y;
}
int main(void)
{
int a;
scanf("%d",&a);
while(a>10) {
a=sumdigits(a);
}
printf("%d",a);
}

Problem is with this line
scanf("%d",a);
It should be
scanf("%d", &a);
//----------^ use &

Related

Why does this program not give out binary output [duplicate]

This question already has answers here:
Why isn't `int pow(int base, int exponent)` in the standard C++ libraries?
(11 answers)
The most efficient way to implement an integer based power function pow(int, int)
(21 answers)
Closed 2 days ago.
I'm new to C++ and this program that I wrote does not give the output, which is a binary form of an integer input.
It does give the result in Python Tutor. But in VSCode the result is always one less than the actual binary output.
Example-
5 = 100
6 = 109
17 = 10000
#include <iostream>
#include <cmath>
int main(){
int n;
std::cout << "Enter n:- ";
std::cin >> n;
int ans = 0;
int i = 0;
while (n != 0){
int bit = n & 1;
ans = (bit * pow(10, i)) + ans;
n = n >> 1;
i++;
}
std::cout << ans;
return 0;
}
What did I do wrong?

Get number of digits in an int without divided by 10 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.
You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.
If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6
Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).
An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}
Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!

Issue with base converter function [duplicate]

This question already has answers here:
Strange behaviour of the pow function
(5 answers)
Closed 6 years ago.
I'm helping a friend with a C++ assignment. There is an issue with the folowing base converter function:
#include <iostream>
#include <cmath>
using namespace std;
int strToInt(string num, unsigned base){
int result = 0;
for (int i=0; i<num.length(); i++) {
if (num[i]>='0' && num[i]<='9')
result += (num[i]-'0')*pow(base,num.length()-i-1);
else if (num[i]>='A' && num[i]<='F')
result += (num[i]-'A'+10)*pow(base,num.length()-i-1);
else if (num[i]>='a' && num[i]<='f')
result += (num[i]-'a'+10)*pow(base,num.length()-i-1);
}
return result;
}
int main()
{
string number;
int base;
while(number.compare("exit")!=0){
cin>>number;
cin>>base;
cout<<strToInt(number,base)<<"\n\n";
}
return 0;
}
For some inexplicable reason every time I enter 3 and 5 digit decimals and chose base 10 I am getting the proper number -1.
E.g.
100
10
99
10000
10
9999
I've been going over this function for the last 5-6 hours and adding all types of debug code, but for the good of me I can't figure out what the hell is wrong.
Code style remarks are also very appreciated.
Cheers
std::pow does floating-point math. You're probably getting a round-off error somewhere. The usual way to accumulate values is to multiply and add each time through the loop:
result *= base;
result += ch - '0';

How to calculate how many times a number goes into another number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This is the program with the initial 'number' stated in the question taken as 'n' and the 'other number' taken as 10.
void divideme()
static int count=0; //initalised a variable which I'll be returning the value of.
int n;
cin>>n;//taken input of variable which I want to divide by another number (say 10 in this case)
int &rem=n;//created a reference variable which stores the value of n.
while (rem>=10) {
rem=rem%10; //this is to be corrected as rem = rem - 10;
count++;
}
return count;
Your code is overkill. Just do the division one time. The result is the number of times 10 goes into the number. No loop is needed at all. The % operator gives you the modulus (remainder) of a division, which is not what you need in this situation.
int divideme()
{
int n;
cin>>n; //get input which I want to divide by another number (say 10 in this case)
return (n / 10);//return how many times it divides by 10
}
For example:
9 / 10 = 0
9 % 10 = 9
10 goes into 9 0 times, with a remainder of 9.
12345 / 10 = 1234
12345 % 10 = 5
10 goes into 12345 1234 times, with a remainder of 5.
The % operator give you the modulus, which is the remainder after division.
If you just want to count the number of times that 10 goes into a number rem, then replace
rem=rem%10;
with
rem = rem - 10;
in your loop.
(Also, you don't need if (rem>=10) in your code. The while loop takes care of this.)
#include <cmath>
#include <iostream>
int times_divided_by_10(int x)
{
return int(std::log10(double(x)));
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}
expected output:
2
another way:
#include <iostream>
int times_divided_by_10(int x)
{
int count = 0;
while (x >= 10) {
++count;
x /= 10;
}
return count;
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}

Sum of prime numbers less than 2 million [duplicate]

This question already has answers here:
Sum of all primes under 2 million
(5 answers)
Closed 9 years ago.
I am trying to solve a Project Euler problem, it wants me to find the sum of prime numbers below 2 million. Here is the code I wrote :
#include <iostream>
using namespace std;
bool isPrime (int x)
{
for(int i = 2; i < x; i++)
{
if(x % i == 0)
return false;
}
return true;
}
int main ()
{
int x = 0;
for(int i = 3 ; i < 2000000;i++)
{
if(isPrime(i))
x = x + i;
}
cout<<x+2<<endl;
}
I know this is not an efficient way to solve this problem. I found an easier way but I think this solution should give the correct answer too. The answer this code finds is : 1179908154. Can you tell me why this code is giving the wrong answer?
The code gives you the wrong answer since you reach to the point x, which is of type int cant represent your number.
You can use another data type unsigned long long ? which will be able to hold it without overflowing