C++ : Why it dont work? - c++11

I was trying to solve
In which you have given a array of int and you have to return its sum.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main(){
int n;
cin >> n;
int k;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
k = k + arr[arr_i];
//cout << "arr = " << arr[arr_i] << " k " << k << endl; // [0]
if (arr_i == (n-1))
{
cout << k;
}
}
return 0;
}
This return a afkard no. instead of sum.
But when uncomment out [0] line. code starts working as it should.
P.S. i found out the solution by changing cout to cerr.
but wanted to know why it doesn't work.

as the other answer, initialize k, move if outside of loop
vector<int> arr(n);
int k = 0;
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
k = k + arr[arr_i];
//cout << "arr = " << arr[arr_i] << " k " << k << endl; // [0]
}
cout << k;
as your question, there is no need std::vector anymore
int sum = 0, num;
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> num;
sum = sum + num;
}
std::cout << sum << std::endl;

Initialize k before you use, else it will contain junk value int k = 0;

As the other answers (+1) suggested, you need to initialize k. However, I think it is slightly better to assign it the first value initially and reduce the number of iterations therefore:
vector<int> arr(n);
if (n > 0) {
int k = arr[0];
for(int arr_i = 1;arr_i < n;arr_i++){
//Your cycle
}
}

Related

Printing the contents of a 2d Vector results without indexing each token as one

I'm attempting to print out the contents of a 2d vector in the same fashion in which they are initialized.
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<vector<int > > frontier = {{-1,0}, {1,0}, {0,-1}, {0,1}};
for (int i = 0; i < frontier.size(); i++) {
for (int j = 0; j < frontier[i].size(); j++) {
std::cout << frontier[i][j] << ", ";
}
}
cout << "End of frontier. " << endl;
/* This below is an implementation that I found online but found
no
* way to be able to implement the column reference.
*/
for (int i = 0; i < frontier.size(); ++i) {
for (int j = 0; j < col; ++j) {
cout << frontier[i + j * col] << ' ';
}
cout << endl;
}
}
This is to determine the contents of a 2d vector. So far, this code can print out every index separated by a comma. I, on the other hand, need to write code that will signify where a new vector begins.
output:
-1, 0, 1, 0, 0, -1, 0, 1,
expected output:
{{-1,0}, {1,0}, {0,-1}, {0,1}}
Here's how I might do it:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::string outerPrefix = "";
std::cout << "{";
for(const auto& outer : frontier)
{
std::cout << outerPrefix << "{";
std::string innerPrefix = "";
for(auto inner : outer)
{
std::cout << innerPrefix << inner;
innerPrefix = ",";
}
std::cout << "}";
outerPrefix = ", ";
}
std::cout << "}";
}
Output: {{-1,0}, {1,0}, {0,-1}, {0,1}}
In the first example I used a range-based for loop. If you're familiar with the concept of foreach in many languages it's basically the same thing. If you don't need an actual index variable it is safer because you don't have to worry about being off by one and indexing outside the container. It also works the same way on containers like map or set where you would need to use iterators rather than an index.
If you were to do the same thing with nested index loops like you had in your original it might look something like this:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::cout << "{";
for(size_t outer = 0; outer < frontier.size(); ++outer)
{
if (outer != 0)
{
std::cout << ", ";
}
std::cout << "{";
for(size_t inner = 0; inner < frontier[outer].size(); ++inner)
{
if (inner != 0)
{
std::cout << ",";
}
std::cout << inner;
}
std::cout << "}";
}
std::cout << "}";
}

C++ ScopeTimer doesn't work

