How can I use variable value to give space [duplicate] - c++

I was wondering how can I do it ,to print certain number of spaces using printf in C
I was thinking something like this,but also my code doesn't print after the first printf statement,my program compiles perfectly fine tho.I'm guessing I have to print N-1 spaces but I'm not quite sure how to do so.
Thanks.
#include <stdio.h>
#include <limits.h>
#include <math.h>
int f(int);
int main(void){
int i, t, funval,tempL,tempH;
int a;
// Make sure to change low and high when testing your program
int low=-3, high=11;
for (t=low; t<=high;t++){
printf("f(%2d)=%3d\n",t,f(t));
}
printf("\n");
if(low <0){
tempL = low;
tempL *=-1;
char nums[low+high+1];
for(a=low; a <sizeof(nums)/sizeof(int);a+5){
printf("%d",a);
}
}
else{
char nums[low+high];
for(a=low; a <sizeof(nums)/sizeof(int);a+5){
printf("%d",a);
}
}
// Your code here...
return 0;
}
int f(int t){
// example 1
return (t*t-4*t+5);
// example 2
// return (-t*t+4*t-1);
// example 3
// return (sin(t)*10);
// example 4
// if (t>0)
// return t*2;
// else
// return t*8;
}
the output should be something like this:
1 6 11 16 21 26 31
| | | | | | |

Printing n spaces
printf has a cool width specifier format that lets you pass an int to specify the width. If the number of spaces, n, is greater than zero:
printf("%*c", n, ' ');
should do the trick. It also occurs to me you could do this for n greater than or equal to zero with:
printf("%*s", n, "");
Printing 1, 6, 11, ... pattern
It's still not fully clear to me what you want, but to generate the exact pattern you described at the bottom of your post, you could do this:
for (i=1; i<=31; i+=5)
printf("%3d ", i);
printf("\n");
for (i=1; i<=31; i+=5)
printf(" | ");
printf("\n");
This outputs:
1 6 11 16 21 26 31
| | | | | | |

Had your objective been :
Start printing at a specified width using printf
You could achieve it like below :
printf("%*c\b",width,' ');
Add the above stuff before printing actual stuff, eg. before a for-loop.
Here the \b positions the cursor one point before the current position thereby making the output appear to start at a particular width, width in this case.

Related

How can I use logarithms to get the opposite of power?

