How to move a star pattern horizontally? - c

I'm assigned a program which will show a star pattern as follows:-
*
**
***
****
And then it will disappear from its place & then re-appear forming a motion like moving from left to right.
I have tried a lot. But, The best I could get was to move only the first star like this:-
*
**
***
****
The whole other part of pattern remains there.
I used delay function and gotoxy and clear screen along with for Loops but unable to do it the right way!
My pattern code:-
#include <stdio.h>
main()
{
char star='*';
int row, col;
int rowFinal;
printf("Enter the number of rows to be printed\n");
scanf("%d",&rowFinal);
for (row=1; row<=rowFinal; row++)
{
for (col=1; col<=row; col++)
{
printf("%c",star);
}
printf("\n");
}
}
Help me with remaining part I have messed it up won't be of any use to show it here.

This question is a bit ambiguous (please show code!), so I'm assuming when you say "assigned" you mean "assigned to make" not "given the program as a closed box and forced to work around what would be a fairly poor design choice if it is indeed impossible or difficult to edit".
Here is a rough framework for how to do it.
for (i=1; i<MAX AMOUNT OF STARS; i++) {
printf(INDENTATION);
//Code to print i stars and \n
}
The "//Code to print..." could be the code or the function call if by "assigned" you mean "given as closed box", but that works line by line.

