I am new to coding and would really appreciate if you could help me with this question. I can't find out why my code does not give me the correct result. Thank you for your time!!
Q:
Using a first dimensional array, count the number of closing brackets and open brackets. Input must be in one line.
Ex. Input: (()))
Output: 3 2
I used an array to receive the input in one line and the for loop to count the number of opening/closing brackets.
#include <stdio.h>
int main(){
char str[1000]; int l=0;r=0;
printf("Enter:\t");
gets(str);
int length=sizeof(str)/sizeof(str[0]);
for(int i=0;i!=EOF && i<length;i++)
{
if(str[i]=='(')
l++;
else if(str[i]==')')
r++;
}
printf("%d %d",l,r);
}
Expected
Input: (())
Output: 2 2
What I get
Input: (())
Output: 6 2
i!=EOF is not needed as this is not a file
int length=sizeof(str)/sizeof(str[0]) doesnt give the length of the string strlen() from #include <string.h> does
your loop is wrong (actually your conditions)
for(size_t i = 0; i < strlen(str);i++)
{
if(str[i]=='(')
{
l++;
}
if(str[i]==')')
{
r++;
}
}
There are mistakes which are covered in basic C learning.
sizeof(str)/sizeof(str[0]); returns size of str array which is in your case 1000. To get length of user input, use strlen function: int length = strlen(str).
Later, use your for loop as for(int i=0;i<length;i++) or better:
//Include string.h on beginning of file
#include <string.h>
size_t length = strlen(str);
for (size_t i = 0; i < length; i++) {
//Do your if.
}
You also have a syntax error at the declaration of r.
You would either have int l=0,r=0;
Or
Int l=0;
Int r=0;
Although, the compiler should have warned you about this.
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 am new to c programming and would like to write a program which has the following requirement:
Input: The number of inputs n, then n input chars , for example, 3 welcome to hku
Output concatenated chars, for example, welcomehku
However, I discovered a problem that when I submit the codes as following to the c autochecking platform, the output is ~~~~welcometohku instead of welcometohku.
Would anyone like to give help on the issue? Thank you very much to all of you.
#include<stdio.h>
#include<string.h>
int main(){
int num; /* array with 50 elements */
int i = 0;
char iarray1[100];
/* read array */
scanf("%d", &num);
char iarray[num][100];
for (i = 0; i < num; i++) {
scanf("%s", iarray[i]);
}
/* print array elements in reverse order */
for (i = 0; i < num; i++) {
strcat(iarray1,iarray[i]);
}
//display the concatenated string
printf("%s",iarray1);
return 0;
}
You need to initialize iarray1
Try
char iarray1[100] = {0};
The reason is that an uninitialized iarray1 may contain any value. So when you do the first strcat it may happen the string you want to concatenate is appended to some gargabe value.
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 want to print multiple character using printf. My approach up to now is this-
#include <stdio.h>
int main()
{
printf("%*c\n", 10, '#');
return 0;
}
But this only prints 9 spaces before the #.
I want to print it like this-
##########
I am unable to figure out how to do this. Please help me?
You can not use printf like that to print repetitive characters in Ansi C. I suggest you to use a loop like this -
#include <stdio.h>
int main()
{
int i;
for(i = 0; i < 10; i++) putchar('#');
return 0;
}
Or if you have absolutely no desire to use loops, you can do something like this-
#include <stdio.h>
int main()
{
char out[100];
memset(out, '#', 10);
out[10] = 0;
printf("%s", out);
return 0;
}
By the way, using printf like this also works-
#include <stdio.h>
int main()
{
printf("%.*s", 10, "############################################");
return 0;
}
I think the best approach, if you have an upper limit to the number of characters to be output is:
printf("%.*s", number_of_asterisks_to_be_printed,
"**********************************************************************");
I think this will also be the most efficient, portable way to do that.
this will print ten # characters, followed by a newline
char tenPounds[] = "##########";
printf( "%s\n", tenPounds);
I am working on a similar problem in "The C Programming Language" book (exercises 1-13 and 1-14). My own program, to start simply, is to count the occurrences of the digits 0 to 9 in a given input, and print a horizontal histogram made of '=' bars according to each count.
To do this, I created the following program;
main() {
int c, ix, k;
int nDigit[10];
//Instantiate zero values for nDigits array
for(ix = 0; ix < 10; ix++) {
nDigit[ix] = 0;
}
//Pull in input, counting digit occurrences and
//incrementing the corresponding value in the nDigit array
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9') {
++nDigit[c-'0'];
}
}
//For each digit value in the array, print that many
//'=' symbols, then a new line when completed
for (ix = 0; ix < 10; ix++) {
k = 0;
while (k <= nDigit[ix]) {
putchar('=');
k++;
}
printf("\n");
}
}
Note that this is a work in progress. A proper histogram should include axes labels, and most importantly this program does not account for digits of zero count. If the input includes five 1's but no 0's, there is no visual way to show that we have no zeros. Still, the mechanism for printing multiple symbols works.
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