I was never good at maths in school and I realized that I actually need the opposite of pow(base, exponent) functions which powers some number by some factor like 2 ^ 4 = 16
Searching for answers I found that logarithm log() should be the opposite of power.
Now, I've found that to write e.g. "log 2 of 32" would in code look like log(32) / log(2)... but how do you translate this following problem into logarithm?
I'm going to write a quick C program to print index table where all alphabetical characters are going to be printed assigned to each index starting from 0 to 26 ^ DIGITS.
Assuming DIGITS are set to 1, table will only be of size 26 (the length of alphabet from A to Z) in format index[0] = A, index[1] = B, ... ... index[25] = Z.
The count of DIGITS gives 26 ^ DIGITS combinations.
Now, I have this code already written:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
unsigned int letterToIndex(char c);
char indexToLetter(unsigned int index);
int main(void)
{
printf("Printing Index table:\n\n");
const int DIGITS = 2;
const int ALPHABSIZE = 26;
int currentIdx = 0; // current index
const int endIndex = pow(ALPHABSIZE, DIGITS);
// this should be
//double bit5 = log(32) / log(2);
//printf("log(32) / log(2) AKA bit^5 should be: %f", bit5);
while (currentIdx < endIndex)
{
printf("index[%i] = ", currentIdx);
/*for (int i = 0; i < DIGITS; ++i)
{
//float logarithm = log( (currentIdx / ALPHABSIZE) % ALPHABSIZE ) / log(DIGITS);
float logarithm = log( currentIdx % ALPHABSIZE ) / log(DIGITS);
printf("%c", indexToLetter( (int) logarithm ));
}*/
// letter
//unsigned int idxLetter = letterToIndex(i) * ALPHABSIZE + letterToIndex(i+1);
///////////////////////////////////////////////////////////////////////////////
// I have an obvious pattern here vv
// here I print only 2 digits hard-coded
// prints the 1st digit
printf("%c", indexToLetter( (currentIdx / ALPHABSIZE) % ALPHABSIZE ));
// prints the 2nd digit
printf("%c", indexToLetter( currentIdx % ALPHABSIZE ));
// obvious pattern ^^
//////////////////////////////////////////////////////////////////////////////
printf("\n");
currentIdx++;
}
// if DIGITS are only 1 sized:
// index[0] = A
// index[1] = B
// index[2] = C
// index[3] = D
// index[4] = E
// ... ... ...
// index[25] = Z
// DIGITS having size of 2:
// index[0] = AA
// index[25] = AZ
// index[26] = BA = index[ 1 * 26 + 0 ] = index[26]
// index[30] = BE = index[ 1 * 26 + 4 ] = index[30]
// ... ... ...
// index[107] = ED = index[ 4 * 26 + 3 ] = index[107]
return 0;
}
// maps the ASCII range from 'A' = 0 to 'Z' = 25
unsigned int letterToIndex(char c)
{
return toupper(c) - 'A';
}
// get any letter from 0 to 25: from 'A' to 'Z'
char indexToLetter(unsigned int index)
{
return toupper(index + 65);
}
I've commented out the for loop inside the main (inside the while block), and this time hardcoded to printf currentIdx's first digit and then its second digit at each iteration in the while loop.
But it strikes me like it's asking for a logarithm... How can I automate this in the for loop? Instead of having two printf lines, I'm pretty much convinced these two lines:
printf("%c", indexToLetter( (currentIdx / ALPHABSIZE) % ALPHABSIZE ));
printf("%c", indexToLetter( currentIdx % ALPHABSIZE ));
could be put into one line with the right (maybe logarithm?) solution. If it was DIGITS size 1, only the 2nd line would apply. DIGITS of size 3 requires opposite of power to 3. It's clearly power to DIGITS.
But what to make out of this pattern in a loop? Let's say const int DIGITS (that's currently set to 2) could be changed to be higher. How to make it dynamic so that it'll combine the alphabet for every digit?
You can start with pow(ALPHABSIZE, DIGITS - 1) and use integer division to get each place value/table index. On each loop you successively reduce by a factor of ALPHABSIZE down to 1. This lets you output left to right.
Logarithms are not necessary to compute here. To compute an integer logarithm you could nevertheless just count the number of passes through a while/for loop in the same fashion.

C++ strcat creating infinite loop