If your problem is how to animate *, here is a small sample code with animates 1 star in 1 line:
#include <stdio.h>
#include <unistd.h>
#define SWEEP_WIDTH 20
int main()
{
int idx = 0, i = 0;
for (i = 0; i < 100; i++)
{
if (--idx < 0)
{
idx = SWEEP_WIDTH;
}
printf("%*s%*s\r", idx, "*", (SWEEP_WIDTH-idx), " ");
fflush(stdout);
usleep(50000);
}
I don't write the whole code for you, but I guess this should be somehow enough to get how you can animate stars in your code.
By the way, you can always code better if you spend time, this is result of 5 min coding, so you may be able to write it much better.

Related

C/Ncurses how to wrap text in a textfield

I would like to wrap a short text in a Text Box in Ncurses, but somehow my text keeps going off screen. How can I wrap the text so it (automatically) goes to a new line when reaching the end of the screen on the right?
I tried playing with '\n' and setting limits but witout results. Any tips what I am doing wrong? See below code for what is going on.
Thanks from a beginner programmer.
#include <ncurses.h>
#include <string.h>
void text(WINDOW* textborder, int wymax, int wxmax, char text5[], int size)
{
for (int i=0;i<size;i++)
{
mvwaddch(textborder,2,i+i, text5[i]);
if (i==wxmax)
{
mvwaddch(textborder,2,i+i, '\n');
}
}
}
int main()
{
char text5[]={"Somebody is watching over us... controlling us. It's true, I tell you. It's true! We are merely sprites that dance at the beck and call of our button-pressing overlord. This is a video game. Don't you see? We are characters in a video game."};
int size;
size=strlen(text5);
int wymax; int wxmax;
initscr();
WINDOW* textborder=newwin(LINES/4, COLS, LINES-LINES/4, 0);
box(textborder,-1,-1);
getmaxyx(textborder, wymax,wxmax);
wxmax=wxmax-4;
text(textborder, wymax, wxmax, text5, size);
wgetch(textborder);
endwin();
return 0;
}
In theory the text should wrap itself. I think your issue may be coming from using mvwaddch, ch generally causes the text not to wrap. This may help Ncurses no-wrap mode when adding strings to window. Sorry I can't be more helpful :)
Applications that draw a box with a border in curses do this using two windows, one within the other. The outer box gets the border; the inner box gets the text. Text printed within the inner box does not affect the outer box.
For example, some of the demo/example programs in ncurses do this, e.g., test_addstr creates look (for the box) and show (for the text):
limit = LINES - 5;
if (level > 0) {
look = newwin(limit, COLS - (2 * (level - 1)), 0, level - 1);
work = newwin(limit - 2, COLS - (2 * level), 1, level);
show = newwin(4, COLS, limit + 1, 0);
box(look, 0, 0);
wnoutrefresh(look);
limit -= 2;
} else {
work = stdscr;
show = derwin(stdscr, 4, COLS, limit + 1, 0);
}
keypad(work, TRUE);

how to delete something which is already written in output in c

so here is the thing I am trying to make something like 1d particle simulator which could simulate two particle but the problem is it takes time proccess and in that time I want to show the user something like loading... and then the loading vanishes and and answer is shown so I wanted to know if is it possible to delete something which already in the output part if so please tell how.
I am pretty knew to this platform so if I did any mistake please tell.
You can use the following code. Example Command-line progress bar:
// C program to create loading bar
#include <stdio.h>
#include <windows.h>
// Function to creating loading bar
void loadingBar()
{
// 0 - black background,
// A - Green Foreground
system("color 0A");
// Initialize char for printing
// loading bar
char a = 177, b = 219;
printf("\n\n\n\n");
printf("\n\n\n\n\t\t\t\t\t"
+ "Loading...\n\n");
printf("\t\t\t\t\t");
// Print initial loading bar
for (int i = 0; i < 26; i++)
printf("%c", a);
// Set the cursor again starting
// point of loading bar
printf("\r");
printf("\t\t\t\t\t");
// Print loading bar progress
for (int i = 0; i < 26; i++) {
printf("%c", b);
// Sleep for 1 second
Sleep(1000);
}
}
// Driver Code
int main()
{
// Function Call
loadingBar();
return 0;
}

Gauss-Jordan Elimination in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, I have some class work that I cannot solve. I could get the code to work partially but now it is just useless. It either freezes (doesn't complete running) or it will give me several inf in the first row.
#include <stdio.h>
#include <math.h>
int main()
{
double a[10][11]={
{3.55618, 5.87317, 7.84934, 5.6951, 3.84642, 9.15038, -1.68539, 5.03067, 7.63384, -1.75626, -1.92193},
{-4.82893, 8.38177, -0.301221, 5.10182, -4.1169,-6.09145, -3.95675, -2.33365, 1.3969, 6.54555, -2.35262},
{-7.64196, 5.66605, 3.20481, 1.55619, -1.19814, 9.79288, 5.35547, 5.86109, 4.95544, -9.35749, 2.27709},
{-2.95914, -9.16958, 7.3216, 2.39876, -8.1302, -7.55135, -2.37718, 7.29694, 5.9867, 8.5401, -2.67493},
{-8.42043, -0.369407, -5.4102, -8.00545, 9.22153, 3.96454, 5.38499, 0.438365, 0.419677, 4.17166, 1.84756},
{6.02952, 4.57728, 5.46424, 3.52915, -1.01135, -3.74686, 8.14264, -8.86961, -2.88114, 1.29821, 4.154126},
{0.519819, -6.16655, 1.13216, 2.75811, -1.05975, 4.20286, -3.45764, 0.763558, -0.281287, -9.76168, -.93387},
{5.15737, -9.67481, 9.29904, -3.93334, 9.12785, -4.25208, -6.1652, 2.5375, 0.139195, 2.00106, -1.28356},
{-4.30784, 1.40711, -6.97966, -9.29715, 5.17234, 2.42634, 1.88818, -2.05526, -3.7679, 3.3708, -3.46841},
{-4.65418, 7.18118, 6.51338, 3.13249, 0.188456, -16.85599, 7.21435, -2.93417, 1.06061, 1.10807, -2.61529}};
int i, j, k, l;
double b[10][11];
i=0;
while(i<10)
{
j=0;
l=i;
while(l<10)
{
j=0;
l++;
while(j<11)
{
This code below works fine. When used on its own, it will turn all the diagonal values into 1.
b[i][j]=a[i][j]/a[i][i];
This code used below to work partially, setting the first column equal to 0, but now it is useless. I tried to manipulate it into getting rid of all values by having that 0 be a k, with k++ within the while code, but it would return either a segmentation code if I placed it by the i++; or a bus error is placed in front of the j=0;, and it would just freeze the program if I placed the i in the 0. Now it is useless that I restored it to default
b[l][j]=a[l][j]-b[i][j]*a[l][0];
j++;
}
}
i++;
}
j=0;
i=0;
while(i<10)
{
while(j<11)
{
printf("%lf\t", b[i][j]);
j++;
}
printf("\n");
i++;
j=0;
}
return 0;
}
How do I go about solving all these issues within my C program?
Not 100% sure what your code is up to, but I see at least 1 place where I believe that you are reading off the end of your arrays:
while(l<10)
{
j=0;
l++;
...
b[l][j]=a[l][j]-b[i][j]*a[l][0];
Because you are incrementing after you check for max size, you have 1 iteration where you are probably reading passed the max size of the array.
To check, put some prints on your indexes in your code where you do your assignments or assert them or something and I think you will find the source of your woes.
Also, PLEASE use constants for your sizes instead of the magic numbers all over the place. You will thank me later when trying to do a calculation of a matrix of a different size.

Error in color fading function

I found this old color fading function in my snippets folder and would like to implement it to one of my projects. It can be used to fade one color to another. It's a very long one-liner:
D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
return (factor<0.0f)?from:((factor>1.0f)?to:((((from>>24)>(to>>24))?((from>>24)-(D3DCOLOR)(factor*(float)((from>>24)-(to>>24)))):((from>>24)+(D3DCOLOR)(factor*(float)((to>>24)-(from>>24))))<<24)|((((from<<8)>>24)>((to<<8)>>24))?(((from<<8)>>24)-(D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24)))):(((from<<8)>>24)+(D3DCOLOR)(factor*(float)(((to<<8)>>24)-((from<<8)>>24))))<<16)|((((from<<16)>>24)>((to<<16)>>24))?(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-((to<<16)>>24)))):(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-((from<<16)>>24))))<<8)|((((from<<24)>>24)>((to<<24)>>24))?(((from<<24)>>24)-(D3DCOLOR)(factor*(float)(((from<<24)>>24)-((to<<24)>>24)))):(((from<<24)>>24)+(D3DCOLOR)(factor*(float)(((to<<24)>>24)-((from<<24)>>24)))))));
}
D3DCOLOR is just a DWORD (unsigned long). A color can for example be 0xAARRGGBB (A-alpha, R-red, G-green, B-blue), but works with other compositions aswell.
Obviously it's a total mess, but this is exactly what I need.
The problem is that it doesn't work as intended:
GetFadedColor(0x00000000, 0xff33cccc, 0.3f)
// = 0x4c0f3d3d - working as intended
GetFadedColor(0xff33cccc, 0x00000000, 0.3f)
// = 0x000000bf - pretty wrong
GetFadedColor(0xff00ff00, 0x00ff00ff, 0.3f)
// = 0x004c00ff - second color value is correct, everything else wrong
I actually don't know how it works and don't remember where I have it from, so I'm asking here for help. Either help me find the error or find an alternative function that does exactly this.
What you should to now is first you should spend maybe 5 minutes to write down some really basic tests with the cases where you know what you expect. You don't even need to use any test framework, because to get rolling you could just use assert:
// basicTests.c
#include <assert.h>
int getFadedColor_basicTests()
{
assert(GetFadedColor(0x00000000, 0xff33cccc, 0.3f) == 0x4c0f3d3d && "30% from black to light blue should be greenish");
assert(GetFadedColor(0xff33cccc, 0x00000000, 0.3f) == something && "30% from one color to another should be...");
// if you're not sure what the exact value should be, you should write a helper function
// that returns true/false for if each of the four components of the actual color
// are in a sensible expected range
...
}
int main()
{
getFadedColor_basicTests();
return 0;
}
Once you're happy with how much coverage you get with tests, be it just 3 asserts total, or maybe 50 asserts if you feel like it, you should start reformatting the one-liner, breaking the line, adding meaningful indentation and comments. Start refactoring, extract out common expressions, add comments on what they do or should do, all while running the tests in between changes and adding tests as you devise new ones.
EDIT:
Isn't it just supposed to linearly extrapolate each of the components separately?
int fade(int from_, int to_, float factor)
{
unsigned char *from = (unsigned char*)&from_;
unsigned char *to = (unsigned char*)&to_;
int result_;
unsigned char *result = (unsigned char*)&result_;
for (int i = 0 ; i < 4; ++i)
{
result[i] = factor * ((int)to[i] - (int)from[i]) + from[i];
}
return result_;
}

