For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements) the index of this number starts from 1 by this it means​ that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;
int i, n, result = 0;
cout << "Input number to sum: ";
cin >> n;
// Finding result
for (i = 0; i <= n; i++){
if (i % 2 == 0) {
result +=i;
} else {
result += i * 5;
}
}
// Make last number have equal sign "1+6+7+12 = 36"
for (i = 0; i <= n; i++){
if (i == n) {
cout << i..?? << "=";
} else {
cout << i..?? << "+";
}
}
// Print result out
cout << result;
return 0;
}
Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
int value = i % 2 == 0 ? i + 1 : i + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>
int main()
{
int n;
std::cout << "Input number to sum: ";
std::cin >> n;
auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };
int result = 0;
int value = 0;
for (int i = 0; i < n; i++)
{
value += update(i);
result += value;
}
std::cout << '\n';
for (int i = 0, value = 0; i < n; i++)
{
value += update(i);
std::cout << (i > 0 ? " + " : "") << value;
}
std::cout << " = " << result;
}
Testable here.
I agree with molbdnilo's answer. However the algorithm some changes.
The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)
while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;
int main()
{
int i, n, result, value = 0;
cout << "Input number to sum: ";
cin >> n;
for (i = 0; i < n; i++)
{
value = i % 2 == 0 ? value + 1 : value + 5;
cout << (i > 0 ? " + " : "") << value;
result += value;
}
cout << " = " << result;
return 0;
}
Testable here
Related
The sequence consists of all numbers from 1 to N (inclusive), n(1<=n<=100). All the odd numbers are listed first, then all the even numbers. For example you input 8 and the code prints this: 1,3,5,7,2,4,6,8. Although when I input an odd number it adds a comma in the end. It's my first time here, no idea how to post it correctly...
Even numbers here
> for(int i=1;i<=n;i++){
if(i%2!=0){
cout<<i<<",";
}
}
Odd numbers here
for(int i=1;i<=n;i++){
if(i%2==0){
if(i==n){
cout<<i;
}
else{
cout<<i<<",";
}
}
}
My pattern.
The comma doesn't get postfixed. It gets prefixed on everything but the first item.
// print odd
for (int i = 1; i <= n; i += 2)
{
if (i != 1)
{
cout << ",";
}
cout << i;
}
for (int i = 2; i <= n; i += 2)
{
cout << ",";
cout << i;
}
Or simplified:
for (int i = 1; i <= n; i += 2)
{
cout << ((i == 1) ? "" : ",") << i;
}
for (int i = 2; i <= n; i += 2)
{
cout << "," << i;
}
The sequence consists of all numbers from 1 to N (inclusive).
So you always have to print 1. Then you just have to print a comma before the (eventual) other numbers.
void print_all_numbers_1_n(int n)
{
std::cout << '1';
for (int i = 3; i <= n; i += 2)
std::cout << ", " << i;
for (int i = 2; i <= n; i += 2)
std::cout << ", " << i;
std::cout << '\n';
}
I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo
I am kinda a newbie in C++ and I am a having hard time with a situation.
My task is to create a decimal to [2:9] number system conversion. I am dividing the input number to the base and then, taking the quotient as the divident and continuing the same process.
For example if the decimal number is 149 and that number is calculated on base 2, my output is like this:
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 1
Remainder 0
Remainder 0
Remainder 1
The outputs are the elements of an array named remainder.
And then I have to merge these array elements in reverse order (1001010) to form the new base number as an integer. How can I do this? I am stuck at this point. The above output is just the part of my output. The number will be prompted from user and it is going to be calculated on bases from 2 to 9. So, array lenghts may change (I have the code for the digit calculation, I have no issues with that).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int merge(int a[]);
int main(int argc, char*argv[])
{
int dNumber;
int system[8];
for (int i = 0; i < 8; i++)
{
system[i] = i + 2;
}
cout << "Please enter the decimal base number which you want to use in the conversion: " << endl;
cin >> dNumber;
int permanent = dNumber; //to keep the input number intact as it changes through the loops (used in line 53)
int ndigits[8]={1};
for (int i = 0; i < 8; i++)
{
while(dNumber > pow(system[i], ndigits[i]))
{
ndigits[i] ++;
}
}
int dNumberNew = dNumber;
for (int k = 0; k < 8; k++){
for (int i=0; i>=0; i++)
{
int Remainder[i], quotient[i];
Remainder[i] = dNumberNew % system[k];
quotient[i] = dNumberNew / system[k]; // since the variables are integers, this line does not assign decimals and finds the quotient easily.
cout << dNumberNew << " " << system[k] << "'e bolundu. " << "Sonuc " << quotient[i] << " Kalan " << Remainder[i] << " cikti." << endl;
dNumberNew = quotient[i];
if (quotient[i] == 0)
{
break;
}
}
cout << "(" << dNumber << ")" << "_(" << system[k] << ")" << "=" << endl;
cout << "" << endl;
dNumberNew = permanent;
}
}
Here is a function you can use as DecimalToBinary converter, analyze the code yourself
string toBinary(unsigned long long* arr, unsigned long long size) {
string answer;
for (unsigned long long i = 1; i < size; i++) {
string binaryNum = "";
while (arr[i] >= 1) {
binaryNum = static_cast<char>((arr[i] % 2) + '0') + binaryNum;
arr[i] = arr[i] / 2;
}
answer += binaryNum + " ";
}
return answer;
}
I need to write a program that takes an integer as input and outputs it with its digits spaced. The algorithm works fine but prints the digits in reverse order. To get the original order, I used a for loop. The problem is that it prints nothing.
#include <iostream>
using namespace std;
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num) ;
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << " Your digits:";
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
return 0;
}
My issue is here
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
It prints nothing. What could be the problem ?
The input used is 1234
The expected output is 1 2 3 4
For starters the function countDigit is wrong.
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
It returns 0 for the valid number 0 that has one digit.
The function can look the following way
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
In this loop
for (int i = countDigit(Num); i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
the variable Num was changed. So in the next loop
for (int x = 1 ; x <= countDigit(Num) ; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
it will not have the original value You need to use an intermediate variable to make the calculation.
Also take into account that the use can enter a negative number.
EDIT: After you updated your code then you also need to move the output of the sum from the loop
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
}
cout << sum ;
And instead of the large integer array it is better to use an object of the type std::string.
Here is a demonstrative program
#include <iostream>
#include <string>
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
int main()
{
const int Base = 10;
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
size_t count = countDigit( num );
std::string s( count, ' ' );
int sum = 0;
for ( ; count-- != 0; num /= Base )
{
int digit = num % Base;
if ( digit < 0 ) digit = -digit;
s[count] = digit + '0';
sum += digit;
}
std:: cout << "Your digits: ";
for ( const auto &c : s ) std::cout << c << ' ';
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Its output might look like
Enter an integer: -123456789
Your digits: 1 2 3 4 5 6 7 8 9
The sum of digits is 45
Another approach is to write a recursive function that outputs digits and returns the sum of digits.
#include <iostream>
unsigned int recursive_sum( long long int n, long long int base = 10, std::ostream &os = std::cout )
{
long long int digit = n % base;
if ( digit < 0 ) digit = -digit;
unsigned int sum = digit + ( ( n /= base ) == 0 ? 0 : recursive_sum( n ) );
os << digit << ' ';
return sum;
}
int main()
{
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
unsigned int sum = recursive_sum( num );
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Again the program output might look like
Enter an integer: -123456789
1 2 3 4 5 6 7 8 9
The sum of digits is 45
This gives the expected output. I assigned countDigit(Num) to c and wrote the sum to outside the loop.
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num); //edit 1
// extracts the digits
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << "Your digits with spaces: ";
// reverses the order
for (int x = 1 ; x <= c ; x++)
{
cout << arr[x] << " " ;
}
cout << endl << "The sum of the digits is: " << sum ; // edit 2
return 0;
}
Here's a shorter version:
#include <concepts>
#include <cstdio>
#include <string>
template <std::integral T>
void printDigits(T const i) {
for (auto const ch : std::to_string(i)) {
std::printf("%c ", ch);
}
std::fflush(stdout);
}
LIVE
Here's a take that uses strings.
#include <iostream>
#include <string>
int main()
{
std::string input;
std::size_t location;
std::cout << "Enter an integer: ";
std::getline(std::cin, input);
std::stoi(input, &location); // Don't care about the integer, just location
if (location != input.length()) {
std::cout << "Invalid Entry: Non-integer entered\n";
return 1;
}
for (auto i : input) {
std::cout << i << ' ';
}
// Here's a one liner that requires <algorithm>
// std::for_each(input.begin(), input.end(), [](auto i) { std::cout << i << ' '; });
std::cout << '\n';
}
I don't care about an integer at all. I can validate that only digits were entered and quit early if not. The only loop I need is for printing.
stoi() can return the integer, but I don't care about the integer. I just want to know how many characters were converted, and I learn that by feeding it the output argument location. Checking that location is the same as the string length ensures that only digits were entered. No decimal points, no extra letters, just numbers.
The caveats are that this might not fit into your requirements if this is an assignment. It also requires C++11, which is surprisingly not a given yet (for assignments, I get the industry arguments).
I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}