Sum of first and last digit of a number [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The problem is to find sum of first and second digit of a number.
If number is smaller than 10 then print number itself.
I wrote this code but i don't know why output is wrong.
#include <iostream>
using namespace std;
int main()
{
int t,a,n,l;
cin>>t;
while(t--)
{
cin>>n;
if(n<10)
{
cout<<n;
}
else
{
a=n%10;
l=n/10;
cout<<a+l<<endl;
}
}
return 0;
}

The reason your solution is wrong because n/10 won't give you the first digit :)
If this is for a question for competitive programming(since you're taking in t test cases), I'll suggest taking input as a string assuming that input is always a valid int.
std::string s;
cin >> s;
if (s.size() == 1) std::cout << s << std::endl;
else std::cout << int(s.front() - '0') + int(s.back()-'0') << std::endl;

extracting of required digits is wrong in your solution.
Please find solution for adding first and last digit of a number at
https://onlinegdb.com/Byro9hCMI or below:
its small and hence pasting it here as well:
#include <iostream>
using namespace std;
int main()
{
int first, last, number;
cin>>number;
first = number % 10;
while((number = number/10)>0)
{
last = number;
}
cout << endl << first+last << endl;
return 0;
}
Two Add first two digit (unit and tens)at https://onlinegdb.com/SJXNThAzI or below:
#include <iostream>
using namespace std;
int main()
{
int first, second, number;
cin>>number;
first = number % 10;
number = number/10;
second = number %10;
cout << endl << first+second << endl;
return 0;
}

Related

Finding the Largest Digit in C++ [duplicate]

This question already has answers here:
How do I extract the digits of a number in C++?
(6 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Input a 3-digit integer.
Print the largest digit in the integer (Tip: use % 10 to get the rightmost digit, and / 10 to remove the rightmost digit).
Input: 173
Expected Output: 7
We were given this activity 2 days old and still couldn't solve this mystery. Here's my own code which doesn't match the given expected output above:
#include<iostream>
using namespace std;
int main() {
int num, result;
cin >> num;
if(num > 0) {
result = num % 10;
num / 10;
cout << result;
}
return 0;
}
You separate only the last digit, but need to check all - just add a loop. Also num / 10 does nothing.
maxdigit = 0;
while (num > 0) {
maxdigit = max(maxdigit, num % 10);
num /= 10;
}
cout << maxdigit;
Different way to solve the problem. Take the input as a string. You can handle much larger numbers and the string is already decomposed into digits. You barely have to think. Just work through the string character-by-character, make sure the character is a digit, and keep track of the biggest digit seen so far.
#include<iostream>
#include <cctype> // needed for isdigit
//using namespace std; Not recommended. Causes problems
int main()
{
std::string num;
char max = 0;
std::cin >> num; // read number as a string.
for (char ch: num)
{ //iterate string character by character
if (!isdigit(static_cast<unsigned char>(ch)))
{ // if we didn't get a digit, the user screwed up (or is a jerk)
// Let's not assume malice and let them know they've made a mistake.
std::cerr << "Must input a valid number";
return -1;
}
if (ch > max)
{ // this is the biggest character seen so far.
max = ch; // update biggest
}
}
std::cout << max; // print biggest
return 0;
}
The answer of MBo is the best and should be accepted.
You are obviously not allowed to use C++ algorithms yet. And, maybe you are learing now about interger and modulo divisions.
If you would be allowed to use more advanced C++, you would probably write something like:
#include <iostream>
#include <algorithm>
int main()
{
if (std::string number{}; (std::cin >> number) and std::all_of(number.begin(), number.end(), ::isdigit))
std::cout << *max_element(number.begin(), number.end()) << '\n';
}
Below is the working example without using loops and without using std::max. Note this(without loop) is just one among many possible ways of doing it.
#include <iostream>
int findDigit(int passed_num, int current_num)
{
int lastDigit;
if (passed_num == 0) {
return current_num;
}
// find the last didit
lastDigit = passed_num % 10;
if(lastDigit > current_num)
{
current_num = lastDigit;
}
//call findDigit() repeatedly
current_num = findDigit(passed_num / 10, current_num);
std::cout<<lastDigit<<" ";
return current_num;
}
int main()
{
std::cout << "Enter a number: ";
int input_num, greatest_num;
std::cin>>input_num;
greatest_num = findDigit(input_num, 0);
std::cout<<"greatest is: "<<greatest_num<<std::endl;
std::cout<<"Enter another number: ";
std::cin>>input_num;
greatest_num = findDigit(input_num, 0);
std::cout<<"greatest is: "<<greatest_num<<std::endl;
return 0;
}
The output of the above is as follows:
Enter a number: 24344357
2 4 3 4 4 3 5 7 greatest is: 7
Enter another number: 2353639
2 3 5 3 6 3 9 greatest is: 9
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 23;
int max = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) ;
cout << max << endl;
}//using Ternary Operator

How to repeat the string in C++? [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 3 years ago.
Improve this question
I have to write a program in which integer value is entered from user and the string has to be displayed that many times. But I am getting errors.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
cout << string(N, "Well Done");
return 0;
}
Note: I am not permitted to use a loop in this assignment.
If you may not use a loop, you may use goto to get around the restriction:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
{
int i = 0;
goto test;
begin:
cout << "Well Done";
++i;
test:
if (i < N)
goto begin;
}
return 0;
}
Note that goto is widely considered bad practice.
EDIT2: IN THE ORIGINAL ASKER's COMMENTS, LOOPS OF ANY KIND ARE PROHIBITED IN THIS ASSIGNMENT.
Use recursion.
void printN(int n, string s) {
if (n <= 0) return;
cout << s << endl;
printN(n-1, s);
}
Then you can call this from your main program as follows:
printN(userInput, "Hi my name is ricky bobby");
EDIT: just saw you haven't learned recursion yet. Look up this term, and familiarize yourself with it. This is a way to do iteration without looping (this is the most simplistic way I can describe it)
std::string does not have a constructor that repeats a string N times (it does have one for repeating a single character N times, though). What you need is a loop instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
for (int i = 0; i < N; ++i)
cout << "Well Done";
return 0;
}

