I want to save an integer type value in array.
Here is a code.
int a,arr[5];
cout<<"Enter a Number ";
cin >> a;
Suppose user enter the value 73972 This value save in arr like this.
arr[0] = 7;
arr[1] = 3;
.. .. .. ..
.. .. .. ..
arr[4] = 2;
How can I do that.???
Iterate reversely on the array and each time divide the number by 10 and store the reminder on the array.
for(int i=4; i>=0; i--)
{
arr[i] = a % 10;
a /= 10;
}
Read a string and break it into digits.
First of all integer values can have more than 5 digits.
You can get the number of digits that an object of type int can contain by using expression
std::numeric limits<int>::digits10 + 1
class std::numeric_limits is declared in header <limits>
Also take into account that if a number contains less digits than the size of the array then you need some mark that will determine the end of the number in the array.
I would advice you to use a character array instead of an array of integers in which the terminating zero will determine the end of the number.
If you want to use an integer array then the code could look the following way
#include <iostream>
#include <algorithm>
#include <limits>
int main()
{
int arr[std::numeric_limits<int>::digits10 + 1];
int a;
std::cout << "Enter a Number ";
std::cin >> a;
int n = 0;
do
{
arr[n++] = a % 10;
} while ( a /= 10 );
std::reverse( arr, arr + n );
for ( int i = 0; i < n; i++ ) std::cout << arr[i] << ' ';
std::cout << std::endl;
}
Related
void decimaltobin()
{
binaryNum = 0;
m = 1;
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * m;
m *= 10;
}
}
Just wondering if there was an easy fix to get this function to print an 8-bit binary number instead of a 4-bit number, e.g. 0000 0101 instead of 0101.
As mentioned in the comments, your code does not print anything yet and the data type of binaryNum is not clear. Here is a working solution.
#include <iostream>
using namespace std;
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing the required number of zeros
int zeros = 8 - i;
for(int m = 0; m < zeros; m++){
cout<<0;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
The code implements the following:
Store the remainder when the number is divided by 2 in an array.
Divide the number by 2
Repeat the above two steps until the number is greater than zero.
Print the required number of zeros. That is 8 - length of the binary number. Note that this code will work for numbers that can be expressed in 8 bits only.
Print the array in reverse order now
Ref
Maybe I am missing your reason but why do you want to code from scratch instead of using a standard library?
You may use standard c++ without having to code a conversion from scratch using for instance std::bitset<NB_OF_BITS>.
Here is a simple example:
#include <iostream>
#include <bitset>
std::bitset<8> decimalToBin(int numberToConvert)
{
return std::bitset<8>(numberToConvert);
}
int main() {
int a = 4, b=8, c=12;
std::cout << decimalToBin(a)<< std::endl;
std::cout << decimalToBin(b)<< std::endl;
std::cout << decimalToBin(c)<< std::endl;
}
It outputs:
00000100
00001000
00001100
Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}
#include<iostream>
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
int main() {
int n;
std::cout << "Enter a Number";
std::cin >> n;
int result = fastFibonacci(n);
std::cout << result << "\n";
return 0;
}
in this code when i enter input 0 or 1 get correct answer. But the problem is that when i replace int numbers[n+2]; with the commented part it start giving me wrong answer when input is 0 or 1. why? anyone please explain me.
In this function
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
there is used a variable length array with n + 2 elements declared in this line
int numbers[n+2]; // int numbers[n].
Variable length arrays is not a standard C++ feature. It can be implemented as own language extension of a C++ compiler.
Using the variable length array makes the function very unsafe because there can occur a stack overflow.
As within the function there is explicitly used two elements of the array
numbers[0] = 0;
numbers[1] = 1;
then the array shall have at least two elements even when the parameter has a value less than 2.
To calculate the n-th Fibonacci number there is no need to declare an array of such a size.
Apart from this the function argument shall have an unsigned integer type. Otherwise the function can invoke undefined behavior if the user passes a negative number.
Also for big values of n there can be an integer overflow for the type int.
The function can be implemented in various ways.
Here is one of possible its implementations.
#include <iostream>
#include <functional>
unsigned long long fibonacci( unsigned int n )
{
unsigned long long a[] = { 0, 1 };
while ( n-- )
{
a[1] += std::exchange( a[0], a[1] );
}
return a[0];
}
int main()
{
const unsigned int N = 10;
for ( unsigned int i = 0; i < N; i++ )
{
std::cout << i << ": " << fibonacci( i ) << '\n';
}
return 0;
}
The program output is
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
int numbers[n+2]; is the declaration of an array of ints with space for n + 2 ints, this is a variable lenght array and is not part of C++ standard, though some compilers allow it it's not somenthing you should use.
If you need a variable lenght array use std::vector.
With int numbers[n+2]; if n is equal to 0 you still have space for 2 ints, if you have int numbers[n]; the array will have space for 0 ints, so the code will fail because you are trying to access memory that does not exist with numbers[0] and numbers[1].
There are several good ways to implement the Fibonacci sequence, in the site you can find many questions regarding this matter in several programming languages, here is one of them Fibonacci series in C++
Edit
So I've seen your comments about using a vector, for making the sequence you wouldn't need the vector just two variables to store the two numbers to add, to store the sequence in a vactor, you can do somenthing like:
#include <iostream>
#include <vector>
#include <iomanip>
//passing the vector by reference
void fastFibonacci(unsigned long long n, std::vector<unsigned long long>& sequence) {
unsigned long long first = 0;
unsigned long long second = 1;
sequence.push_back(first); //add first values to the vector
sequence.push_back(second); //add first values to the vector
for (unsigned long long i = 0, value = 0; i < n && value <= LLONG_MAX ; ++i) {
value = first + second;
first = second;
second = value;
sequence.push_back(value); //adding values to the vector
}
}
int main() {
unsigned long long limit; //number of values in the sequence
int num = 1;
std::vector<unsigned long long> sequence; //container for the sequence
std::cout << "Enter upper limit: ";
std::cin >> limit;
fastFibonacci(limit, sequence);
//print the sequence in a range based loop formatted with <iomanip> library
for(auto& i : sequence){
std::cout << std::setw(4) << std::left << num++ << " " << i << std::endl;
}
return 0;
}
If you want to print just one of the numbers in the sequence, just use, for instance:
std::cout << sequence[10];
Instead of the whole vector.
The code you post in the comment to the other answer won't work because the access to the vector is out of bounds in numbers[i] = numbers[i - 1] + numbers[i - 2];, if for instance i = 5, your vector only has 2 nodes but you are accessing the 6th node numbers[5].
Suppose I have the integer 1004.
I want to store this in the array A with the following pattern:
A[0]=1
A[1]=0
A[2]=0
A[3]=4
How can I get the value at that index ?
How can I do this in C++?
You get the last index of a number by using modulo 10 and then remove that value by dividing the number by 10.
So assume you do this:
1004 % 10 = 4
1004 / 10 = 100
Then repeat that for each digit
Using c++ static memory:
int originalNumber = 1004;
int digitArray[10] = {0};
int idx = 0;
while (originalNumber > 0)
{
int digit = n % 10;
originalNumber /= 10;
digitArray[idx] = digit;
++idx;
}
// Reverse the order of the array
std::reverse(std::begin(digitArray), std::begin(digitArray)+(idx-1));
I'm not sure if it's the most efficient way of doing this but it definitely works.
You can enter each digit in the number to the array but from the end of the array to the beginning.
For example, there is an array with the size of 4, so you get the last digit of the number like this: num % 10, and push the digit to the third index of the array.
Code example:
#define SIZE 4
int* numToArray(int num)
{
int* arr = new int[SIZE]; // assuming you already know the number of digits in the number
for(int i = SIZE-1; i >= 0; i++)
{
arr[i] = num % 10; // Enters the last digit to the array
num /= 10; // Gets rid of the last digit in the number
}
return arr;
}
Instead of ordinary integer array, I suggest you using std::vector instead.
Then, you can have something like the following:
#include <iostream>
#include <vector>
int main() {
int number = 1004;
std::vector<int> digits;
while (number != 0) {
digits.insert(digits.begin(), number % 10);
number /= 10;
}
for (auto const i : digits) {
std::cout << i << " "; // 1 0 0 4
}
// or by index
std::cout << std::endl;
std::cout << "[0]" << digits[0] << std::endl; // 1
std::cout << "[1]" << digits[1] << std::endl; // 0
std::cout << "[2]" << digits[2] << std::endl; // 0
std::cout << "[3]" << digits[3] << std::endl; // 4
return 0;
}
Demo
Adding to all the existing answers I'd like to propose a more elegant, if probably less efficient approach utilizing the many wonders of the standard library.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
auto number = 1004;
auto asString = std::to_string(number); //
std::vector<int> digits(asString.length());
std::transform(asString.begin(), asString.end(), digits.begin(), [](char c){return c -'0';});
for(auto d : digits)
{
std::cout << d << ' ';
}
}
I'm doing a homework problem where I have two take input from a user in the form of two dynamic char arrays (max of 100 characters each) and returning their sum.
I'm struggling with coming up with a sum function that works correctly when the two numbers are of different length or when the answer is less than 100 digits. When the numbers are of different length, they get added as if they were the same (e.g. 100 + 1000 becomes 1000+1000). When the result is less than 100 digits, the full arrays is printed anyway (so there are dozens of trailing zeros). (EDIT: Fixed, see below).
I know that there is no way to tell the actual size of a dynamic array, and I can't figure out any way to place some sort of sentinel value that stops the program from processing farther. I'm not allowed to use vectors or traditional arrays, which would give me a clear path to the solution. EDIT: This has been fixed by checking for '\0'.
I know SO doesn't want to do people's homework for them (nor am I asking that), but I do need some guidance as to how I can solve this problem. I've been working for hours and still can't think of a solution.
My program is as follows:
#include <iostream>
#include <algorithm>
int* sum(char*, char*);
int main() {
char * arr = new char[100];
char * arr2 = new char[100];
std::cout << "Enter value 1: ";
std::cin >> arr;
std::cout << "Enter value 2: ";
std::cin >> arr2;
int * result = sum(arr, arr2);
std::cout << "Result: ";
for (int i = 0; i < 100 && result[i] != '\0'; i++) {
std::cout << result[i];
}
std::cout << std::endl;
return 0;
}
int* sum(char * num1, char* num2) {
std::reverse(num1, num1 + 100);
std::reverse(num2, num2 + 100);
bool carryOver = false;
int* retarr = new int[100]; //Array to return to user
for (int i = 0; i < 100; i++) {
//Numerical value is char - 48, unless
//char value is zero, then int val is zero
int val1 = std::max(num1[i] - 48, 0);
int val2 = std::max(num2[i] - 48, 0);
int carry = (carryOver)? 1 : 0;
carryOver = false; //Reset carryOver var
int t = val1 + val2 + carry;
if (t >= 10) {
t = t % 10;
carryOver = true;
}
retarr[99 - i] = t;
}
return retarr;
}