How can I write strings into a 2D ASCII character array? - c

Good day everyone,
I'm currently learning C through youtube and I have minimal knowledge about arrays. Is it possible for me to use an array to designate a place inside a pattern. e.g In a 20x20box Could I ask the user to say where he would like to place his name tag or brandname? I'm also wondering if I can create a pattern for a shield and know where the user would want to place his coat of arms using strings and loops.
#include <stdio.h>
#include <string.h>
int main()
{
int i,j, choice;
int Num=20;
/*
char brand[20][20]={{"BrandName"}};
printf("where should the brandname be placed?")
scanf("%d", &choice);
if(choice==1)//prints it on the left for example?*/
for(i=0;i<Num;i++)
{
for(j=0;j<Num;j++)
{
if(i==0||i==Num-1)
{
printf("*");
}
else if(j==0||j==Num-1)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}

Related

My c program keeps crashing and I do not know why

I am writing a program like hangman in c and I am trying to run it .The problem is that it's working fine until I give it a letter to quess the word but then it crashes with -1073741819 (0xC0000005). Can someone help me solve this, I think its something really small that I cant
see . Thank you for helping me!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Rules(void);
void maskWord (char starword[], int size);
int playRound(char starword[], char answer[]);
void updateStarWord(char starword[], char answer[], char userguess);
int occurancesInWord(char userguess, char answer[]);
int c=0;
char answer[128];
int N;
int main()
{
int ch,size;
char starword[1000];
do
{
printf("---Welcome to Hangman!---\n");
printf("1.Start Game\n2.Instructions\n3.Exit\n");
scanf("%d",&ch);
if(ch>0&& ch<4)
{
switch(ch)
{
case 1:
maskWord(starword,size);break;
case 2:
Rules();break;
}
}
else
system("cls");
}
while(ch!=3);
return 0;
}
void Rules(void)
{
do
{
do
{
printf("\nThe word to guess is represented by a row of dashes representing each letter of the word.");
printf("\nRules may permit or forbid proper nouns, such as names, places, brands, or slang.");
printf("\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions.");
printf("\nIf the suggested letter does not occur in the word, the other player draws one element of a hanged stick figure as a tally mark.\n");
}
while(getchar()!='\n');
}
while(getchar()!='\n');
}
void maskWord (char starword[], int size)
{
printf("Enter word to guess: ");
fflush(stdout);
scanf(" %s", answer);
int N = strlen(answer);
int mask[N];
for (int i=0; i < N; ++i)
{
mask[i] = 0;
}
playRound(mask,N);
}
int playRound(char starword[], char answer[])
{
// Loop over each round of guessing
int gameover = 0;
while (! gameover)
{
// Print word with *s for unguessed letters
printf("The word is : ");
for(int j=0; j < answer; ++j)
{
if (starword[j])
{
printf("%c", answer[j]);
}
else
{
printf("*");
}
}
printf("\n");
// Get player's next guess
char guess;
printf("\nGive a letter: ");
fflush(stdout);
scanf(" %c", &guess);
updateStarWord(starword,answer,guess);
}
}
void updateStarWord(char starword[], char answer[], char userguess)
{
// Mark true all mask positions corresponding to guess
int k;
for(k=0; k < answer; ++k)
{
if ((answer[k]) ==(userguess))
{
starword[k] = 1;
}
}
}
Your for loop doesn't make sense because the condition for terminating it is k < answer. You are comparing an integer (k) to a pointer (answer). The compiler should have warned you about this, so make sure your compiler warnings are turned on and you are paying attention to them. Pointers and integers are different things, and comparing them is almost never what you want to do.
If answer is null-terminated, you could probably replace that condition with answer[k]. Or maybe updateStarWord needs to take an argument that indicates the length of answer, and then the condition would be k < answer_length.

How to keep track of the amount a certain loop has run and storing values into arrays

I am a newbie in coding and preparing an assignment in which I am encountering certain difficulties. I just want you guys to help me identify my mistake for one issue I am facing. Before pasting my code I am giving an overview of what had to be done.
The user have to create drones and after creating one drone the program should return back to the main menu, store the details of the 1st drone and if request to enter another drone he/she should be allowed to do so until the number of drones have reached 10. Only 10 drones are allowed and we have to use arrays for storing the values of each drone. I am unable to make the program count 10 and using arrays to store them. In the code I have pasted here, I am trying for 2 but I am unable to do that as well. Please help me...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct drone_t{
char name[30];
float top_s;
float acc;
};
void printing (struct drone_t dron[2]);
int main()
{
int a, i;
char nam;
struct drone_t drone[2];
printf("Welcome to the drone travel time calculator\n");
printf("1. Create Drone\n2. Calculate Time\n3. Exit\n");
scanf("%d", &i);
if (i == 1)
{
for (a=1; a < 3; a++)
{
printf("What is the name of the drone?\n");
scanf("%s", drone[a].name);
printf("What is the top speed of the drone? (kmph)\n");
scanf("%f", &drone[a].top_s);
printf("What is the acceleration of the drone? (mpsps)\n");
scanf("%f", &drone[a].acc);
printing(drone);
}
}
else if (i == 2)
{
printing(drone);
}
}
void printing (struct drone_t dron[2])
{
int a;
for (a=1; a < 3; a++)
{
printf("Name is: %s\n", dron[a].name);
}
//return 0;
}
Anticipated Output is:
Welcome to the drone travel time calculator
1. Create Drone
2. Calculate Time
3. Exit
1
What is the name of the drone?
Jayne
What is the top speed of the drone? (kmph)
12
what is the acceleration of the drone? (mpsps)
12
1. Create Drone
2. Calculate Time
3. Exit
1
What is the name of the drone?
JayneW
What is the top speed of the drone? (kmph)
12
what is the acceleration of the drone? (mpsps)
12
1. Create Drone
2. Calculate Time
3. Exit
2
Select a drone:
1. Jayne
2. JayneW
EDIT:
#coderredoc
Here is the full code.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct drone_t{
char name[30];
float top_s;
float acc;
};
void show_menu();
void do_create(int dronesCreated);
#define MAXDRONES 10
int main()
{
int dronesCreated = 0;
int i;
while(1)
{
show_menu();
if (i == 1)
{
if(dronesCreated<=MAXDRONES-1)
{
dronesCreated++;
do_create(dronesCreated);
}
else
{
printf("error: cannot create more drones");
}
}
else
{
break;
}
}
}
void show_menu()
{
int i;
printf("1. Create Drone\n2. Calculate Time\n3. Exit\n");
scanf("%d", &i);
}
void do_create(int dronesCreated)
{
char name[10];
int b, c;
int count = dronesCreated;
struct drone_t drone[10];
for (b=0; b <= count; b++)
{
printf("What is the name of the drone?\n");
scanf("%s", drone[b].name);
printf("What is the top speed of the drone? (kmph)\n");
scanf("%f", &drone[b].top_s);
printf("What is the acceleration of the drone? (mpsps)\n");
scanf("%f", &drone[b].acc);
}
}
As far as I can understand you are stuck in this part.
How to continue getting input?
For that you need to write a while(1){..} with a propr exit condition like break etc.
Rest of the job boils down to how many drones are there? and accessing and storing them.
For storing an array of structure will be sufficient. For count of drone you can use a seperate variable. Accessing them is nothing but array access.
A pseudocode to your guide:
#define MAXDRONES 10
int dronesCreated =0;
while(1){
show _menu();
if( option is DRONE_CREATE){
if(dronesCreated<=MAXDRONES-1){
do_create();//increment NUM_OF_DRONES here.
dronesCreated++;
}
else
print appropriate message.
else if(option is PRINT)
print()
else
break;
}
Look it is simple to understand the design of the program from intuitive viewpoint.
You need a loop because you need to continuouskly ask for option from user. That's why loop.
How to stop at 10 drones?
You keep a variable and check when DRONE_CREATE option is given whether 10 drones are created. If yes then don't call the function else do call the function.
Implementation centric approach:
Now as you are using the global array of structures for the drones, you need to use a count varible like this.
int numberOfDrones = 0; And then use the control as shown above.
How to print and scan the drones?
Simply the way you would input and output them.
scanf("%s",drone[a].name);
print("%s,%d",drone[a].name,drone[a].age);
All at one time:
for(int i=0;i<MAXDRONES;i++){
printf("What is the name of the drone?\n");
scanf("%s", drone[a].name);
printf("What is the top speed of the drone? (kmph)\n");
scanf("%f", &drone[a].top_s);
printf("What is the acceleration of the drone? (mpsps)\n");
scanf("%f", &drone[a].acc);
printing(drone);
}
You have a fundamental error that catches many people new to C-like languages:
Array subscripts in C run from zero, i.e. the first element of array drone would be "drone[0]".
This means that when your code executes the main() for loop for the second time it will be writing the data outside the bounds of the array. This results in undefined behaviour. The quick fix is to change the for loop to: for (a=0; a < 2; a++) in both main() and printing().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DRONES 10
struct drone_t{
char name[30];
float top_s;
float acc;
};
void printing (struct drone_t dron[]); //no need to mention size while prototyping
int main()
{
unsigned short cnt,choice;
//char nam; //uneccessary variable
struct drone_t drone[DRONES];
printf("Welcome to the drone travel time calculator\n");
do{
printf("1. Create Drone\n2. Calculate Time\n3. Exit\n:\t");
scanf("%d", &choice);
switch(choice)
{
case 1:
for (cnt=0; cnt < DRONES; cnt++)
{
printf("What is the name of the drone?\n");
scanf("%s",drone[cnt].name);
printf("What is the top speed of the drone?(kmph)\n");
scanf("%f", &drone[cnt].top_s);
printf("What is the acceleration of the drone?(mpsps)\n");
scanf("%f", &drone[cnt].acc);
}
printing(drone);//put this statement outside loop
break;
case 2:
printing(drone);
break;
case 3:
exit(EXIT_SUCCESS);
default:
printf("choose correct option :D");
break;
}
}while(choice!=3); //if explicitly using exit case then not needed
}
void printing (struct drone_t dron[10])
{
unsigned short cnt;
for (cnt=0; cnt < DRONES; cnt++)
{
printf("Name is: %s\n", dron[cnt].name);
}
}
Note: Don't use for(cnt=1;;) it may cause problems like an off-by-one error so better use for(cnt=0;;).

Write a C program to arrange the numbers in an array as a series of odd and even numbers

I've made an attempt to create the above program,but there's some error.Here's my program
#include <stdio.h>
#include <conio.h>
void main()
{
int a[20],o[20],e[20],c[40],i,j,k,l,n;
printf("enter size of array");
scanf("%d",&n);
printf("enter array");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
for(k=1;k<=(n-j);k++)
{
if(a[i]%2==0)
{
o[j]=a[i];
break;
}
else
{
e[k]=a[i];
}
}
}
}
for(i=1;i<=j;i++)
{
c[l]=o[i];
}
for(i=1;i<=k;i++)
{
c[l+k]=e[k];
}
printf("The new array is");
for(l=1;l<=(j+k);l++)
{
printf(" %d ",c[l]);
}
getch();
}
Can anybody please help me rectify the error in the above program?Can someone also give me a few tips on how to become a good C programmer?
The problem is probably because you never initialize the variable l.
Using an uninitialized variables yields in undefined behaviour (google that).
Also your array indexes start at 1 as for example here:
for (i = 1; i <= n; i++)
In C array indexes start at 0, so you should write this:
for (i = 0; i < n; i++)
This appies to all your other for loops.
There may be other problems though.
Your program looks overly complicated
Using variable names such as odd instead of o and even instead of e would make your program much easier to read.
Your program is poorly formatted. Correct formatting is essential to readbility

String manipulation in C?

Okay I am trying to ask and sort names in C. I completed the code and it compiled without an error but I have a problem. When I input mixed characters that is Uppercase and Lowercase I get Uppercase sorted first and not in order. What should I do to my code ? Please anyone help me.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char name[30][25],temp[25];
int i,j,n;
printf("Enter how many students : ");
scanf("%d",&n);
for(i=0;i<n;i++);
{
printf("Enter the name of the student : ");
scanf("%s",name[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("The sorted names are : \n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
return(0);
}
The loops for your bubble sort are wrong - change:
for(i=0;i<n;i++)
{
for(j=i+j;j<n;j++)
{
to:
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
Alternatively just use qsort from the standard C library rather than trying to re-invent the wheel.
You have two options. One, convert the string to lower (or upper) before comparison. Secondly strcol each string, this puts k next to K etc. Both methods are destructive so you may need to create a work string and free it after comparison.
First of all your program is wrong. For example instead of
scanf("%s",&name[i]);
there has to be
scanf("%s", name[i]);
Or in this statement
for(j=i+j;j<n;j++)
there is used uninitialized variable j.
As for your question then you should convert strings to upper case using standard C function toupper declared in header <ctype.h>
Also it is better to use selection sort without copying strings every time when name[j] is less than name[i].
Multiple errors:
do not end the for loop with a semicolon
for(i=0;i<n;i++);
take a second look at these variables
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
as you described you compare incorrectly for your usecase
if(strcmp(name[i],name[j])>0)
This is a possible solution:
#include <stdio.h>
#include <string.h>
char * Inputs[] =
{
"3\n",
"Carl\n",
"Frank\n",
"carl\n"
};
int in = 0;
int main()
{
char name[30][25],temp[25];
int i,j,n;
printf("Enter how many students : \n");
sscanf(Inputs[in++],"%i",&n);
printf("You entered : %i\n", n);
for(i=0;i<n;i++)
{
printf("Enter the name of the student : \n");
sscanf(Inputs[in++],"%s",&name[i]);
printf("You entered : %s\n", name[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(stricmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("The sorted names are : \n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
getch();
return(0);
}

Sorting letters C programming

I'm trying to make the letters of a matrix sort alphabetically and then be written out in a single string.For instance you type ten words,which are then stored in an array,and every letter has its place in the matrix then,right?But after I've written the words I want to bunch all the letters of all words together and then type all the letters out in alphabetical order.This is what I have so far:
#include <stdio.h>
#include <conio.h>
int main(void){
int i, j, k, f, n, m;
//was trying out various things,that's why I have so many useless ints up there
char word[10][15],temp;
for(i=0;i<=9;i++)
{
printf("Type in wword number %d: ", i+1);
gets(word[i]);
}
for(k=i-1;k>=0;k--)
{
for(m=0;m<k;m++)
if(word[k][f] > word[m][n])
{
temp=word[k][f];
word[k][f]=word[m][n];
word[m][n]=temp;
}
}
printf("Letters alphabetically sorted: ");
for(i=0;i<=9;i++){
for(j=0;j<=14;j++){
printf("%d",word[i][j]);
}
}
printf("\n");
getch();
}
I'm still in the process of learning about matrixes and I've gotten pretty familiar with arrays by now.But the sorting thing is confusing me,this was my attempt but it doesn't work.It lets you write all the words,and then it crashes.
What am I doing wrong here?And how do I correct it?
In your code here:
temp=word[k][f];
word[k][f]=word[m][n];
word[m][n]=temp;
the variables n and f are used uninitialised. That will most likely be the cause of the crash.
f,n are uninitialized. It has garbage and is the reason for crashing at this point.
for(k=i-1;k>=0;k--)
{
for(m=0;m<k;m++)
if(word[k][f] > word[m][n]) // f,n are uninitialized and are error prone
I think this will work..Please excute and tell me..
void main()
{
char word[10][15],temp,sorted_word[15];
int i,j,ii,k,l=0;
for(i=0;i<=9;i++)
{
printf("Type in wword number %d: ", i+1);
gets(word[i]);
}
for(i=0;i<=9;i++)
{
for(j=0;word[i][j]!='\0';j++)
{
ii=i;
for(k=j+1;1;k++)
{
if(ii==9 && word[ii][k]=='\0')
break;
if(word[ii][k]=='\0')
{
ii++;
k=0;
}
if(word[i][j]>word[ii][k])
{
temp=word[i][j];
word[i][j]=word[ii][k];
word[ii][k]=temp;
}
}
sorted_word[l++]=word[i][j];
}
}
sorted_word[l]='\0';
printf("%s",sorted_word);
getch();
}
here the
for(i=0;i<=9;i++)
{ printf("type in wword %d: ",i+1);
gets(word[i]);
}
gets (word[1]);
stores the value from word[1] onwards but where as the character array starts from
word[0].
may be this is not the full solution for u problem
this issue may help u in solving your doubt.

Resources