I am working through Andrew Koenig's Accelerated C++, and one of the exercises asks to write a program to output two columns, one of integers up to some maxInt and the other of their squares. Here is my code:
#include <iostream>
#include <iomanip>
#include <string>
using std::cout;
using std::endl;
using std::setw;
using std::to_string;
using std::string;
int square(const int n)
{
return n*n;
}
int main()
{
// loop until maxInt
const int maxInt = 1000;
// use the length of maxInt and its square to comptue width later on
const int maxIntSize = to_string(maxInt).length();
const int maxIntSquareSize = to_string(square(maxInt)).length();
for (int i = 1; i != maxInt + 1; ++i) {
const int j = square(i);
// we need iSize to compute the width
const int iSize = to_string(i).length();
const int width = maxIntSize + maxIntSquareSize + 1 - iSize;
cout << i << setw(width) << j << endl;
}
return 0;
}
My problem is that the program is inconsistent. Sometimes it works as I expect, other times it stops printing prematurely. Furthermore, when it doesn't do what I expect, the behavior is rather unpredictable. Could anyone let me know what I'm doing wrong?
(Also, I am new to C++, so any general advice is appreciated.)
Related
I am a beginner at using C++ so I was wondering if someone would be able to help me out as I'm currently trying to print a 'for' loop. The 'alfa' loop is printing correctly but when that information is called upon by the 'sina' loop, only zeros are being printed in the console.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <new>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
const double convToRad = pi/180.0;
int main(){
int INDEX = 91;
double alfa[INDEX] {0};
double sina[INDEX] {0};
for (int p = 90; p >= 0; p--){
alfa[INDEX] = p*convToRad;
//std::cout << alfa[INDEX] << std::endl;
}
for (int e = 0; e <= 90; e++){
sina[INDEX] = sin(alfa[INDEX]);
std::cout << sina[INDEX] << std::endl; //only prints 0's
}
return 0;
}
Your are accessing wrong memory location.
INDEX=91;
You had typed INDEX instead of p and e in both the loops.
So accessing a single wrong location which may gives a junk value or crash the program.
A few notes:
Don't use magical numbers, use constants.
Don't use the numbers in the array which are constant as you did.
Try a simple fix:
for (int p = 0; p < INDEX; p++) {
// storing 90* stuff in first index, 89* in second and so on...
alfa[p] = (90 - p) * convToRad;
// std::cout << alfa[p] << std::endl;
}
for (int e = 0; e < INDEX; e++) {
sina[e] = sin(alfa[e]);
std::cout << sina[e] << std::endl;
}
There is a task. It is necessary in a one-dimensional array of N real numbers to calculate the number of the maximum modulo element among unpaired numbers.
I wrote the code, but it does not work. I can’t understand what’s wrong with him.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
setlocale(0, "");
const int KolEl = 5;
int mas[KolEl];
int max = abs(mas[0]);
int result;
for (int i = 0; i < KolEl; i++)
{
cout << " Введите елемент[" << i << "] = ";
cin >> mas[i];
if (mas[i] % 2 == 1) {
if (abs(mas[i]) > max) {
result = i;
cout << result << endl;
}
}
}
system("pause");
}
You initialize max as:
int mas[KolEl];
int max = abs(mas[0]);
However, the values in mas[] are garbage values (read: undefined behavior). So now the value in max is also UB.
You then go on to use that value to compare to the input you take:
if (abs(mas[i]) > max) {
So the result of that comparison is undefined.
You probably meant to declare max as something like:
int max = INT_MIN;
So that the first comparison will always be true (every int except INT_MIN will be greater than it).
Unable to understand the unexpected output. The pointer doesn't point to the 0th index no. of a string
I have been trying to find the reason for the output of the following program. the loop starts from i=0 but there is no character being displayed at the 0th index no. and the loop starts from the 1st index no.
#include <conio.h>
#include <iostream.h>
#include <string.h>
int main()
{
clrscr();
int i, n;
char *x = "Alice";
n = strlen(x);
*x = x[n];
for (i = 0; i <= n; i++)
{
cout << x;
x++;
}
cout << endl << x;
getch();
}
I am getting the following output: liceicecee
But I expected the output to start from 'A'.
You should really upgrade to a modern compiler. There are many free ones available.
#include <iostream.h> // non-standard header file
#include <string.h> // not recommended - it brings its functions into the global namespace
void main() { // main must return "int"
int i, n;
char* x = "Alice"; // illegal, must be const char*
n = strlen(x);
*x = x[n]; // illegal copy of the terminating \0 to the first const char
for(i = 0; i <= n; i++) { // <= includes the terminating \0
cout << x; // will print: "", "lice", "ice", "ce", "e", ""
// since you move x forward below
x++;
}
cout << endl << x; // x is now pointing after the \0, undefined behaviour
}
If you want to print the letters one by one (using your current program as a base) using standard C++:
#include <iostream>
#include <cstring>
int main() {
const char* x = "Alice";
size_t n = std::strlen(x);
for(size_t i = 0; i < n; ++i, ++x) {
std::cout << *x; // *x to dereferece x to get the char it's pointing at
}
std::cout << "\n"; // std::endl is overkill, no need to flush
}
What strlen does is to search for the first \0 character and to count how long it had to search. You really don't need to do that here since you are going through all the characters (by stepping x) yourself. Illustration:
#include <iostream>
int main() {
const char* x = "Alice";
size_t n = 0;
while(*x != '\0') {
std::cout << *x;
++x;
++n;
}
std::cout << "\nThe string was " << n << " characters long\n";
}
I'm working on a function that finds the smallest element in an array. I'm trying to modify the variable s using pass by reference. I'm brand new to C++ and I'm not sure if I have done pass-by-reference correctly. Can anyone confirm that this is the correct way to do this, or suggest better ways to approach a min value function with pass by reference?
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
using namespace std;
int smallestElm(int numArray[], int length, int &smallest);
int main() {
int n[3] = {2,5,3};
int s = 0;
int length = 0;
cout << smallestElm(n, length, s) << endl;
}
int smallestElm(int numArray[], int length, int &smallest) {
smallest = numArray[0];
length = sizeof (numArray) / sizeof (int);
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
return 0;
}
}
Yes this is correct, as you should be able to tell by yourself, by modifying your main function like this:
int main() {
int s = 0;
// call your function
cout << s << endl; // Here you print 's', thus you confirm whether you are right or not
}
If s wouldn't change its value, then your pass by reference won't be correct (since s does change its value inside the body of the function).
As for the function, it's wrong, since it will return before checking all the elements! So, change that to something like this to check all the elements of the array before saying for certain which the smallest element is:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int &smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int &smallest) {
smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
}
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
2
2
smallest element = 2
Don't forget that STL provides min_element, that you could use like this:
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int n[] = {2,5,3};
int *s = std::min_element(n, n + 3); // 3 size of the array
cout << "smallest element = " << *s << endl;
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
smallest element = 2
Can anyone confirm that this is the correct way to do this
Yes, that is the correct way to declare a reference argument. And yes, you can modify objects through a reference.
or suggest better ways to approach a min value function ...
A better way would arguably be to return the min value, instead of modifying an argument. Right now the function always returns 0, which seems useless.
... with pass by reference
That's a silly idea, but your approach is correct way to pass by reference. The function itself has multiple bugs.
It seems to always return after the first iteration, so it'll always find one of the first 2 element to be "smallest".
The value of int length argument is never used. It is overridden before use.
sizeof (numArray) returns the size of the pointer numArray which is not in any way related to the size of the pointed array.
The function always uses numArray[0] so it will have undefined behaviour if length == 0.
It's correct your code, but there is another way: Using a pointer to int, into the function argument and invoke this with the address of memory of variable s, as the below sample shows:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int *smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, &s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int *smallest) {
*smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < *smallest) {
*smallest = numArray[i];
}
cout << *smallest << endl;
}
}
In an effort to code the briefest solution I could for an approximation of the integral using Riemann sums, I ran into a strange problem: if the user requested a partition count in excess of 10, the program failed. Any thoughts? Here's the code:
// The Integral
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <iomanip>
using std::cin; using std::cout;
using std::endl;
int func (int x);
int main ()
{
cout << "Please enter left and right bounds: ";
int left, right;
cin >> left >> right;
cout << "Please enter a # of partitions (>0): ";
int R;
cin >> R;
int width = (right - left) / R;
int total = 0;
for (int i = 0; i < R; ++i) {
total += func(left + width*i);
}
cout << "The integral is: " << total << endl;
return 0;
}
int func (int x)
{
return x*x;
}
Using a partition size of greater than 10 is not your actual problem.
Your are using integers for your variables and function return value, when you should be using float or double.
For instance:
int width = (right - left) / R;
If (right - left) < R width will be zero!
on a side note, unless you plan on expanding this small prog, you're including way to many useless stuff. this is all you'd need for this prog:
#include <iostream>
#include <cstdio>
using namespace std;
int func (int x)
{
return x*x;
}
int main()
{
// if you have your main() at the bottom, you dont have to declare other functions on top.
}
cheers :)
Another comment:
In my opinion the for-loop in your code does not compute the correct Riemann-sum.
I think it should look like this:
for (int i = 0; i < R; i++) {
total += func(left) * width;
left += width;
}
Cheers :)