More output than desired in an array of string - c

I am trying to solve a problem. You can ignore the problem in the code. My doubt is that if I am taking the value of t as 2, still the array outputs 3 strings although I am running the loop only t times for output.
#include<stdio.h>
#include<string.h>
int main(void){
int t;
int i;
int j;
int n;
int c;
int temp;
char result[30][3];
int flag;
scanf("%d", &t);
for(i = 0; i < t; i++){
flag = 0;
scanf("%d", &n);
scanf("%d", &c);
for(j = 0; j < n; j++){
scanf("%d", &temp);
if(c > temp){
c = c - temp;
} else{
flag = 1;
}
}
if(flag == 0){
strcpy(result[i], "Yes");
} else{
strcpy(result[i], "No");
}
}
for(i = 0; i < t; i++){
printf("%s", result[i]);
}
}

Add a \n when you printf a result[i], then you'll find that you actually output 2 strings. For example, if you first strcpy(result[0], "Yes") and then strcpy(result[0], "No"), you'll get the outputs like this:
YesNo
No
In fact, the storage of result is as follows:
result[0]: ['Y']['e']['s']
result[1]: ['N']['o']['\0']
You get "YesNo" when you output result[0], since a two-dimensional array is stored contiguously in the memory and a string ends with \0.
As another example, if you strcpy(result[0], "Hello"), then when you output result[0], you'll get
Hello
and when you output result[1], you'll get
lo
Since the storage in result is as follows:
result[0]: ['H']['e']['l']
result[1]: ['l']['o']['\0']

Related

I don't know why I got it wrong in my code. c language, string iterations

