I'm just doing practice problems out of my C book and am stuck on this one:
Write a program that creates an array with 26 elements and stores the 26
lowercase letters in it. Also have it show the array contents.
I'm getting stuck here
char abc[26];
char index;
for(index="a", abc[0]; index<="z"; index++, abc[0]++){
abc[]=abc[index]
}
printf("%s", abc);
I'm mostly confused on how to append something to an array when its in a for loop, and how to print the entire array.
No need to append as mentioned in the comments, also be careful with char i= "a" and char i = 'a'
here is a code, that does create array of 26 lower case alphabet
#include <stdio.h>
int main()
{
char arr[27];
int i;
for(i=0; i<26; i++)
{
arr[i] = 'a'+i;
}
arr[i]='\0'; //null terminate the array
printf("%s\n", arr);
}
Related
I am trying to make an array of character Arrays. The program will read in sentences and store the sentences in a character array, and then that character array will be stored in another array. After reading numerous websites and Stack Over Flow pages I think it can be done like this. The program breaks when trying to store my character array into another array, so i'm not sure how to correct my code.
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(int ac, char *av[])
{
int size; //number of sentences
char strings[100];// character array to hold the sentences
char temp;
printf("Number of Strings: ");
scanf_s("%d", &size); // read in the number of sentences to type
char **c = malloc(size); //array of character arrays
int i = 0;
int j = 0;
while (i < size) //loop for number of sentences
{
printf("Enter string %i ",(i+1));
scanf_s("%c", &temp); // temp statement to clear buffer
fgets(strings, 100, stdin);
// **** this next line breaks the program
c[i][j] = strings; // store sentence into array of character arrays
j++;
i++;
}
printf("The first character in element 0 is: %d\n", c[0][0]);
system("PAUSE");
return 0;
}
Al you need to do is allocate the memory for the string just read and copy the string:
c[i][j] = strings; // replace this with:
c[i]= malloc(strlen(strings)+1);
strcpy(c[i],strings);
Sadly char **c is not array of characters arrays. But this will properly allocate a 2d array dynamically if you follow
char (*c)[SIZE];
And then doing this
c = malloc(sizeof(char[LEN][SIZE]));
Then you do what you are trying to do.
for(size_t i = 0; i < LEN; i++){
if(fgets(c[i],SIZE,stdin)){
...
}
}
Or you can do it like this
char **c = malloc(LEN);
..
for(size_t i = 0; i < LEN; i++){
c[i] = malloc(SIZE);
...
}
But again c is nothing but jagged array of characters.
Check the return value of malloc and free the dynamically allocated memory when you are done working with it.
Listen dude,
Do you want to store the words in the character array and then store this in another array.
It is what you want ?
If yes then you can do the following.
Use stdlib by using # include <stdlib.h> .
This lets you use string functions directly.
Now read every word as a string and make array of strings.
So now if you number of strings is n, define an array for that as string my_array[n] and scan each word using scanf("%s",&my_array [i]).
In this way you will get an array of strings.
i am working on a school project and i need to enter the national teems for a backetball tournament. I need to enter 3 teams, and when i have a problem with printing, this is just a test print, i kicks me out of a program, this is in C language. Best Regards.
#include<stdio.h>
int main()
{
char t[30];
int score1, score2;
int i;
printf("Enter the National Teams\n");
for(i=1;i<4;i++)
{
scanf("%s", &t[i]);
}
for(i=1;i<4;i++)
{
printf("%s", t[i]);
}
return 0;
}
Use 2-D char array as follows :
#include<stdio.h>
int main()
{
char t[30][30];
int score1, score2;
int i;
printf("Enter the National Teams\n");
for(i=1;i<4;i++)
{
scanf("%s", t[i]);
}
for(i=1;i<4;i++)
{
printf("%s", t[i]);
}
return 0;
}
2-D char array t[X][Y] : X is the max number of strings and Y is the max length of string possible
You could also do something like this:
#include <stdio.h>
int main(){
int i;
char (*teamName)[10];
for ( i=0; i < 3; i++ ){
scanf("%s", &teamName[i]);
}
for( i = 0; i < 3; i++ ){
printf("%s\n", teamName[i]);
}
return 0;
}
It does the exact same thing as the 2D array suggestion below, but it uses pointers to do it.
The big thing to remember is that strings in C are arrays of type char, with a null terminator character (ASCII 0) at the end. What you've done here is to declare a char array of length 30. Your program is trying to shovel a string (which is a char array) into each slot in the array, resulting in a crash.
What you really want is to create an array of arrays of chars (otherwise known as a 2D array), and store one string in each slot of that (and print it again afterwards).
To clarify, think of an array like a series of buckets, each of which can contain one value (in this case, a char):
[ ][ ][c][ ][a]
What your program is trying to do is shove a whole string (which is a whole bunch of chars) into each bucket:
[a][ ][ ][ ][ ]
z
c
f
b
Wondering how store different strings in an array.
For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on
int
main(int argc, char *argv[]) {
char variable[1000];
int i;
printf("enter a variable\n");
scanf("%s", variable);
for (i = 0; ??? ;i++) {
printf("The variable entered was: %s\n",variable[i]);
}
return 0;
Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest
Thanks!
You can use 2D array to store multiple strings. For 10 strings each of length 100
char variable[10][100];
printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)
scanf("%100s", variable[i]);
Better to use fgets to read string.
fgets(variable[i], sizeof(variable[i]), stdin);
You can also use dynamic memory allocation by using an array of pointers to char.
The most efficient way is to have an array of character pointers and allocate memory for them as needed:
char *strings[10];
int main(int ac, char *av[]) {
memset(strings, 0, 10 * sizeof(char *));
for (int i = 0; i < 10; i += 1) {
char ins[100];
scanf("%100s", ins);
strings[i] = malloc(strlen(ins) + 1);
if (strings[i]) {
strcpy(strings[i], ins);
}
}
}
variable[0] has just stored first letter of string. If you want to store multiple strings in an array you can use 2D array.
it has structure like
arr[3][100] = { "hello","world", "there"}
and you can access them as
printf("%s", arr[0]); one by one.
scanf returns number of successful readed parameters;
use 2D array for string-array
Never go out of bounds array
#include <stdio.h>
//Use defines or constants!
#define NUM_STRINGS 10
#define MAX_LENGTH_OFSTRING 1000
int main() {
char variable[NUM_STRINGS][MAX_LENGTH_OFSTRING +1 /*for '\0' Null Character */];
int i = 0;
printf("enter a variable\n");
while(scanf("%s", variable[i]) > 0){//if you print Ctrl+Z then program finish work. Do not write more than MAX_LENGTH_OFSTRING symbols
printf("The variable entered was: %s\n",variable[i]);
i++;
if(i >= NUM_STRINGS)
break;
}
return 0;
}
at the moment, I'm trying some pointer stuff in C. But now, I have a problem with a pointer array. By using my code below, I get a strange output. I think there is a big mistake in the code, but I can't find it.
I just want to print the strings of the pointer array.
#include <stdio.h>
int main(void)
{
char *words[] = {"word1", "word2", "word3"};
char *ptr;
int i = 0;
ptr = words[0];
while(*ptr != '\0')
{
printf("%s", *(words+i));
ptr++;
i++;
}
return 0;
}
Output: word1word2word3Hã}¯Hɡ
Thanks for helping.
while(*ptr != '\0')
{
printf("%s", *(words+i));
ptr++;
i++;
}
initially, ptr points to the 'w' in "word1". So the loop iterates five times until *ptr == '\0'. But the array words contains only three elements, thus the fourth and fifth iteration invoke undefined behaviour and garbage is printed when the bytes after the words array are interpreted as pointers to 0-terminated strings. It could easily crash, and if you try it on other systems, with other compilers or compiler settings, it will sometimes crash.
You could translate the loop to
for(i = 0; i < strlen(words[0]); ++i) {
printf("%s", words[i]);
}
to see more easily what it does.
If you want to print out the strings in the words array, you can use
// this only worls because words is an actual array, not a pointer
int numElems = sizeof words / sizeof words[0];
for(i = 0; i < numElems; ++i) {
printf("%s", words[i]);
}
As words is an actual array, you can obtain the number of elements it contains using sizeof. Then you loop as many times as the array has elements.
I think you intended ptr to iterate through the items in the words array, but in fact it is actually iterating through the characters of "word1". To iterate through the words array, while pretending to not know the number of items to iterate through, then change the while condition as follows:
int main(void)
{
char *words[] = {"word1", "word2", "word3"};
char numWords = sizeof(words) / sizeof( words[0]);
int i = 0;
while(i < numWords)
{
printf("%s", *(words+i));
i++;
}
return 0;
}
If you really want to use ptr to iterate through the items of the words array, then change the words array and the while condition as follows:
int main(void)
{
char *words[] = {"word1", "word2", "word3", NULL};
char *ptr[] = words;
int i = 0;
while(ptr[i] != NULL)
{
printf("%s", *(words+i));
i++;
}
return 0;
}
I have a problem in C where i have to find number of occurrence of each character in a string.Suppose i have string like "amitamt" and output should be like "a2m2it2" .I have a routine from which i can find no of occurrence of a particular character.
int count_chars(const char* string, char ch)
{
int count = 0;
int i;
int length = strlen(string);
for (i = 0; i < length; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
But I am not sure how could I count each character of string
If you have an ASCII string, create an int array of size 256. Then loop through the string and increment the value in the int array on position x. While x is the ASCII value of the character in your string you're looping through.
if i have any mistakes like syntax please excuse as im working on vb , Im unable to figure out where to put braces or brackets ,
and I belive strchr makes your task easier
#include <stdio.h>
#include <string.h>
int str_occ (char *pch ,char a)
{
int i = 0;
char *p;
p=strchr(pch,a);
while (p!=NULL)
{
i = i+1;
p = strchr(p+1,a);
}
return i;
}
To explain the code *pch is the string you have to pass ,char a is the alphabet you are searching to find how many times its occurring and int i returns the value of number of occurrences
say sample
int main()
{
char a[]="hello world";
int i;
i=str_occ(a,'l');
printf("%d",i);
}
output is 3
You can make the code as per your requirements, keep caling the function inside a loop , I mean rotate your elements