Why I can not see output in cycle (C++ simple code)? - c++

I would like to edit numbers in p2 according to the code in for cycle.
But If I try to write out actual number in p2, I donĀ“t see anything in output.
What could I change to see it?
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i; i >0; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}

As pointed out by Ilya, you need to change the condition in the for loop. Right now, at the beginning of the for loop, i = 0, so the for loop never starts. Change it to the following:
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}

Since you did not initialize the value of i it takes the random value that is stored in its location.
So just make i 0 and loop it through until 10.
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
return 0;
}

Because you didn't initialize the i variable, it takes a random number of type int, causing the loop to misbehave. You need to make i=0 for it to work correctly.
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i=0; i < sizeof(p1)/sizeof(p1[0]); i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
sizeof(p1)/sizeof(p1[0]) is count of array elements.

Related

How do I print out a simple array with numbers 0-99 on the console

I'm new to CS and I'm stuck on a practice problem in arrays where I have to print out an array with numbers 0-99 onto the console. My code right now seems to just create the numbers and print them but not actually put them in the array. I'm just curious how to actually set the elements to the array and then print them because that's the only thing holding me back from finishing the rest of the problem.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = 0;
cout << num << endl;
}
Looks like you are very close! You just need to assign the value of 'i' into your array slot. Hope this helps!
EDIT:
To print the contents of the array you need to iterate back over the array and print each array element.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = i; //assign value of 'i' to array slot
//print array elements
for (int i = 0; i < 100; i++)
cout << num[i]<< endl;
}
read the correct carefully:
#include <iostream>
#include <cstdio> // its C++ equivalent
using namespace std;
int main() {
int num[100];
for (int i = 0; i < 100; ++i)
num[i] = i;
for (int i = 0; i < 100; ++i)
cout << "num[" << i << "]" << num[i] << endl;
}

Why does this code output before even reading input?

My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}
You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.
There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.

Size of a vector of pairs

I am filling up an adjacency list of vector with pairs given by :
vector<pair<int, int>> adj[1000];
I am doing a depth first search on the list but experiencing some weird behaviour. The first print statement prints some value which means I have some items in adj[s][0], adj[s][1], adj[s][2] and so on. However when I calculate the size of adj[s] in the next line it prints out to be zero. Am I missing something here?. Is my definition for vector of pairs correct?. The adjacency list is correctly filled because when I ran cout << adj[s][0].first << endl; in dfs, it was correctly showing me the neighbors of each and every node.
Complete code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <climits>
#include <algorithm>
using namespace std;
vector<pair<int, int>> adj[1000];
bool visited[1000];
int nodeweight[1000];
void initialize()
{
for(int i = 0; i < 1000; i++)
visited[i] = false;
for(int i=0; i < 1000; i++)
adj[i].clear();
for(int i = 0; i <1000; i++)
nodeweight[i] = INT_MAX;
}
void dfs(int s)
{
visited[s] = true;
cout << adj[s][1].first << endl;
int minimum = INT_MAX, tovisit = 0;
for(int i = 0; i < adj[s].size(); i++)
{
cout << adj[s][i].second;
if(!visited[adj[s][i].first] && adj[s][i].second < minimum)
{
minimum = adj[s][i].second;
tovisit = adj[s][i].first;
}
}
nodeweight[tovisit] = minimum;
//dfs(tovisit);
}
int main() {
int N, E;
cin >> N >> E;
while(E--)
{
int i, j, w;
cin >> i >> j >> w;
adj[i].push_back(make_pair(j,w));
adj[j].push_back(make_pair(i,w));
}
initialize();
for(int i = 1; i <= N; i++)
{
dfs(i);
}
return 0;
}
You are clearing adj again after filling in initialize().
First you fill adj in the while loop in main. Then you call initialize() which includes this loop clearing all vectors in it:
for(int i=0; i < 1000; i++)
adj[i].clear();
Then you have cout << adj[s][1].first << endl; in dfs which is undefined behavior because there are no elements in adj[s]. The fact that you seem to get the correct results is just coincidental undefined behavior (although practical it is because the memory holding the vector data was not cleared.)
adj[s].size() is correctly reported as 0.

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.
You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array

Getting bizarre issue with variables outside the main method?

I have some global variables defined just above my main method. When I try to call the function "fib()" while using those variables, I get incorrect results.
When I move the variables into the local scope of the function, I get correct results.
Why does this happen? Here is the correct code:
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
int sum = 0;
int fib1 = 1;
int fib2 = 0;
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
The incorrect code has the three variables "sum", "fib1", and "fib2" above the main method. Why does this not work, but declaring the variables inside the function does?
Edit: below is the incorrect code. Note that the only difference is the placement of the variables.
using namespace std;
#include <iostream>
#include <vector>
vector <int> fibVals;
int fibInput;
int fib(int n);
int sum = 0;
int fib1 = 1;
int fib2 = 0;
int main()
{
cout << "Please enter 3 Fibonacci numbers you wish to find:: \n";
for(int i = 0; i < 3; i++)
{
cin >> fibInput;
fibVals.push_back(fibInput);
}
cout << "The values at those Fibonacci numbers are(in order)::\n";
for(int i = 0; i < 3; i++)
{
cout << fib( fibVals[i] ) << "\n";
}
return 0;
}
int fib(int n)
{
if (n == 0 || n == 1)
return n;
for(int i = 2; i <= n; i++)
{
sum = fib1 + fib2;
fib2 = fib1;
fib1 = sum;
}
return sum;
}
I understand the concept of scope. I thought that making those three variables global(outside main) would make no difference than if they were made local(inside fib() ).
You should try to make your question clearer. Nevertheless I will take a shot in the dark and try to respond to what I believe your question is. Think what happens if you move sum, fib1, and fib2 outside the function fib(), in other words you make them global. They will keep their value across function invocations (technically, they have static storage duration). Hence, when you invoke fib() the second time, sum will be equal to the previous value returned by fib(). However, when you put them inside the function, they are local to that scope, and at each function invocation they start "fresh" and are re-initialized (technically they have automatic storage duration).