Detecting the first digit in the second digits? - c++

Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.

As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}

Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}

Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.

Related

delete all digits except one

I have this integer:
4732891432890432432094732089174839207894362154
It's big so I want to delete all digits in it except the digit 4 and I don't know how. This is my code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
unsigned ll n, lastDigit, count = 0;
ll t;
cin >> t;
while(t--)
{
cin >> n;
while (n !=0)
{
lastDigit = n % 10;
if(lastDigit == 4)
count++;
n /= 10;
}
cout << count << "\n";
}
return 0;
}
I used the while loop because I have multiple test case not only that number.
Just to show you current C++ (C++20) works a bit different then wat most (older) C++ material teaches you.
#include <algorithm>
#include <iostream>
#include <string>
#include <ranges>
bool is_not_four(const char digit)
{
return digit != '4';
}
int main()
{
// such a big number iwll not fit in any of the integer types
// needs to be stored in memory
std::string big_number{ "4732891432890432432094732089174839207894362154" };
// or input big_number from std::cin
// std::cout >> "input number : "
// std::cin >> big_number;
// NEVER trust user input
if (!std::any_of(big_number.begin(), big_number.end(), std::isdigit))
{
std::cout << "input should only contain digits";
}
else
{
// only loop over characters not equal to 4
for (const char digit : big_number | std::views::filter(is_not_four))
{
std::cout << digit;
}
// you can also remove characters with std::remove_if
}
return 0;
}

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 get length of int variable as string have builtin function e.g string.length()

Is there any way to get the length of int variable e.g In string we get the length by simply writing int size = string.length();
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i = 0;
cout<<"Please Enter the value of i"<<endl;
cin>>i;
//if user enter 123
//then size be 3 .
// Is it possible to find that size
}
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
int main () {
assert(int(log10(9)) + 1 == 1);
assert(int(log10(99)) + 1 == 2);
assert(int(log10(123)) + 1 == 3);
assert(int(log10(999)) + 1 == 3);
return 0;}
You have a few options here:
(This answer assumes you mean number of printable characters in the integer input)
Read the input as a string and get its length before converting to an int. Note that this code avoids error handling for brevity.
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter the value of i" << endl;
string stringIn = "";
cin >> stringIn;
cout << "stringIn = " << stringIn << endl;
size_t length = stringIn.length();
cout << "input length = " << length << endl;
int intIn;
istringstream(stringIn) >> intIn;
cout << "integer = " << intIn << endl;
}
Read in an integer and count the digits directly:
Many other answer do this using log. I'll give one that will properly count the minus sign as a character.
int length_of_int(int number) {
int length = 0;
if (number < 0) {
number = (-1) * number;
++length;
}
while (number) {
number /= 10;
length++;
}
return length;
}
Derived from granmirupa's answer.
Not sure whether it fits your requirement but you could use std::to_string to convert your numeric data to string and then return its length.
For length i assume you mean the number of digits in a number:
#include <math.h>
.....
int num_of_digits(int number)
{
int digits;
if(number < 0)
number = (-1)*number;
digits = ((int)log10 (number)) + 1;
return digits;
}
Or:
int num_of_digits(int number)
{
int digits = 0;
if (number < 0) number = (-1) * number;
while (number) {
number /= 10;
digits++;
}
return digits;
}
Onother option could be this (can works with float too, but the result is not guaranteed):
#include <iostream>
#include <sstream>
#include <iomanip>
...........
int num_of_digits3(float number){
stringstream ss;
ss << setprecision (20) << number;
return ss.str().length();
}

Is there a way in C++ to only return the the last instance of a for loop?

Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}

Fibonacci series in C++ can't get more than 47 numbers

I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}