problem
After receiving the string S, write a program that repeats each character R times to create a new string and print it out. That is, you can make P by repeating the first character R times and repeating the second character R times. S contains only the QR Code "alphanumeric" characters.
QR Code "alphanumeric" character is 0123456789ABCDEFGHIJK
Input
The number T (1 ≤ T ≤ 1,000) of test cases is given in the first line. Each test case is given by dividing the number of repetitions R (1 RR 88) and the string S into spaces. The length of S is at least 1 and does not exceed 20 characters.
Output
Output P for each test case.
input Example
2
3 ABC
5 /HTP
output Example
AAABBBCCC
/////HHHHHTTTTTPPPPP
My code:
#include<stdio.h>
int main() {
int a=0;
scanf("%d", &a);
for (int k = 0; k < a; k++) {
int d;
char b[20];
scanf("%d", &d);
scanf("%s", &b);
for (int i = 0; b[i]!=NULL; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
}
}
There is a problem in the code:
scanf("%s", b);
we write "b" instead of "&b"
‘&’ is used to get the address of the variable. C does not have a string type, String is just an array of characters and an array variable stores the address of the first index location.By default the variable itself points to the base address and therefore to access base address of string, there is no need of adding an extra ‘&’
so we can write :
#include<stdio.h>
int main() {
int a=0;
scanf("%d", &a);
for (int k = 0; k < a; k++) {
int d;
scanf("%d", &d);
char b[20];
scanf("%s",b);
for (int i = 0; b[i]; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
printf("\n");
}
}
Improvements
Use size_t to iterate through arrays
NOTE: char b[20];, b decays to pointer (sizeof() operator is an exception)
In line scanf("%s", &b);, &b is not required it will cause undefined behavior, just b is fine
Always check whether scanf() input was successful
Don't use "%s", use "%<WIDTH>s", to avoid buffer-overflow
b[i]!=NULL is quite wrong, NULL is a pointer whereas b[i] is a char, and char can't be compared with pointer, you should check for '\0' or just 0
Initialize your variable b using = {}, then all the elements of b will be 0
Length of b should be 21 +1 for the null terminating character
Final Code
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 0;
if (scanf("%d", &a) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
for (int k = 0; k < a; k++) {
int d;
if (scanf("%d", &d) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
char b[21] = {};
if (scanf("%20s", b) != 1) {
fputs("bad input", stderr);
return EXIT_FAILURE;
}
for (size_t i = 0; b[i] != 0; i++) {
for (int j = 0; j < d; j++) {
printf("%c", b[i]);
}
}
puts("\n");
}
return EXIT_SUCCESS;
}
Input
2
3 ABC
5 /HTP
Output
AAABBBCCC
/////HHHHHTTTTTPPPPP
TRY IT ONLINE

Need some help how to enter a number and count it using array

I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.

How can I take input character in a character array using %c and produce the right output using %s?

This is my code.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
char ch[100];
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf(" %c", &ch[i]);
}
printf("%s\n", strupr(ch));
return 0;
}
At first, I want to take the size of the character array in n variable. After, i want to take n character's and assign the array. The output comes from this program is right but it also produce some garbage values.
For example:
5
s d g h f
Output: SDGHFC└U▄■`
How can i ignore the garbage values from my output?
Simply initialize your array ch[] to all zeros. I.E.
for (i = 0; i < 100; i += 1) { ch[i] = '\0'; }
Put this line just after the declaration of ch[].
As you are reading character the spaces you are providing in your input, will also be considered as characters, and strupr(c) will give some shaggy output, also you have to manually provided null character at the end of your character array. Below program might help you find your answer
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
for(i = 0; i < n; i++){
char temp;
scanf("%c", &temp);
if(temp != '\n')
ch[i] = temp;
else
break;
}
ch[n] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Your Input should look like
5
sdghf
To give input with spaces. Program will look like.
#include<stdio.h>
#include<string.h>
int main()
{
int n, i;
scanf("%d", &n);
fflush(stdin);
char ch[100];
char temp;
i = 0;
while(scanf("%c", &temp)){
if(temp == ' ')
continue;
if(temp != '\n')
ch[i++] = temp;
else
break;
}
ch[i] = '\0';
printf("%s\n", strupr(ch));
return 0;
}
Now, you can give your character in any arrangement as you want.

Segmentation fault 11 using arrays

I am a beginner with coding and I got my code to compile but when I input integers, I get segmentation fault. Please help.
The problem is: I need to first get how many students there are then the next inputs will be the marks of those students. So if inputed 3, the next inputs should be 3 marks of the 3 students. Then the input should be either g(girl) or b(boy). From there, if boy, I need to sum up all the odd marks.
THIS IS MY CODE:
#include<stdio.h>
#include<stdlib.h>
int marks_summation(int* marks, int number_of_students, char gender){
int i=0, sum=0;
int marksforGirls=0, marksforBoys=0;
char g;
for(marks = 0; *marks <= number_of_students; marks++){
if(gender == g){
do{
if(marks[i]%2 == 0){
marksforGirls = marks[i];
i++;
sum += marksforGirls;
}
} while(*marks<=number_of_students);
}
else{
do{
if(marks[i]%2 != 0){
marksforBoys = marks[i];
i++;
sum += marksforBoys;
}
} while (*marks<=number_of_students);
}
}
return 0;
}
int main(){
int i=0, number_of_students=0;
int *marks=0;
int sum=0;
char gender;
scanf("%d",&number_of_students);
marks = (int*)malloc(number_of_students * sizeof(int));
for(i=0; i<number_of_students; i++){
scanf(" %d", &marks[i]);//for every marks put in, it will go into marks
}
scanf("%c",&gender);
marks_summation(marks, number_of_students, gender);
printf("%d", sum);
free(marks);
return 0;
}
The following line is not doing what you might think it does:
for(marks = 0; *marks <= number_of_students; marks++)
I believe you'd want to use an index to access each of marks elements.
As others have pointed out, the problem is in the for loop. Besides pointers being wrong, your loop condition is also wrong. Furthermore your function doesn't return anything. Also, both of your do-while loops are infinite loops.
Try this:
int mark_sum(int *marks, int number_of_students, char gender){
int sum = 0;
for(int i = 0; i < number_of_students; ++i){
if(gender = 'g'){
if(marks[i] % 2 == 0)
sum += marks[i];
} else {
if(marks[i] % 2 != 0)
sum += marks[i];
}
}
return sum;
}
Also, in main you need to actually store the value returned by the function:
int sum = mark_sum(marks, number_of_students, gender);

making a word search puzzle?

I've made a program that allows you to choose the size of the grid and it allows you to enter up to 20 words. Now I have to insert the entered words horizontally into the original array using a function. The function must return a value for success and a value for failure to enter the word into the puzzle board. I need help getting started with what the actual function should look like along with the function prototype. Pseudocode would be helpful. I'm a fairly new programmer so any help is great. Thank you
#include<stdio.h>
#include<string.h>
void printmatrix(char matrix[][20],int);
void inserthor(char matrix[][20],int);
int main(void)
{
//declare variables
char matrix[20][20];
char words[20][100];
int x;
int a,b;
int i=0;
int n=0;
for (a=0;a<20;a++)
{
for (b=0;b<20;b++)
{
matrix[a][b] = '+';
}
}
while (x<10 || x>20)
{
printf("How large would you like the puzzle to be (between 10 and 20):\n");
scanf("%d",&x);
}
printmatrix(matrix,x);
//part 3
printf("Enter up to 20 words to hide in the puzzle.\n");
printf("Enter the word 'done' after your last word if entering less than 20 words.\n");
for (i = 0; i < 20; i++)
{
printf("Enter word %2d:\n", i+1);
if (scanf("%99s", words[i]) != 1 || strcmp(words[i], "done") == 0)
break;
}
n = i;
printf("%d words entered\n", n);
for (i = 0; i < n; i++)
printf("Word %2d = [%s]\n", i+1, words[i]);
return 0;
}
void printmatrix(char matrix[][20],int x)
{
int i,j;
printf("Empty Puzzle:\n");
for (i=0;i<x;i++)
{
for (j=0;j<x;j++)
{
printf(" %c ", matrix[i][j]);
}
printf("\n");
}
}
Your function prototype
void inserthor(char matrix[][20],int);
lacks the parameter with the word to be entered and the value to be returned. You could use
char *inserthor(char matrix[][20], int order, char *word)
{
int i, j, l = strlen(word);
for (i = 0; i < order; ++i)
for (j = 0; j <= order-l; ++j)
if (matrix[i][j] == '+') return memcpy(&matrix[i][j], word, l);
return NULL;
}
which returns the address of the inserted word for success and NULL for failure.

Resources