I'm trying to implement a timer class which prints the time needed for a given scope. Somehow I can't get it to work properly. My code so far:
Main.cpp:
#include "scopetimer.hpp"
#include <cstdlib>
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
void work01()
{
double numbers[10000];
for (int i = 0; i < 10000; ++i)
{
numbers[i] = double(std::rand()) / double(RAND_MAX);
}
for (int n = 10000; n > 1; n = n - 1) {
for (int i = 0; i < n - 1; i = i + 1) {
if (numbers[i] > numbers[i + 1]) {
double tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = tmp;
}
}
}
}
void work02()
{
int* buf[1024];
for (int i = 2; i < 1024; ++i)
buf[i] = new int[i];
for (int i = 2; i < 1024; ++i)
delete[] buf[i];
}
// counts the number of primes in an interval
int work03(int n0, int n1)
{
int freq = n1 - n0 + 1;
for (int i = n0; i <= n1; ++i)
{
// Have fun: use the alternative iteration direction and see how fast
// it gets!
// for(int j = 2; j < i; ++j)
for (int j = i - 1; j > 1; --j)
{
if (i%j == 0)
{
--freq;
break;
}
}
}
return freq;
}
int main(int, char**)
{
{ ScopeTimer("work01");
work01();
}
{
ScopeTimer("work02");
work02();
}
{
ScopeTimer("work03");
work03(0, 10000);
}
std::cout << std::endl << "Tests" << std::endl << std::endl;
{
clock_t start_(std::clock());
work01();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work02();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work03(0,10000);
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
system("Pause");
}
scopetimer.cpp
#include "scopetimer.hpp"
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
ScopeTimer::ScopeTimer(const std::string& name)
:name_(name),
start_(std::clock()) {
}
ScopeTimer::~ScopeTimer() {
double elapsed = (double(std::clock() - start_) / double(CLOCKS_PER_SEC));
std::cout << name_ << ": " << int(elapsed) << "ns" << std::endl;
}
I tested the clock functions outside of ScopeTimer(), which works fine. So the only issues, as far as I can tell, is that I can't get ScopeTimer() to work. It always prints 0ns. I mostly followed the turorial: https://felix.abecassis.me/2011/09/cpp-timer-raii/
Kind regards
In ~ScopeTimer() you print how many complete seconds have passed not how many nanoseconds, while in the second part of main, you print the number of clock ticks, which may or may not be the same as a nanosecond.
I came across the same problem
The solution for me is to define a ScopeTimer instance instead of just call its constructor, I mean:
{
ScopeTimer _scopetimer("work01");
work01();
}
That should work
I guess compiler seems to ignore (optimize) that, 'cause when you just call ScopeTimer("work01").

Can somebody tell me what this sorting algorithm is called?

So my teacher told me about the bubble sorting technique and it looks like it runs too many times, so I came up with this, I'm fairly sure that it's already been made and I want to know what it's called.
Here it is:
#include <iostream>
using namespace std;
int main()
{
int n, k = 0, i, min, aux;
cout << "N:";cin >> n;
int v[n];
for(i=0;i<n;i++)
cin >> v[i];
do{
for(i=k;i<n;i++){
if(i==k)
min = i;
if(v[i] < v[min])
min = i;
}
aux = v[k];
v[k] = v[min];
v[min] = aux;
k ++;
}while(k<n-1);
cout << "\n";
for(i=0;i<n-1;i++){
cout << v[i] << ",";
}
cout << v[n-1] << ".";
}
This is called selection sort. Good job coming up with it on your own, you can read about it here.

Pairs x,y verify equation

I have to build a program as bellow:
User enters 3 Integers: a, b, c
User enters one integer n, and then n integers (ascending, and different numbers)
Program checks all possible pairs (x,y) (with x!=y) of the numbers entered if verifies the equation ax^2 + by^2 = c and prints all pairs which verifies the equation.
I done the program as bellow:
#include<iostream>
using namespace std;
int main() {
int a,b,c,n,i,j;
cin >> a;
cin >> b;
cin >> c;
cin >> n;
int num[n];
for(i=0;i<n;i++) {
cin >> num[i];
}
for (i=0;i<n;i++)
for (j=i+1;j<n;j++) {
if(a*num[i]*num[i]+b*num[j]*num[j] == c) {
cout << "(" << num[i] << "," << num[j] << ")";
}
if(a*num[j]*num[j]+b*num[i]*num[i] == c) {
cout << "(" << num[j] << "," << num[i] << ")";
}
}
return 0;
}
I made it by O(nlogn) with two 'for' statements but i know it could be done by O(n).
NOTE THAT MY PROGRAM WORKS AND I DON'T NEED TO ADD EXPECTED OUTPUT AND MY CURRENT OUTPUT AS YOU SAID IN THE COMMENTS. I ONLY WANT IT TO BE O(N) not O(nlogn) -> I WANT AN OPTIMIZED VERSION OF THE CODE!
How can I do this?
Example of running program: a=1, b=1, c=20
Then n = 5
Then n numbers: 2 3 4 9 18
Program will show all pairs (x,y) which verifies the equation x^2 + y^2 = 20. In this case it shows (2,4)
and (4,2).
Thank you!
Assuming 0 based index...
Set i=0
Set j=n-1
While i<n or j>=0
Set sum=a(num[i]^2)+b(num[j^2)
If sum==c then found pair, and increase i
If sum<c increase i
If sum>c decrease j
I found exactly this problem solved here: http://lonews.ro/educatie-cultura/22899-rezolvare-admitere-universitatea-bucuresti-2015-pregatire-informatica.html and changed a bit to show the pairs (it originally shows the number of pairs).
#include <iostream>
using namespace std;
int main()
{
int a, b, c, n, i=0;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "n = ";
cin >> n;
int s[n];
for(i=0; i<n; i++) {
cout << "s[" << i+1 << "] = ";
cin >> s[i];
}
int j=n-1;
i = 0;
while(j>=0 || i<n) {
if(a*s[i]*s[i] + b*s[j]*s[j] == c) {
cout << "(" << s[i] << "," << s[j] << ") ";
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] < c) {
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] > c) {
j--;
}
}
return 0;
}

