show last digit of string/int

How do i show the last number/letter of a string/int?
for example take it we have the number 888888881, how do i just show the number 1?
For int:

int myNumber = 888888881;

cout << myNumber % 10; This is called the modulus operator (The remainder of dividing by 10).

For Strings:

cout << myString.at (myString.length () - 1);

Last edited on
closed account (EvoTURfi)
For ints, I'm not sure.

For strings, this is how I do it:

1
2
3
4
5
6
7
8
char mychar[26];
int i=0;
while(mychar[i]!='\0') // This loop will go through all of the characters in the string until it reaches \0
{
i++;
}
i--; // This will go to the last character of the string
cout<<mychar[i]<<endl; // Display last character 
dvader123's way is correct, but takes longer time. Because you are looping with a loop size equals to the string size - 1.

So, it's better to direct access the character at the position you want. Here's how it works.

When you declare a string and it is eventually set, for example, to "Hello", it's actually an array of characters.

An Array is a set of pointers that point to subsequent in-order places in the memory which contains data of the type you declared the array with. In this case, char.

When you use square brackets in arrays [] or at in strings, you actually tell your program to do something like this:

1. Fetch the address of the pointer to the first element in the array.
2. Identify the data type of the elements and get its byte size. In our case char, the byte size is one.
3. Now, we know how many bytes the array allocates and the order of the needed element, so the needed byte which has our data (letter) is d away from the first pointer; where d = (byte size of one character) * position you requested .

So, no looping done, so this operation is O(1) while the looping way is O(n). Look up time complexity analysis for more info.

anybody willing to help me? :( please please
You can use % operator for any number of integers you want to separate. For example 888881%10 will give you 1 and 888881%100 will give you 81...

@aiden post your problem separately and you will surely get help...

http://recurseit.blogspot.com
Topic archived. No new replies allowed.