Deciding the base condition in backtracking recursive algorithm

I was solving the N Queen problem where we need to place 4 queens on a 4 X 4 chess board such that no two queens can attack each other. I tried this earlier but my approach did not involve backtracking, so I was trying again. The code snippets are
int size=4,i,j;
int arr[4][4];
int lastjindex[4]; // to store the last location which we may need to backtrack
void placeQueen(int i,int j)
{
int availableornot=0;
for(j=0;j<size;j++)
{
if(isAvailable(i,j)==1)
{
availableornot=1;
break;
}
}
if(availableornot==1)
{
arr[i][j]=1;
lastjindex[i]=j;
if((i+1)!=size)
{
placeQueen(i+1,0);
}
}
else
{
// no column was availabe so we backtrack
arr[i-1][lastjindex[i-1]]=0;
placeQueen(i-1,lastjindex[i-1]+1);
}
}
The isAvailable() method returns 1 if arr[i][j] is not under attack, else it returns 0.
int isAvailable(int i,int j)
{
int m,n,flag=0;
for(m=0;m<i;m++)
{
for(n=0;n<size;n++)
{
int k=abs(i-m);
int l=abs(j-n);
if(arr[m][j]==0 || arr[k][l]==0)
{
flag=1;
break;
// means that spot is available
}
}
}
return flag;
}
I call the above method from main as
placeQueen(0,0);
My program compiles successfully but it prints all zeroes.
Is there any problem with my recursion? Please help me correct my code as I am trying to learn how to implement backtracking algorithms!
Also I am not able to decide the base condition to end recursion. How do I choose it here?
There's no printing in the code you posted. If you print after you have backtracked, you will be back to the initial condition of no queens on the board. Print after you have placed N queens, which is also the end condition for recursion. If you only want to print one solution, exit after printing, or set a flag that tells the caller that you're done so you pop all the way out. If you print all solutions, that will include reflections and rotations. You can eliminate one axis of reflection by only placing queens within size/2 in the first level.
Also, there are some clear logic errors in you code, such as
arr[m][j]==0 || arr[k][l]==0
A queen can only be placed if it isn't attacked on the file and it isn't attacked along a diagonal. Use a debugger or add printfs to your code to trace where it is trying to place queens -- that will help you figure out what it is doing wrong.
And aside from being wrong, your isAvailable is very inefficient. You want to know if the [i,j] square is attacked along the file or a diagonal. For that you should have a single loop over the rows of the previous queens for (m = 0; m < i; m++), but you only need three tests, not a loop, to check the file and the diagonals. As soon as you find any previous queen on a file or diagonal, you're done, and the square isn't available -- return false. (And ignore people who tell you that a function should only have one return -- they are wrong, and there are lengthly discussions here at SO and even scientific studies of error rates in code that bear this out.) Only if no previous queen is found is the square available.
Your placeQueen is also wrong. For each available square on a row, you need to place a queen and then recurse, but you're just finding the first available square. And backtracking is achieved simply by removing the queen you placed and then returning ... the previous level of placeQueen will try the next available spot.
Again, trace the code to see what it's doing. And, even more importantly, think through the logic of what is needed. Write your algorithm in words, convince yourself that it will solve the problem, then write the code to carry out the algorithm.
#include <stdio.h>
#define SIZE 4
int size=SIZE;
int arr[SIZE][SIZE] = { 0 };
void placeQueen(int col){
int r,c;
if(col == size){//all queen put!
//print out
for(r = 0;r<size;++r){
for(c = 0;c<size;++c)
printf("%d", arr[c][r]);
printf("\n");
}
printf("\n");
return ;
}
for(r=0;r<size;++r){
if(isAvailable(col, r)==1){
arr[col][r]=1;
placeQueen(col+1);
arr[col][r]=0;//reset
}
}
}
int isAvailable(int col,int row){
int c;
for(c=0;c<col;++c){
int d = col - c;
if(arr[c][row]==1)
return 0;//queen already same row
if(row+d < size && arr[c][row+d]==1 || row-d >= 0 && arr[c][row-d]==1)
return 0;//queen already same slanting position
}
return 1;
}
int main(){
placeQueen(0);
return 0;
}

Resources