Parallel Matrix Multiplication in C++

I am trying to implement Parallel Multi-threaded Matrix multiplication in C++. The method i follow involves dividing Arrays into 4 sub-arrays and carry out parallel Multiplication using 4 threads on these 4 sub arrays.
I have written a C++ code but it is throwing error and terminates explicitly. Error :
"terminate called after throwing an instance of std::system_error
what():invalid Argument"
Here is my complete code. I am relatively new to C++ and multi-threading.
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
#include <string>
#define N 4
using namespace std;
mutex mu;
void stage_1_multiply(int *a,int *b,int *d){
int *xij;
int *yij;
int *zij;
int COLS = N,ROWS = N;
cout<< " thread "<< this_thread::get_id() << " "<<endl;
for(int i = 0;i<(N/2);++i){
for(int j = 0;j < (N/2); j++){
for(int k = 0; k<(N/2);k++){
mu.lock();
xij = a + ((COLS * i) + k);
yij = b + ((COLS * k) + j);
zij = d + ((COLS * i) + j);
*zij += ( (*xij) * (*yij) );
mu.unlock();
}
}
}
}
int main(){
int A[4][4],B[4][4],C[4][4],D_1[4][4],D_2[4][4];
for(int i = 0;i<4;i++){
for(int j = 0;j<4;j++){
A[i][j] = i + 1;
B[i][j] = i + 1;
C[i][j] = 0;
D_1[i][j] = 0;
D_2[i][j] = 0;
}
}
for(int i = 0;i<4;i++){
for(int j = 0;j< 4;j++){
cout << A[i][j] << " ";
}
cout << endl;
}
for(int i = 0;i<4;i++){
for(int j = 0;j< 4;j++){
cout << B[i][j] << " ";
}
cout << endl;
}
vector< thread> threads(8);
int th = 0;
threads[th++] = thread(stage_1_multiply,&A[0][0],&B[0][0],&D_1[0][0]);
threads[th++] = thread(stage_1_multiply,&A[0][2],&B[2][0],&D_2[0][0]);
threads[th++] = thread(stage_1_multiply,&A[2][0],&B[0][2],&D_1[2][2]);
threads[th++] = thread(stage_1_multiply,&A[2][2],&B[2][2],&D_2[2][2]);
for( auto& t : threads){
t.join();
}
threads[th++] = thread(stage_1_multiply,&A[0][0],&B[0][2],&D_1[0][2]);
threads[th++] = thread(stage_1_multiply,&A[0][2],&B[2][2],&D_2[0][2]);
threads[th++] = thread(stage_1_multiply,&A[2][0],&B[0][0],&D_1[2][0]);
threads[th++] = thread(stage_1_multiply,&A[2][2],&B[2][0],&D_2[2][0]);
for( auto& t : threads){
t.join();
}
// code to add The Matrices D_1 and D_2 goes here.
for(int i = 0;i<4;i++){
for(int j = 0;j< 4;j++){
cout << D_1[i][j] << " ";
}
cout << endl;
}
cout << " Main Close "<<endl;
return 0;
}
What am doing wrong? is it anything related to parallel access of shared memory? If so how can i correct it?
PS: This is a homework Assignment.

Resources