Un-mash a string in C++ using recursion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Part A: Have a user input a string. Then display this string smashed up as follows: display the first character in the string, then the last, then the second, then the second to last, then the third... So if the string is “abcdef”, it will display:
afbecd (input “abcdef”)
12345 --> 15243
123456 --> 162534
Part B: Now, unmash the above strings.
i.e 162534 -->123456
I got part A to work.
#include <iostream>
using namespace std;
void mash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
mash(sequence);
}
void mash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
cout << s[a - 1];
s = s.substr(1,a-2);
mash(s);
}
}
but I have no clue how to approach part B. I guess I can try to print out the characters in the even position, say in the string 162534, thus I will get 123. Then I guess I can try to print out the odd position characters from the last one up to the first one, i.e, 456. Combining these two will get the original strings but I have no clue how to use recursion to solve part B.
Here is a hint. So unmash(string s) should first print the first character s[0], then unmash(s.substr(2, length - 2)), then s[1]. Of course, you also need to check if length <= 2 need to treat that differently.
Here is my answer an it works perfectly thanks to all of the members of SO who helped me.
#include <iostream>
using namespace std;
void unmash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
unmash(sequence);
}
void unmash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1||a == 2)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
unmash(s.substr(2));
cout << s[1];
}
}

Finding the primality of an integer using C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Write a C++ algorithm to test for a prime number. My C++ codes are as follows
#include<iostream>
#include<cmath>
using namespace std;
int x,n;
bool isprime(int);
int main()
{
cout<<"Enter prime no"<<endl;
cin>>x;
for (n=2;n<=floor(sqrt(x));n++)
{
if (x==1)
cout<<"not prime"<<endl;
else if (x%n==0)
cout<<"is not prime"<<endl;
else
cout<<"prime"<<endl;
}
}
But when i run the programn my output does not seem right for example i keep getting "is prime" when the answer is clearly is not prime.The
else if (x%n==0)
cout<<"is not prime"<<endl;
portion of the statement couldnt seem to be excuted properly.Could anyone explain to me what is wrong with my code. Thanks
Your loop outputs "prime" for each non-divisor of x. You should terminate the loop after the first "not prime" hit and only output "prime" if the loop was not terminated.
As suggested by Udo Klein, you should break out of the loop when it is has been detected that the number is not a prime. Also there is no need to check if x is equal to one inside the loop.
#include<iostream>
#include<cmath>
int main()
{
int x;
std::cout << "Enter prime no" << std::endl;
std::cin >> x;
if (x == 1)
{
std::cout << "not prime" << std::endl;
return 1;
}
for (int n = 2; n <= floor(sqrt(x)); n++)
{
if (x % n == 0)
{
std::cout << "is not prime" << std::endl;
return 1;
}
}
std::cout << "prime" << std::endl;
return 0;
}

Wrong output for sum of digits using loop c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i was required to make a program that asks users for a positive integer value, while the program uses loop to get the sum of all the numbers from 1 through n (user input). So lets say the user enters 5, the program would do 1+2+3+4+5 = 15
this is the code so far
#include <iostream>
using namespace std;
int main()
{
int number; int sum = 0; // variables
cout <<"Please input an integer greater than zero\n"
<<"Please refrain from using a negative integer." <<endl;
cin >> number; // user input
for (int i=1; i <= number; i++) // looping statement
{
sum = sum + i; // formula that takes user digits and finds sum
cout << sum;
}
My issue is that when i compile the program,for example, i enter 3, the program's output would be "136"
i want it to say 1+2+3 = 6 or much something like "the sum of the integer is 6" i just want to show the total of the value.
I'm new in c++ any help would be appreciated. Thank you!
You are writing cout << sum inside your loop. That means you get one number output every time your loop runs (it's really writing 1 then 3 then 6 which gets all smushed together and comes out as 136). Move that statement after the following }.
Here's how you can get your 1+2+3=6 output:
#include <iostream>
using namespace std;
int main()
{
int number; int sum = 0; // variables
cout <<"Please input an integer greater than zero\n"
<<"Please refrain from using a negative integer." <<endl;
cin >> number; // user input
for (int i=1; i <= number; i++) // looping statement
{
sum = sum + i; // formula that takes user digits and finds sum
if ( i == number )
cout << i;
else
cout << i << "+";
}
cout << "=" << sum;
}