I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}
Related
int grades[100];
int j = 0;
int len = sizeof(grades)/sizeof(grades[0]);
while (j < len)
{
cout << grades[j] << endl;
j++;
}
I have entered only 5 grades and I want to print only that entered grades then ho can I print that?
I have tried to use length of array but since I have created array of size 100, it is printing all unwanted characters at the end.
I have also used '\0' to get end of array but it is not working.
#include <vector>
std::vector<int> grades;
// add 3 grades
grades.push_back(4);
grades.push_back(1);
grades.push_back(9);
// https://www.cplusplus.com/reference/vector/vector/size/
auto size = grades.size();
Just keep track of the size when you read the numbers:
#include <iostream>
int main()
{
int const max_len = 100;
int arr[max_len];
std::cout << "Enter numbers: ";
int len = 0;
while (len < max_len && std::cin >> arr[len]) {
++len;
}
// you've read `len` numbers.
std::cout << "You've entered " << len << " numbers\n";
for (int i = 0; i != len; ++i) {
std::cout << arr[i] << '\n';
}
}
Your code returns the total number of elements the array can store.
Try this instead:-
#include <iostream>
int main()
{
int sample[10];
int length = 0;
for (int integer : sample)
{
if (integer != NULL)
{
length++;
// If you want to print the element as well -
std::cout << integer << std::endl;
}
}
}
Essentially what it does goes through all of the elements of the array and adds 1 to length if that element is not NULL (NULL means a null pointer, or if you're a beginner, just know it means basically nothing).
You can easily change int to any other type.
Hope it helps :)
do you know how can I start to count a string from 1 and not from 0 in c++? for example, xyz are on iterations 0,1,2.. but i need them to be on 1,2,3. I know you can put cout << i+1; but is there any other way to do this with strlen(s+1)?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 0; i < n; ++i)
cout<<i<<": "<<s[i]<<"\n";
return 0;
}
i+1 is the way to go. An alternate method is starting your loop with 1 instead and accessing the array at element i-1, but that's a bit silly:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 1; i <= n; ++i) // i = 1 not 0
cout<<i<<": "<<s[i-1]<<"\n";
return 0;
}
In C++, you shouldn't use C-Strings. Instead, use std::string:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::getline(std::cin, s);
for (int i = 0; i < s.length(); ++i)
std::cout << i + 1 << ": " << s[i] << '\n' ;
return 0;
}
As others have said, the simple answer is really just accept you start from zero - however, for an actually solution you can use boost-range and use an index adaptor with an argument of '1'.
std::string str;
std::getline(std::cin, str);
for (const auto & element : str | boost::adaptors::indexed(1)) {
std::cout << element.index()
<< " : "
<< element.value()
<< std::endl;
}
I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:
I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I'm making a program that prints all digits from an array (entered as an integer) and it works, but the digits are printed backwards and I don't know how to reverse them. Can someone help?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
cout << digit << '\n';
number /= 10;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
// numdigits = explode(n,digits);
cout << "[";
while (n > 0) {
int digit = n % 10;
n /= 10;
digits[digit] = digit;
cout << digits[digit];
}
cout << "]" << endl;
}
You just have to reverse the array using reverse() from <algorithm>.
Code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
int array_c = 0;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
number /= 10;
array[array_c++] = digit;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
explode(n,digits);
reverse(digits,digits+array_c);
cout << "[";
for(int i = 0; i < array_c; ++i)
cout<<digits[i];
cout << "]" << endl;
}
Your use of
digits[digit] = digit;
is not right. You probably meant to use
digits[numdigits] = digit;
You can fix your problem by dividing the work into two steps. In the first step, you store the digits. In the second step, you print the digits.
int numdigits = 0;
while (n > 0) {
cout << "n: " << n << endl;
int digit = n % 10;
n /= 10;
digits[numdigits++] = digit;
}
// Make sure to print them in reverse order.
cout << "[";
for ( ; numdigits > 0; )
{
cout << digits[--numdigits];
}
cout << "]" << endl;