Question
How can I give spaces between numbers? When I add a <<" " after cout<<j the pattern changed. Is there any other way to give spaces between numbers?
code
#include<iostream>
using namespace std;
int main(){
int i,j=1,space,star,n;
cin>>n;
i=1;
Looping
while(i<=n){
space=n-i;
while(space){
cout<<" ";
space--;
}
star=i;
while(star){
cout<<j<<" ";
j++;
star--;
}
cout<<"\n";
i++;
}
return 0;
}
output
for n=4
1
23
456
78910
I want this output :-
1
2 3
3 4 5
7 8 9 10
For the expected output you only need to add a second space in the while(space) loop:
space = n - i;
while (space) {
std::cout << " "; // note: two spaces
space--;
}
or multiply space by 2 before the loop:
space = 2 * (n - i);
while (space) {
std::cout << ' ';
space--;
}
You could also #include <string> and skip the loop:
space = 2 * (n - i);
std::cout << std::string(space, ' ');
Another way of skipping the loop is to #include <iomanip> and use std::setw.
Note that you can use std::setw and std::left to correct the while (star) loop too to make this pattern hold for up to n = 13.
space = 2 * (n - i) + 1;
std::cout << std::setw(space) << "";
while (star) {
std::cout << std::setw(2) << std::left << j;
j++;
star--;
}
Demo
Related
How to keep the smoke set changing while the rocket goes up?
I don't understood very well, but the set only changes while the rocket is at the base.And he wasn't supposed to stand still.
veja o movimento do vĂdeo no link ->
https://i.imgur.com/RRvFqBR.mp4
The loop for(int h = 0; h < 29; h++){ maintains the set by changing the condition of the increment, and only takes off after that. Then the set stops changing.
#include <unistd.h>
#include <stdio.h>
#define LINE 11
#define COLN 12
#define R_COLN 12
#define R_LINE 9
#define R_SET 2
#define DELAY 95000
//string to display the rocket
const char rocket[LINE][COLN+1]={
" ^ ",
" /^\\ ",
" |-| ",
" |R| ",
" |O| ",
" |C| ",
" |K| ",
" |E| ",
" /|T|\\ ",
" / | | \\ ",
" | | | | "
};
const char smoke[R_SET][R_LINE][R_COLN+1]={
{
" ' * ",
" * + . ' ",
" - . + ",
" . ' : . ",
" + ' ' * . ",
" . * . ",
" . ' : ",
" . ' . ",
" ' "
},
{
" * ' ",
" ' . + * ",
" + . - ",
" . : ' . ",
" . * ' ' + ",
" . * . ",
" : ' . ",
" . ' . ",
" ' "}
};
int main(){
int jumpControlAtBottom = 0;
int shifControl = 0;
int smoke_set = 0;
for(int h = 0; h < 29; h++){ //frame
for (jumpControlAtBottom = 0; jumpControlAtBottom < 28; ++jumpControlAtBottom){
// Jump to bottom of console
printf("\n");
}
for(int i = 0; i< LINE; i++){
printf("%.*s\n", COLN, rocket[i]);
}
for(int y=0; y<R_LINE; ++y){
printf("%.*s\n", R_COLN, smoke[smoke_set][y]);
}
smoke_set=(smoke_set+1)%R_SET; // Advance to the next set
// (or go back to the first one).
fflush(stdout); // Draw the current frame on the screen.
usleep(DELAY); // Pause to be visible.
}
for (shifControl = 0; shifControl < 28; ++shifControl){
// Rocket move on the basis of delay
usleep(DELAY);
// move rocket a line upward
printf("\n");
}
return 0;
}
Currently your logic is:
Draw one frame.
Change smoke set.
Repeat 1-2 for 29 frames.
Draw line to push frame up.
Repeat 4 to keep pushing frames up.
From that it is obvious the smoke will stop changing at step 4. So the logic needs to include the take off elevation in step 1. The easiest way to do that is to put the draw frame into a function and add the elevation as a parameter.
Here is an example:
void draw_frame(int elevation)
{
int jumpControlAtBottom = 0;
static int smoke_set = 0;
for (jumpControlAtBottom = 0; jumpControlAtBottom < 28 + elevation; ++jumpControlAtBottom){
// Jump to bottom of console
printf("\n");
}
for(int i = 0; i< LINE; i++){
printf("%.*s\n", COLN, rocket[i]);
}
for(int y=0; y<R_LINE; ++y){
printf("%.*s\n", R_COLN, smoke[smoke_set][y]);
}
smoke_set=(smoke_set+1)%R_SET; // Advance to the next set
// (or go back to the first one).
// Push image up by elevation
for (int ix = 0; ix < elevation; ix++) {
printf("\n");
}
fflush(stdout); // Draw the current frame on the screen.
usleep(DELAY); // Pause to be visible.
}
int main(){
int shifControl = 0;
// No elevation - engine starting up
for(int h = 0; h < 29; h++){ //frame
draw_frame(0);
}
// take off has occured
for (shifControl = 0; shifControl < 28; ++shifControl){
// Rocket move on the basis of delay
// move rocket a line upward
draw_frame(shifControl);
}
return 0;
}
It seems to me like you're struggling to understand the procedural nature of C, which probably means you're guessing and playing around with code from other (probably poor) examples.
This is akin to guessing how to prepare a chicken for cooking and then asking your guests how to prepare a chicken for cooking, after the chicken is cooked. You have an application that does most of what you want. How did you come up with this code, yet not know how to apply such a simple tweak?
If you don't understand the procedural nature of C, it stands to reason that any exercise that has you read the procedural nature of C in order to extract some logic and repeat it is terrible for you. Where is your book? Start with the basics.
To be clear, this answer may not seem relevant, but it does actually answer your question: you need to hoist some of your smoke-related logic out into a different function so that you can reuse it later... but before you do that, you need to be able to read C, and we're not here to do your work for you, rather to guide you in the right direction.
I'm doing an exercise and I stuck with my code. I hope you guys can help me fix it.
And here is my function fen():
double fen(double x,double y, int n) { // You should complete this function
// Write your statements here
double sum=1,temp;
int j=2,k=1;
double a = (x*y*y) / 18;
sum=1-a;
for(int i=2;i<=n;i++)
{
for(;j<=i;j++)
{
a *= (x*y);
for(;k<=(i+j);k++)
a /= k;
}
temp = a/(k*k);
temp = (i%2 == 0) ? temp : -temp;
sum+=temp;
}
return sum; //This statement must be changed
}
I've checked many times but still don't know why its result's wrong.
I've debugged and when i=3, a actually equal to 0.025 but it displayed0.02499999999.
I wrote a small code to simplify things and here it is:
#include <iostream>
using namespace std;
double fen(double x,double y, int n) {
double tmp = y;
double sum = 1;
for (int i = 1; i < n; i++) {
tmp *= -((x * y * (2*i-1)) / ((2*i) * (2*i+1) * (2*i+1)));
sum += tmp;
}
return sum;
}
int main(void) {
cout << fen(2,3,1) << endl;
cout << fen(2,3,2) << endl;
cout << fen(2,3,3) << endl;
cout << fen(2,3,4) << endl;
cout << fen(2,3,1000) << endl;
return 0;
}
I only checked it till fen(2,3,4) and results were correct till there. it shows 0.162772 for fen(2,3,1000):
1
0
0.18
0.161633
0.162772
UPDATE:
Updated code to use cout for output rather than printf. But I don't think this code really differs between C or C++.
In addition, remember that you reach quickly to limit of numerical precision of double in this code.
OP's formula mis-calculates the terms.
// int j=2,k=1;
int j=2,k=3; // The loop's later calculation expect this to be initially 3
// in the loop
// add
a *= k; // undo the prior terms /k
for(;j<=i;j++) {
// this part OK
}
// temp = a/(k*k);
temp = a/k*; // Only need /k
Other simplifications possible.
/* There are 100 students and 100 lockers. Student 1 opens all, student 2 closes every second one, student 3 changes every third
locker(closes if open, opens if close), Student 4 changes every forth locker and so on for all 100 students.
Which locker will be left open? */
Here is my code thus far:
#include <stdio.h>
int main(void)
{
int locker[100], i, closed = 0, opened = 0;
for(i=0; i<100; i++) locker[i] = 1;//0 means closed locker, 1 means open locker
for(i=1; i<101; i++) if(i % 2 == 0) locker[i-1] = 0; // every second locker is closed by second student...(2,4,6,7)
for(i=3; i<101; i++){ // i means student no. i
if(locker[i-1] == 0) locker[i-1] = 1;
if(locker[i-1] == 1) locker[i-1] = 0;
if I substitute "if(locker[i-1] == 1)" with "else" why the program doesn't work? Correct result is opened 1 closed 99. If I use 'else' result becomes opened 50 and closed 50
}
for(i=0; i<100; i++){
if(locker[i] == 0) closed = closed + 1;
else opened = opened + 1;
}
printf("opened locker %d\nclosed locker %d", opened, closed);
return 0;
}
This is my first post in stack overflow. Correct me if I've done anything wrong.
I'll give you a few hints to help you out.
The answer is that 10 lockers remain open, 90 are closed.
For this particular problem, it's easier to write the code if you avoid zero-based indexing. So
declare the array as int locker[101]; and then use indexes 1 thru
100 to represent the 100 lockers.
The Nth student is supposed to change every Nth locker. So you need
two nested for loops. The outer loop keeps track of n, and the
inner loop flips lockers.
The inner loop that only affects every Nth locker should look like
this
for ( i = n; i <= 100; i += n ) // every Nth locker
locker[i] = 1 - locker[i]; // flip the locker
Note that instead of the normal i=0 and i++, we have i=n
and i+=n. So, for example, if n is 3, then the values of i
are 3,6,9,...
Though I have not checked entire code and the logic of your question is not very clear to me, these lines seem to be problematic in your code:
if(locker[i-1] == 0) locker[i-1] = 1;
if(locker[i-1] == 1) locker[i-1] = 0;
What you're doing here is if a value is 0, then you are setting it to 1, then you are checking again, if it is 1, you are setting it to 0. So, so in this case all values will be set to 0 after running through both these statements.
Instead you should be doing
if(locker[i-1] == 0) locker[i-1] = 1;
else locker[i-1] = 0;
Note that your loop is wrong because you are looping over every locker for the third student and not looping over the remainder. You should for each student (n) change every nth locker to the reverse.
Also when you have the two ifs in a row. If the first if opens a locker, the second if sees it open and closes it (which is wrong). The else is required to actually change it.
Another point is that you can use exclusive or instead of the if locker[i] ^= 1
#include <stdio.h>
int main(void)
{
int locker[100], i, k, closed = 0, opened = 0;
for(i=0; i<100; i++) {
if (i%2 == 0) locker[i] = 1; // odd lockers (base 1) stay open
else locker[i] = 0; // even lockers (base 1) are closed
//0 means closed locker, 1 means open locker
for(i=3; i<101; i++){ // i means student no. i
for (k=i; k<101); k+=i) { // change every ith locker
// if (locker[k-1] == 0) locker[k-1]=1
// else locker[i-1] = 0;
// use exclusive or instead of if
locker[i-1] ^= 1;
}
}
}
// Now check the number open or closed
for(i=0; i<100; i++){
if(locker[i] == 0) closed = closed + 1;
else opened = opened + 1;
}
printf("opened locker %d\nclosed locker %d", opened, closed);
return 0;
}
solution without using an array.
#include <iostream>
using namespace std;
int main()
{
int studentTotal , lockerTotal, visit, totalOpened = 0, totalClosed = 0;
cout << "Enter number of students" << endl;
cin >> studentTotal;
lockerTotal = studentTotal;
for (int locker = 1; locker <= lockerTotal; locker++ ){ // locker loop
cout << "\n\n\nLocker no." << locker << endl;
cout << " is visited by student(s) ";
visit = 0;
for (int student = 1 ; student <= studentTotal; student++) { // student loop
if( locker % student == 0) {
cout << student << ", ";
visit++;}
}//end of locker loop
cout << "\nTotal number of visits: " << visit;
if (visit % 2 == 0){
cout << " the locker will stay closed.";
totalClosed++;}
else { cout << " the locker will be opened.";
totalOpened++;}
} //end of student loop
if (lockerTotal == totalOpened + totalClosed) {
cout << "\n\n\nOf total lockers (" << lockerTotal << "), " << totalOpened << " will be left open." << "(" << totalClosed << ") " << "will be closed." << endl;
}else cout << "Error!!";
return 0;
}
LOCKERS is the new FIZZBUZZ.
Here's a version which uses Booleans.
/* locker problem.c
*/
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
bool locker[101]; // locker open = true, closed = false
// student 1 opens all lockers
for (int i = 1; i <= 100; ++i) {
locker[i] = true;
}
// subsequent students toggle (flip) subsequent lockers
for (int i = 2; i <= 100; ++i) {
for (int j = i; j <= 100; j += i) {
locker[j] = ! locker[j];
}
}
// display results
printf("\nopen lockers:");
for (int i = 1; i <= 100; ++i) {
if (locker[i]) {
printf(" %d", i);
}
}
putchar('\n');
return 0;
}
At the conclusion of the process the open lockers are the ones with a number which is a perfect square -- a perfect square has an odd number of divisors.
1) Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10).
Once the data has been entered, the program must analyze the data and output which person ate the most pancakes for breakfast.
My solution uses an array, but the program only displays the person who ate the most sentence if I put a break in the end of the if statement. Without the break the program just asks how much each person ate then exits. I'm just trying to understand exactly why the break needs to be there, or if there is a way to do it without the break.
Here is my code:
//Pancakes!
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//Build array of people and set a value for most eaten
int people[9] = {};
int most = -1;
for (int n=1; n<=10; n++)
{
//Sets the number of pancakes eaten to a person value in the array
cout << "How many pancakes did person " << n << " eat? ";
cin >> people[n-1];
//Checks if the value entered above is the highest value
if(people[n-1] > most)
{
most = people[n-1];
}
}
//Line entered for formatting
cout << endl;
//Lists the person and how many pancakes they ate
for (int x=0; x<10; x++)
{
if(people[x] == most)
{
cout << "Person " << (x+1) << " ate " << most << " pancake(s), the most!" << endl;
break;
}
}
//Pause after program
cout << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
Also feel free to review my code and give me tips for making it more concise because im still a newbie =] thanks.
For the above question, I would solve it this way to preview the person who ate the most pancakes:
Code:
// assuming the first one is the highest one
most = 0;
//now checking for the higest one
for (int x = 0; x < 10; x++) {
if (people[x] > =people[most]) {
most = x;
}
}
cout << people[most]; //this shows the highest pancakes.
This doesn't use break at all and gives the required output.
I need to read an integer one by one until i read a '$', and then to determine the largest, smallest and so on. I could use a character variable and do it, but it works for numbers from 0 to 9. But how do I read integers of two or more digits and at the same time, detect a '$' - I used a char *, but I guess it is equivalent to an array, which I should not use here. Also, char holds a single number / char, hence not suitable for larger numbers. What should I do?
No arrays, no pointers, no tricky char-by-char read & convert. Just plain scanf and getchar.
#include <stdio.h>
int main()
{
int newValue=0; /* value being acquired */
int max; /* current maximum value */
int min; /* current minimum value */
int firstAcquired=0; /* boolean flag set to 1 after first acquisition */
int ch; /* used as temporary storage for the getchar() */
for(;;)
{
/* scanf returns the number of successfully acquired fields; here if it
returns 0 means that the value couldn't be acquired */
if(scanf("%d",&newValue)==0)
{
/* scanf failed, but it's guaranteed it put the offending character
back into the stream, from where we can get it */
ch=getchar();
if(ch=='$' || ch==EOF)
break;
else
/* from here to the break it's just to handle invalid input and EOF
gracefully; if you are not interested you can replace this stuff
with a random curse to the user */
{
puts("Invalid input, retry.");
/* Empty the buffer */
while((ch=getchar())!='\n' && ch!=EOF)
;
}
/* if it's EOF we exit */
if(ch==EOF)
break;
}
else
{
/* Everything went better than expected */
if(!firstAcquired || newValue>max)
max=newValue;
if(!firstAcquired || newValue<min)
min=newValue;
firstAcquired=1;
}
}
if(firstAcquired)
{
printf("The maximum value was %d\n", max);
printf("The minimum value was %d\n", min);
}
return 0;
}
In the interest of spoiling all the fun, showing off, outright overkill and darn tooting fun:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
namespace qi = boost::spirit::qi;
template <typename V>
void show_statistics(const V& data)
{
using namespace boost::spirit::karma;
std::cout << "data:\t"<< format('{' << auto_ % ", " << '}', data) << std::endl;
std::cout << "min:\t" << *std::min_element(data.begin(), data.end()) << std::endl;
std::cout << "max:\t" << *std::max_element(data.begin(), data.end()) << std::endl;
auto sum = std::accumulate(data.begin(), data.end(), 0);
std::cout << "sum:\t" << sum << std::endl;
std::cout << "avg:\t" << (1.0*sum) / data.size() << std::endl;
}
void dostats(const std::vector<int>& data) { show_statistics(data); }
int main()
{
std::cin.unsetf(std::ios::skipws);
auto f = boost::spirit::istream_iterator(std::cin);
decltype(f) l;
bool ok = qi::phrase_parse(f, l, +(+qi::int_ > "$") [ dostats ], qi::space);
if (f!=l)
std::cout << "Remaining input unparsed: " << std::string(f,l) << std::endl;
return ok? 0:255;
}
Demo:
Sample run:
sehe#natty:/tmp$ ./test2 <<< "1 2 3 4 5 $ 3 -9 0 0 0 $ 900 9000 $ unparsed trailing text"
data: {1, 2, 3, 4, 5}
min: 1
max: 5
sum: 15
avg: 3
data: {3, -9, 0, 0, 0}
min: -9
max: 3
sum: -6
avg: -1.2
data: {900, 9000}
min: 900
max: 9000
sum: 9900
avg: 4950
Remaining input unparsed: unparsed trailing text
You can use 'scanf("%s")' to read a group of characters. You can then check if the first character is a '%' and terminate if so. Otherwise, call atoi to convert to an integer. Store the largest and smallest in integer types, not character types.
Basically, the only time you have to deal with characters is when you read them in and check if it's a '$'. Otherwise, use integers all the way through.
If I'm getting what you want correctly it should be something like this:
int i = 0;
char c = getchar();
while (c != '$')
{
i = i * 10 + (c - '0');
c = getchar();
}
Hope it helped.
You can read char by char in a loop, check values and so on...
int i = 0;
char c = 0;
int size = 10;
int currentIndex = 0;
int* integers = malloc(sizeof(int) * size);
int counter = 0;
do
{
scanf("%c", &c);
if (c == ' ') // Match space, used a number separator
{
if (counter != 0 && i != 0)
{
if (currentIndex >= size)
{
size += 5;
integers = realloc(integers, size);
}
integers[currentIndex] = i;
currentIndex++;
}
counter = 0;
i = 0;
}
else if (c >= '0' && c <= '9')
{
i = (i * counter * 10) + (c - '0');
counter++;
}
}
while(c != '$');
Don't forget to free integers in the end!
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define BUFF_SIZE 16
#define DATA_MAX_SIZE 64
int main(){
char buff[BUFF_SIZE];
int data[DATA_MAX_SIZE];
int i,value,counter = 0;
char *buffp,*p;
while(NULL!=fgets(buff,BUFF_SIZE,stdin)){
buff[BUFF_SIZE - 1]='\0';
buffp = buff;
next: while(isspace(*buffp))
++buffp;
if(*buffp == '\0')
continue;
value = strtol(buffp, &p, 0);
if(counter == DATA_MAX_SIZE){
printf("over data max size!\n");
break;
} else if(p != buffp){
data[counter++]=value;
if(*p == '\0' || *p == '\r'|| *p == '\n')
continue;
buffp = p;
goto next;
} else {
if(*p == '$')
break;
printf("format error\n");
break;
}
}
//check code
for(i=0;i<counter;++i){
printf("data[%d]=%d\n",i, data[i]);
}
return 0;
}
OUTPUT:
1 2 3
123
456
99 $
data[0]=1
data[1]=2
data[2]=3
data[3]=123
data[4]=456
data[5]=99
12345
4
$
data[0]=12345
data[1]=4