Trying to run a code but terminal does not read the program - c++

This is probably a very easy problem, but I am studying while loops and I am trying to write a program that sums numbers from 50 to 100. This is my code that I wrote
#include <iostream>
using namespace std;
int main() {
int sum=0;
int val=1;
while(50 <= val <= 100) {
sum = sum + val;
val = val + 1;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I was to compile the code and get a program, but each time I am trying to run the program on terminal is just goes idle. Is there something wrond with my code? Thanks!

All the comments are valid. Please look at the C++ reference for syntax and how to use operators and loop.
I believe looking at some correct code is also a way to learn and hence posting this :
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
int i = 50; // Why not start from 50 itself, when you want sum(50-100)
while (i <=100)
{
sum += i; // Same as sum = sum + i
i++; // Same as i = i + 1
}
cout<<sum<<"\n";
return 0;
}

Related

How to find Minimum Maximum sum c++

I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
void minimaxsum(vector<int> arr){
int i,j,temp;
int n=sizeof(arr);
int sum=0;
int low=INT_MAX;
int high=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
sum+=arr[i];
}
temp=sum-arr[j];
if(temp<low){
low=temp;
}
else if(temp>high){
high=temp;
}
}
cout<<low;
cout<<high<<endl;
}
int main (){
vector<int> arr;
arr.push_back(1.0);
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
There are 2 problems.
Your code is unfortunately buggy and cannot deliver the correct result.
The solution approach, the design is wrong
I will show you what is wrong and how it could be refactored.
But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.
Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.
Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:
#include <iostream>
#include <vector>
#include <limits.h> // Do not use .h include files from C-language. Use limits
using namespace std; // Never open the complete std-namepsace. Use fully qualified names
void minimaxsum(vector<int> arr) { // Pass per reference and not per value to avoid copies
int i, j, temp; // Always define variables when you need them, not before. Always initialize
int n = sizeof(arr); // This will not work. You mean "arr.size();"
int sum = 0;
int low = INT_MAX; // Use numeric_limits from C++
int high = 0; // Initialize with MIN value. Otherwise it will fail for negative integers
for (j = 0; j < n; j++) { // It is not understandable, why you use a nested loop, using the same parameters
for (i = 0; i < n; i++) { // Outside sum should be calculated only once
sum += arr[i]; // You will sum up always. Sum is never reset
}
temp = sum - arr[j];
if (temp < low) {
low = temp;
}
else if (temp > high) {
high = temp;
}
}
cout << low; // You miss a '\n' at the end
cout << high << endl; // endl is not necessary for cout. '\n' is sufficent
}
int main() {
vector<int> arr; // use an initializer list
arr.push_back(1.0); // Do not push back doubles into an integer vector
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.
Refactoring your code to a working, but still not an optimal C++ solution could look like:
#include <iostream>
#include <vector>
#include <limits>
// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {
// Initialize the resulting values in a way, the the first comparison will always be true
int low = std::numeric_limits<int>::max();
int high = std::numeric_limits<int>::min();;
// Calculate the sum of all 5 values
int sumOf5 = 0;
for (const int i : arr)
sumOf5 += i;
// Now subtract one value from the sum of 5
for (const int i : arr) {
if (sumOf5 - i < low) // Check for new min
low = sumOf5 - i;
if (sumOf5 - i > high) // Check for new max
high = sumOf5 - i;
}
std::cout << "Min: " << low << "\tMax: " << high << '\n';
}
int main() {
std::vector<int> arr{ 1,2,3,1,2 }; // The test Data
minimaxsum(arr); // Show min and max result
}

Averaging Coin Tosses with Accumulator C++

This is the problem I am working with
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The accumulator is not working the way I want It to? Very much a C++ Noob, for homework lol. Anyone help please?
Why am I using rand()????
second part of the assignment has us using the newer method (mt19937), just trying to tackle this bit first before moving on.
#include <iostream>
using namespace std;
int main() {
int heads = 0, tails = 0, num, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
for (int i = 0; i < 10000; i++) // COIN TOSS
{
int random = rand() % 2;
if (random == 0)
{
heads++;
}
else
{
tails++;
}
}
cout << abs((heads++ - tails++));
cin >> num;
total =+ num;
}
cout << "The average distance between is " << total / 1000 << endl;
cin.get();
return 0;
}
With your code, you never actually save the values that you need. And there's some unnecessary arithmetic that would throw off your results. This line:
cout << abs((heads++ - tails++)); increments the heads and tails variables, but they shouldn't be.
The next two lines make no sense. Why do you need to get a number from the user, and why do you add that number to your total?
Finally, this expression: total / 1000 performs integer division, which will throw off your results.
Those are the immediate issues I can spot in your code.
Next, we move on to your problem statement. What is an accumulator? To me, it sounds like you're supposed to have a class? It also reminds me of std::accumulate, but if that's what you intended, it would have said as much. Also, std::accumulate would require storing results, and that's not really necessary for this program. The code below performs the main task, i.e. it runs the necessary simulations and tracks results.
You'll notice I don't bother counting tails. The big average is also calculated as it goes since the total number of simulations is known ahead of time.
#include <cmath>
#include <iostream>
#include <random>
int flip_coin() {
static std::mt19937 prng(std::random_device{}());
static std::uniform_int_distribution<int> flip(0, 1);
return flip(prng);
}
int main() {
constexpr int tosses = 10'000;
constexpr int simulations = 1'000;
double diffAvg = 0.0;
for (int i = 0; i < simulations; ++i) {
int heads = 0;
for (int j = 0; j < tosses; ++j) {
if (flip_coin()) {
++heads;
}
}
diffAvg +=
std::abs(heads - (tosses - heads)) / static_cast<double>(simulations);
}
std::cout << "The average heads/tails diff is: " << diffAvg << '\n';
return 0;
}
What I ended up doing that seems to work for **THIS VERSION WITH RAND() (using the new method later) **
#include <iostream>
using namespace std;
int main()
{
int heads = 0, tails = 0, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
{
for (int i = 0; i < 10000; ++i) // COIN TOSS
if (rand() % 2 == 0)
++heads;
else
++tails;
total += abs(heads - tails);
}
}
cout << "The average distance between is " << total / 1000.0 << '\n';
cin.get();
return 0;
}