Im trying to create an array and each object in the array should have the name Model(i) where is is index, Im doing this so they will have the names indexed in descending order Model5, Model4 ... Im trying to do that using char[] but for some reason in my code the use of strcat inside of for loop make me get stuck on an infinite loop, the second point if someone could help is convert the index in a way that I could concatenate with the name and give to the constructor.
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
class CARRO {
public:
CARRO() {};
CARRO(char *modelo, unsigned ano);
char* getModelo();
unsigned getAno();
private:
char modelo[100];
unsigned ano;
};
void swap(int *p, int *q);
int partition(int *v, int start, int end);
int randomizedPartition(int *v, int start, int end);
void qsHelper(int *v, int start, int end);
void quickSort(int *v, int len);
void printList(CARRO *carros, unsigned len);
int main(int argc, char const *argv[]) {
CARRO carros[5];
unsigned len = sizeof(carros)/sizeof(CARRO);
for (int i = 0; i < len; ++i) {
char modelo[] = "Modelo";
char id[] = "I";
strcat(modelo, id);
unsigned ano = 1000 * (i+1);
carros[i] = CARRO(modelo, ano);
cout << carros[i].getModelo() << endl;
}
//printList(carros, len);
return 0;
}
CARRO::CARRO(char *modelo, unsigned ano) {
strcpy(this->modelo, modelo);
this->ano = ano;
}
If I remove the line :
strcat(modelo, id);
The loop works fine. I just cant understand why strcat is somehow generating an infinite loop. the output is this: (with the line strcat)
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
ModeloI
^CModeloI
The loop works fine. I just cant understand why strcat is somehow generating an infinite loop. the output is this: (with the line strcat)
The loop doesn't work fine! You are trashing memory. Let's make some boxes to represent the stack as might be seen by your program (let's assume the loop has just gone around to 1):
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| char modelo[7] | int i | unsigned len |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 'M' | 'o' | 'd' | 'e' | 'l' | 'o' | 0 | 1 | 0 | 0 | 0 | 5 | 0 | 0 | 0 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
So when you do this:
strcat( modelo, id );
You end up with a buffer overrun by one byte. In my particular example, this writes over the first byte of the variable i, thus causing your loop to continue indefinitely:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| char modelo[7] | int i |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 'M' | 'o' | 'd' | 'e' | 'l' | 'o' | 'I' | 0 | 0 | 0 | 0 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
^^^^^
Nul-terminator written
Of course, I have laid out your stack like this purely as an example. Your compiler might not keep the stack together like this. There might be extra padding after your array and it might just happen to "work". The variable i might be held in a register and never in memory, or the compiler might have unrolled the loop completely. Your architecture might be big-endian (instead of little-endian as in my example).
The point is, the resulting behaviour is completely undefined. We cannot look at this code and say what will happen, even if you get consistent results on your machine.
So to fix this, you can simply make modelo large enough to store the string "ModeloI" including the terminator, which means making it large enough to store 8 bytes instead of 7:
char modelo[8] = "Modelo";
Then you'll have defined behaviour, regardless of whether the stack is laid out as below or any other way:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| char modelo[8] | int i |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 'M' | 'o' | 'd' | 'e' | 'l' | 'o' | 'I' | 0 | 1 | 0 | 0 | 0 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+

Function A calls function B that calls function A, what do you call that?

I know that when function calls themselft, it's called recursion. But how do you call when function A calls function B that calls A until there is an IF statement that stops whole proces. Look at this exercise from one C book(and by the way could I solved this better?)
Write a function that displays a menu of four numbered choices and
asks you to choose one. (The output should look like the preceding.)
Write a function that has two int arguments: a lower limit and an
upper limit. The function should read an integer from input. If the
integer is outside the limits, the function should print a menu again
(using the function from part "a" of this question) to reprompt the
user and then get a new value. When an integer in the proper limits is
entered, the function should return that value to the calling
function.
Write a minimal program using the functions from parts "a" and "b" of
this question. By minimal, we mean it need not actually perform the
actions promised by the menu; it should just show the choices and get
a valid response.
#include <stdio.h>
void Display(void);
int Limits(int a, int b);
int main(void)
{
Display();
return 0;
}
void Display()
{
int y = 0;
printf("1 - 2 - 3 - 4\n");
y = Limits(0, 100);
if(y < 100 && y > 0)
printf("%d\n", y);
}
int Limits(int a, int b)
{
int x;
scanf("%d", &x);
if(x < a || x > b)
Display();
return x;
}
OUTPUT:
1 - 2 - 3 - 4
1234
1 - 2 - 3 - 4
34456
1 - 2 - 3 - 4
123
1 - 2 - 3 - 4
-34
1 - 2 - 3 - 4
-23
1 - 2 - 3 - 4
88
88
Press [Enter] to close the terminal ...
That's called mutual recursion or (less often) cross recursion.
As far as how to solve it cleanly, it sounds to me like it fits roughly with a pattern like:
namespace {
int show_menu() {
printf("1 - 2 - 3 - 4");
int n;
std::cin >> n;
return n;
}
}
int menu() {
int value;
do {
value = show_menu();
} while (value <1 || value > 4);
return value;
}

Fibonacci series in C++ : Control reaches end of non-void function

while practicing recursive functions, I have written this code for fibonacci series and (factorial) the program does not run and shows the error "Control reaches end of non-void function" i suspect this is about the last iteration reaching zero and not knowing what to do into minus integers. I have tried return 0, return 1, but no good. any suggestions?
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <ctime>
using namespace std;
int fib(int n) {
int x;
if(n<=1) {
cout << "zero reached \n";
x= 1;
} else {
x= fib(n-1)+fib(n-2);
return x;
}
}
int factorial(int n){
int x;
if (n==0){
x=1;
}
else {
x=(n*factorial(n-1));
return x;
}
}
Change
else if (n==1)
x=1;
to
else if (n==1)
return 1;
Then fib() should work for all non-negative numbers. If you want to simplify it and have it work for all numbers, go with something like:
int fib(int n) {
if(n<=1) {
cout << "zero reached \n";
return 1;
} else {
return fib(n-1)+fib(n-2);
}
}
"Control reaches end of non-void function"
This is a compile-time warning (which can be treated as an error with appropriate compiler flags). It means that you have declared your function as non-void (in this case, int) and yet there is a path through your function for which there is no return (in this case if (n == 1)).
One of the reasons that some programmers prefer to have exactly one return statement per function, at the very last line of the function...
return x;
}
...is that it is easy to see that their functions return appropriately. This can also be achieved by keeping functions very short.
You should also check your logic in your factorial() implementation, you have infinite recursion therein.
Presumably the factorial function should be returning n * factorial(n-1) for n > 0.
x=(factorial(n)*factorial(n-1)) should read x = n * factorial(n-1)
In your second base case (n == 1), you never return x; or 'return 1;'
The else section of your factorial() function starts:
x=(factorial(n)*factorial(n-1));
This leads to infinite recursion. It should be:
x=(n*factorial(n-1));
Sometimes, your compiler is not able to deduce that your function actually has no missing return. In such cases, several solutions exist:
Assume
if (foo == 0) {
return bar;
} else {
return frob;
}
Restructure your code
if (foo == 0) {
return bar;
}
return frob;
This works good if you can interpret the if-statement as a kind of firewall or precondition.
abort()
(see David Rodríguez's comment.)
if (foo == 0) {
return bar;
} else {
return frob;
}
abort(); return -1; // unreachable
Return something else accordingly. The comment tells fellow programmers and yourself why this is there.
throw
#include <stdexcept>
if (foo == 0) {
return bar;
} else {
return frob;
}
throw std::runtime_error ("impossible");
Not a counter measure: Single Function Exit Point
Do not fall back to one-return-per-function a.k.a. single-function-exit-point as a workaround. This is obsolete in C++ because you almost never know where the function will exit:
void foo(int&);
int bar () {
int ret = -1;
foo (ret);
return ret;
}
Looks nice and looks like SFEP, but reverse engineering the 3rd party proprietary libfoo reveals:
void foo (int &) {
if (rand()%2) throw ":P";
}
Also, this can imply an unnecessary performance loss:
Frob bar ()
{
Frob ret;
if (...) ret = ...;
...
if (...) ret = ...;
else if (...) ret = ...;
return ret;
}
because:
class Frob { char c[1024]; }; // copy lots of data upon copy
And, every mutable variable increases the cyclomatic complexity of your code. It means more code and more state to test and verify, in turn means that you suck off more state from the maintainers brain, in turn means less maintainer's brain quality.
Last, not least: Some classes have no default construction and you would have to write really bogus code, if possible at all:
File mogrify() {
File f ("/dev/random"); // need bogus init
...
}
Do not do this.
There is nothing wrong with if-else statements. The C++ code applying them looks similar to other languages. In order to emphasize expressiveness of C++, one could write for factorial (as example):
int factorial(int n){return (n > 1) ? n * factorial(n - 1) : 1;}
This illustration, using "truly" C/C++ conditional operator ?:, and other suggestions above lack the production strength. It would be needed to take measures against overfilling the placeholder (int or unsigned int) for the result and with recursive solutions overfilling the calling stack. Clearly, that the maximum n for factorial can be computed in advance and serve for protection against "bad inputs". However, this could be done on other indirection levels controlling n coming to the function factorial. The version above returns 1 for any negative n. Using unsigned int would prevent dealing processing negative inputs. However, it would not prevent possible conversion situation created by a user. Thus, measures against negative inputs might be desirable too.
While the author is asking what is technically wrong with the recursive function computing the Fibonacci numbers, I would like to notice that the recursive function outlined above will solve the task in time exponentially growing with n. I do not want to discourage creating perfect C++ from it. However, it is known that the task can be computed faster. This is less important for small n. You would need to refresh the matrix multiplication knowledge in order to understand the explanation. Consider, evaluation of powers of the matrix:
power n = 1 | 1 1 |
| 1 0 | = M^1
power n = 2 | 1 1 | | 1 1 | | 2 1 |
| 1 0 | * | 1 0 | = | 1 1 | = M^2
power n = 3 | 2 1 | | 1 1 | | 3 2 |
| 1 1 | * | 1 0 | = | 2 1 | = M^3
power n = 4 | 3 2 | | 1 1 | | 5 3 |
| 2 1 | * | 1 0 | = | 3 2 | = M^4
Do you see that the matrix elements of the result resemble the Fibonacci numbers? Continue
power n = 5 | 5 3 | | 1 1 | | 8 5 |
| 3 2 | * | 1 0 | = | 5 3 | = M^5
Your guess is right (this is proved by mathematical induction, try or just use)
power n | 1 1 |^n | F(n + 1) F(n) |
| 1 0 | = M^n * | F(n) F(n - 1) |
When multiply the matrices, apply at least the so-called "exponentiation by squaring". Just to remind:
if n is odd (n % 2 != 0), then M * (M^2)^((n - 1) / 2)
M^n =
if n is even (n % 2 == 0), then (M^2)^(n/2)
Without this, your implementation will get the time properties of an iterative procedure (which is still better than exponential growth). Add your lovely C++ and it will give a decent result. However, since there is no a limit of perfectness, this also can be improved. Particularly, there is a so-called "fast doubling" for the Fibonacci numbers. This would have the same asymptotic properties but with a better time coefficient for the dependence on time. When one say O(N) or O(N^2) the actual constant coefficients will determine further differences. One O(N) can be still better than another O(n).

How to indent lines using recursion?

Trying to achieve something like this using recursion:
if (m > n) return;
Foo 1 // no tabs
Foo 2 // \t
Foo 3 // \t\t
Foo 2 // \t
Foo 1 // no tabs
I have a function that takes 2 parameters: void indent(int m, int n);
(calling number from m to n).
So far I figured this much out:
As long as m <= n, keep calling the function. (base case)
Print the first line without any tabs setw(0)
Call the function recursively with m+1 increment. setw(4*m)
Print the first line without any tabs (again). setw(0)
Am I on the right track? Is my pseudocode correct at least?
Also, is there any way to express tabs numerically? I can't think of any way to use tab \t using either recursion or iteration.
Update: I figured it out :). cout << setw(4*m); right before cout << "Foo"; does the trick. On first call m=0 so setw(0), on 2nd call setw(4), then setw(8) and so on. Now I just have to print the text backward to 0 tabs.
Looks like you are on the right path. You would just want your recursive method to check when m == n, you would only print the line once rather then twice and then unroll.
This will work perfectly.
void indent( int m, int n )
{
PrintTabs( m ); // Forward Printing
if ( m < n )
{
indent( m + 1, n );
PrintTabs( m ); // Backward Printing
}
}
int main()
{
indent( 0, MAX );
return 0;
}