#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32];
char input[32];
int number;
int i;
for(i=0;i<10;i++)
{
fgets(input,sizeof(input),stdin);
sscanf(input,%s,name[i]);
}
//assume that we don't know variable name have 10 element of arrays.
//function to count how many elements of arrays to stored at number.
for(i=0;i<number;i++)
{
printf("%s",name[i]);
}
}
What function can count the elements of the arrays?
How about initialising your target strings to 0 then checking if they are not null whilst printing?
#include <stdio.h>
#include <string.h>
int main()
{
char name[32][32] = {0};
...
for(i=0;i<32;i++)
{
if(name[i][0]!='\0')
printf("%s",name[i]);
}
}
This one is a solution.
But i don't know why it is not working while trying to make a array_length function.
#include<stdio.h>
int main(){
int a[]={1,2,3,4,5,6,7,8,9,0};
int len;
len = sizeof(a)/sizeof(*a);
printf("Length is %d\n",len);
return 0;
}
C does not maintain this kind of information. It is up to the developer to implement some way of knowing that the item in the array is valid or not. Typically this is done by selecting an 'invalid value', which is a value that is never going to occur in real data. Another way of doing this is to separately maintain a count.
This is all fine for learning C. If you are doing this for the real world, you would be much better off using data structures like lists. If you are using C++, I would suggest that you learn STL.
Simple C solution would be something like this. The value of "empty" is used to indicate any value which will not occur normally in the input. You can change the #define to any other value you want like "-----" or ".". We begin by initializing the entire array to "empty"
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 32
#define MAX_LENGTH 32
#define EMPTY "empty"
int main(void)
{
char name[MAX_ITEMS][MAX_LENGTH];
char input[MAX_LENGTH];
int i;
for(i = 0; i < MAX_ITEMS; i++)
{
strcpy(name[i], EMPTY);
}
for(i = 0; i < 10; i++)
{
fgets(input, MAX_LENGTH, stdin);
sscanf(input, "%s", name[i]);
}
for(i = 0; strcmp(name[i], EMPTY) && i < MAX_ITEMS; i++)
{
printf("%s\n", name[i]);
}
return(0);
}
Related
I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}
I got a task from my college which is to find the length of a string using pointers in a function.Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define max 100
int lengthchar(char *array1[])
{
int a, x = 0;
for (a = 0; *(array1++) != '\0'; a++)
{
x++;
}
return x;
}
int main()
{
char arr1[max];
int length;
printf("Enter string\n");
gets(arr1);
length = lengthchar(arr1);
printf("Length=%d", length);
return 0;
}
But when I give input something bellow:
Enter string: av
Length=9
It shows the wrong length, what's my mistake?
This is because of the way to pass a string pointer as an argument to the function.
Just change char *array1[] to char *array1 or array1[].
Have a look at the implementation below:
int lengthchar(char array1[])
{
int a,x=0;
for(a=0;*(array1++)!='\0';a++)
{
x++;
}
return x;
}
PS: variable a can be removed by using a while loop.
In your function signature, you are telling the compiler that lenghtchar() expects a pointer to character strings, or **char in other words.
What you really want to do is to change your function from int lengthchar(char *array1[]) to int lengthchar(char array1[]) or int lengthchar(char *array1). This is a bit tricky since in C, you can address an array by using the address of its first element (aka, by using pointer to its first item).
Expert C Programming has a dedicated chapter on this topic.
Now, coming to your lengthchar() function, I would do some refactoring to eliminate the variable a and use a while loop instead. I have also included another alternative implementation that relies on pointer arithmetic (more fun to me :) )
Note also that I used fgets() instead of gets() which is considered deprecated since it does not do any bounds checking.
#include <stdio.h>
#include <stdlib.h>
#define max 100
/*
* returns the lenght of the string excluding the terminating
* NULL character
*/
int lengthchar(char *array1) {
int x = 0;
while (*array1++)
x++;
return x-1;
}
int lengthchar1(char *array1){
char *p;
for (p = array1; *p; p++)
;
return p - array1 - 1; /* -1 for \0 */
}
int main() {
char arr1[max];
int length;
printf("Enter string\n");
fgets(arr1, max, stdin);
length = lengthchar(arr1);
printf("Length=%d", length);
return 0;
}
On declaring or defining a function that shall take an array of type T as an argument, use the notation: T *array or T array[]; T may stand for any valid C data type such as char, int, float, double, etc...
As for your loop, the variable a seems to be redundant because it has no effect on any part of the program. The return value of the function lengthchar() is one more than the number of characters inputted.
Also you should avoid the function gets() because it is deemed dangerous and has been removed from the C standard; use fgets() instead.
Your code should look something like this:
#include <stdio.h>
#include <string.h>
#define max 100
int lengthchar(char *str)
{
int len = 0;
while (*str++)
{
len++;
}
return len;
}
int main()
{
char str1[max];
printf("Enter string:");
fgets(str1, max, stdin);
str1[strcspn(str1, "\n")] = 0; // remove new-line character
int length = lengthchar(str1);
printf("Length = %d\n", length);
return 0;
}
I tried to write a program to count the number of occurrences of a given character in a given string.
Here's the program:
#include <stdio.h>
#include <string.h>
int find_c(char s[], char c)
{
int count;
int i;
for(i=0; i < strlen(s); i++)
if(s[i] == c)
count++;
return count;
}
int main()
{
int number;
char s[] = "fighjudredifind";
number = find_c(s, 'd');
printf("%d\n",number);
return 0;
}
I was expecting the following output:
3
since the number of occurrences of the character 'd' in the string s is 3.
Each time I tried to run the program, a different number was displayed on the screen. For example, I got the following output while running the program one time:
-378387261
And got this output, when running the program another time:
141456579
Why did I get the wrong output and how can I fix this?
Thanks in advance!
Well, Your code is good. Only mistake is, you did not initialize the count to 0. If you do not initialize the variable will hold the garbage value and you will be performing operations on that value. As a result, in the earlier case, you got all the garbage values, when you execute the program each time.
Here is the code:
#include <stdio.h>
#include <string.h>
int find_c(char s[], char c) {
int count=0;
int i;
for(i=0; i < strlen(s); i++)
if(s[i] == c)
count++;
return count;
}
int main() {
int number;
char s[] = "fighjudredifind";
number = find_c(s, 'd');
printf("%d\n",number);
return 0;
}
In C Integers are not automatically initialized to zero.
The problem is that the count variable is not initialized.
Try initializing the count variable in the find_c function to zero.
I have I problem. I get 2 warnings from console, but I dont know what's wrong with my code. Can you have look?
Program suppose to show lines with at least 11 characters and 4 numbers
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
if(isalpha(line)) numberAlpha++;
else if(isdigit(line)) numberDigit++;
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Both isalpha() and isdigit() takes an int, not a char *, as argument.
In your code, by passing the array name as the argument, you're essentially passing a char * (array name decays to the pointer to the first element when used as function argument), so, you're getting the warning.
You need to loop over the individual elements of line and pass them to the functions.
That said, just a suggestion, for hosted environment, int main() should be int main(void) to conform to the standard.
isalpha and isdigit are supposed to test if a char taken as int (a char can be safely converted to an int) is the encoding of an alphanumeric or digit character. You pass a char array, not an individual char. You need to test each char of the string you got, so you need a loop as:
for (int i=0; i<strlen(line); i++) {
if (isalpha(line[i])) numberAlpha++;
...
}
It is better to compute the length once:
int length = strlen(line);
for (int i=0; i<length; i++) {
...
}
You may also use a pointer to move along the string:
for (char *ptr = line; *ptr!=`\0`; ptr++) {
if (isalpha(*ptr)) ...
...
}
isalpha() and isdigit() functions take an int. But you are passing a char* i.e. the array line gets converted into a pointer to its first element (see: What is array decaying?). That's what the compiler complains about. You need to loop over line to find the number of digits and alphabets in it.
Also note that fgets() will read in the newline character if line has space. So, you need to trim it out before counting.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
line[strcspn(line, "\n")] = 0; // Remove the trailing newline, if any.
for (size_t i = 0; line[i]; i++) {
if(isalpha((unsigned char)line[i])) numberAlpha++;
else if((unsigned char)isdigit(line[i])) numberDigit++;
}
printf("alpha: %d, digits:%d \n", numberAlpha, numberDigit);
}
return 0;
}
Ok, i got something like this:
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
int i;
for(i=0; i<strlen(line); i++){
if(isalpha(line[i])) numberAlpha++;
else if(isdigit(line[i])) numberDigit++;
}
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Now the question is, if it is passible to make it first accepts data and then display only those line which follows the if statment. Now it shows line just after input it.
This is a code that has to take an input array from the user and input the same after removing the duplicates. However, I am unsure on how to incorporate an input array in this, and right now it has the elements hardcoded. This is my first week of programming so I apologize if this is a silly question. This is the code:
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int l[nelems] = {1,2,3,1,4,4,5,6};
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
Try using a for loop and scanf.
int i;
for(i=0;i<nelems;i++){
scanf("%d",&l[i]);
}
This is what you need.
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int i;
int l[nelems] ;
for(i=0;i<nelems;i++)
{
printf("enter %d number :",i);
scanf("%d",&l[i]);
}
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
If you like int-type array, you can just declare another one:
int input[nelems];
and follow the user968000 advice, remembering that when you are typing the sequence in your console you have to put a white space between each number.
To avoid that, I'd rather use char-type arrays, declared as follows:
char l[nelems] = {'1', '2', '3' /*etc.*/};
char input[nelems];
Then you make a for loop, as user968000 suggested:
int i;
for(i=0;i<nelems;i++)
scanf("%c", &input[i]);
In this case you won't need the white spaces between the digits. Notice the '&' character in the scanf function: just put it as I showed, you'll surely learn what it is in next lessons.
So you have an input array and you can handle it as you want.