search a number in an unsorted array

I have a code that searches for a given entry in an array, and returns the position in the array of that entry, provided one knows the array contain that number. However, a strange thing happens. When I try to test the code with some concrete arrays, the code works well for some entries, and it does not work for others. The code is this:
#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
int a = (n/2);
int b = n;
int tmp = 0;
while (x != data[a])
{
if (x > data[a])
{
tmp = a;
a = (b+a)/2;
b = b;
}
if (x < data[a])
{
a = tmp;
b = a;
}
}
return a;
}
(in a previous version I was using the floor function to round the numbers contained in a to their integer parts, but I understand this is not necessary.)
I have tested the program for example for the following array in this main:
int main()
{
int n = 6; int x = 12;
int array1[] = {3,12,5,9,7,11};
cout << "The entry " << x << " is found at position "
<< 1+Find_entry(array1, n, x) << endl;
return 0;
}
When I type as in this example x=12, the program gives the correct answer 1. Same thing for x=3, x=11 and x=9. But if I type x=7 or x=5, the program refuses to give an output and I get a message like
"Process terminated with status -1073741510 (0 minute(s), 9 second(s))".
Can anybody explain what's the problem here? How can be the code fixed?? Thank you all for your answers.
You cannot use binary search for unsorted array. Use linear search.
int Find_entry(int data[], int n, int x)
{
int a = 0;
while (a < n && x != data[a]) a++;
return a;
}
Binary search only works on sorted inputs.

Trying to make a table that converts decimal to binary and ASCII C++

I have to make a table that shows the values 1 through 127 converted to binary and decimal like this:
Hexadecimal and Octal are optional.
Here's what I have so far:
using namespace std;
int main() {
int dec;
int binary_array [128];
for (dec = 0; dec<128; dec++){
for (int I =0; I < 7; i++){
binary_array[i]= dec % 2;
cout<<binary_array[i];
dec = dec / 2;
}
}
}
You can use bitset to convert decimal to binary and then print out the results.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
for(int i = 0; i <= 127; i++)
{
cout << i << " " << bitset<8>(i) << endl;
}
return 0;
}
EDIT:
Since using bitset is not an option, lets dissect your code and understand whats wrong with it.
using namespace std;
int main()
{
int dec;
int binary_array [128];
for (dec = 0; dec<128; dec++)
{
for (int I =0; I < 7; i++)
{
binary_array[i]= dec % 2; <--OK
cout<<binary_array[i]; <-- NOT OK, think carefully
dec = dec / 2; <-- OK
}
//now you have exited for loop, what is the value of dec?
//think what happened to dec in the second for loop
//your current logic will create a infinite loop
}
}
Your logic is on the right path and if you think carefully, you will be able to do it yourself and feel good about it instead of copying available solution without trying to learn what went wrong. I would suggest you to try to think hard and implement. If you still cannot solve it, feel free to post updated code and let us know.

Print out even number

I just want to ask your help here. I am new beginner in c++ programming. How to print out the even number in range 100 - 200. I tried write some code and it didn't work out. Here is my code. I hope, someone here can help me. Will appreciate that so much. Thanks.
include <stdio.h>
void main()
{
int i;
for (i= 100; i<= 200; i += 2){
print i;
}
}
Well, pretty simple:
#include <iostream> // This is the C++ I/O header, has basic functions like output an input.
int main(){ // the main function is generally an int, not a void.
for(int i = 100; i <= 200; i+=2){ // for loop to advance by 2.
std::cout << i << std::endl; // print out the number and go to next line, std:: is a prefix used for functions in the std namespace.
} // End for loop
return 0; // Return int function
} // Close the int function, end of program
you were using C libraries, not C++ ones, as well as no function that is called print in C++, nor C. Also there is no void main function, use int main() instead. finally, you need to have std:: in front of cout and endl as these lie in the std namespace.
Use the following code:
#include <iostream>
int main()
{
int i;
for (i= 100; i<= 200; i += 2){
std::cout << i << std::endl;
}
return 0;
}
Your code looks good....Only the printing part needs to be changed
#include <stdio.h>
int main()
{
for (int i= 100; i<= 200; i += 2){
printf("%d",i);
}
return 0;
}
This might help!
#include <iostream>
using namespace std;
int main()
{
for (int count = 100; count <= 200; count += 2)
{
cout << count << ", ";
}
cout << endl;
return 0;
}