i am doing code practicing which is below
int main() {
int N, Q, cnt;
scanf("%d", &N);
char **str1=(char**)malloc(sizeof(char*)*N);
for(int i=0; i<N; i++) {
str1[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str1[i]);
}
scanf("%d", &Q);
char **str2=(char**)malloc(sizeof(char*)*Q);
for(int i=0; i<Q; i++) {
str2[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str2[i]);
}
for(int i=0; i<Q; i++) {
for(int j=0, cnt=0; j<N; j++) {
// if statement
if( strcmp(str2[i], str1[j]) == 0) cnt++;
}
printf("%d\n", cnt);
}
for(int i=0; i<N; i++){
free(str1[i]);
}
for(int i=0; i<Q; i++) {
free(str2[i]);
}
free(str1);
free(str2);
return 0;
}
STD input are
4
aaa
bbb
ccc
aaa
3
aaa
bbb
cca
than print out
2
1
0
because
'aaa' is 2 times
'bbb' is 1 times
'cca' is 0 times
if( strcmp(str2[i], str1[j]) == 0) cnt++;
however the if statement, doesn't count cnt++
whats wrong, my code with strcmp() ?
You have two variables called cnt.
One declared on this line:
int N, Q, cnt;
and scoped to the entire function.
One declared on this line:
for(int j=0, cnt=0; j<N; j++) {
and scoped to the for loop.
The statement cnt++ modifies the second one since it's inside the for loop.
The statement printf("%d\n", cnt); prints the first one since it's outside the for loop.
Related
Okay so I'm a beginner programmer so any tips on any part of the code are greatly appreciated,
but the main question is why does the code in function int longestSequence(int n,int array[n]);work when placed in main, but not when called from the function?
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int longestSequence(int n,int array[n]);
int main()
{
int n;
scanf("%d", &n);
int mat[n][n];
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
scanf("%d", &mat[i][j]);
}
}
int arraySize = n*n;
int array[arraySize];
int arrayIndex = 0;
for(int i=0; i<n; i++){
if(i%2 == 0){
for(int j = 0; j<n; j++){
array[arrayIndex++] = mat[i][j];
}
}else{
for(int j = n-1; j>=0; j--){
array[arrayIndex++] = mat[i][j];
}
}
}
/// Here's the same code that works when in main
// int numOfSequental = 0;
// int maxNumOfSequental = INT_MIN;
// for(int i = 0; i<n; i++){
// if(niz[i] == (niz[i+1]-1)){
// numOfSequental++;
// if(numOfSequental>maxNumOfSequental){
// maxNumOfSequental = numOfSequental;
// }
// continue;
// }
// numOfSequental = 0;
// }
//calling the function in printf
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
return 0;
}
int longestSequence(int n,int array[n])
{
int numOfSequental = 0;
int maxNumOfSequental = INT_MIN;
for(int i = 0; i<n; i++){
if(array[i] == (array[i+1]-1)){
numOfSequental++;
if(numOfSequental>maxNumOfSequental){
maxNumOfSequental = numOfSequental;
}
continue;
}
numOfSequental = 0;
}
return maxNumOfSequental+1;
}
"the main question is why does the code in function int longestSequence(int n,int array[n]); work when placed in main, but not
when called from the function?"
As called it should not work in either place.
printf("Length of the sequence: %d", longestSequence(arraySize, array[arraySize]));
// ^^^^^^^^^^^
return 0;
Note first that the index passed: arraySize is one beyond the legal index for array. In C, indexing is zero based, and so it goes from 0 - arraySize - 1
More importantly though the 2nd argument of longestSequence should be a pointer to the array, not an indexed element of the array.
printf("Length of the sequence: %d", longestSequence(arraySize, array));
return 0;
Also, in general, to compare subsequent numbers in an array with size n, the range of comparisons should be limited to:
a[i] == a[i+1] //for i == 0 through i == n-1
Change:
for(int i = 0; i<n; i++){
// ^^^
if(array[i] == (array[i+1]-1)){//array out of bounds when i == n
// ^^^
To
for(int i = 0; i<n-1; i++){
// ^^^^^
if(array[i] == (array[i+1]-1)){//i will never reach n
EDIT:
One last thing addresses comment about replacing calls to scanf() with using the 2nd argument of main. First to do that the code must include the prototype of main: int main(int argc, char *argv[]);. With this prototype, the program as called from the command line can now include command line arguments, eg: if running from CMD prompt in Windows:
C:\dev> myProg.exe 3 1 2 3 4 5 6 7 8 9
Inside your program then arguments of argc and argv[]` are populated as follows:
argc == 11 //total number of arguments
argv[0] == "myProg.exe" //program name is alway in argv[0]
argv[1] == "3"
argv[2] == "1"
...
argv[10] == "9"
Which should translate to creating a 3x3 array populated with the 9 subsequent values.
So the first statements in your code could now be: (in psuedo code)
int n = atoi(argv[1]);//check value of n before using
int array[n][n];
int index = 2;
for(int i = 0; i<n ; i++)
for(int j = 0; j<n ; j++)
array[i][j] = atoi(argv[index]);
index++;
It's a program that requires the user to enter the values of two 3 by 3 matrix then finds the sum of both matrices and prints out the same together with the added matrices but for some reason after entering the values of both matrices the a value in matrix gets altered then it affects the sum but at times it doesn't
#include<stdio.h>
void main(){
int matrix1[2][2];
int matrix2[2][2];
int sumMatrix[2][2];
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix one's values> ");
scanf("%d", &matrix1[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("Matrix[%d][%d]\n", i, j);
printf("Enter matrix two's values> ");
scanf("%d", &matrix2[i][j]);
}
printf("\n");
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", matrix1[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", matrix2[i][j]);
}
printf("\n");}
printf("\n");
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
printf("%d ", sumMatrix[i][j]);
}
printf("\n");
}
}
You're declaring matrixes of size 2x2 and access them as if they were 3x3. What's happening more precisely is a buffer overflow, you write somewhere you shouldn't, and by doing so you overwrite other variables.
Lad, that is array overflow.
int matrix1[2][2];
But in the loop, you may get matrix1[2][1], matrix1[2][2].
Ok so clearly I'm the idiot. I thought array sizes are set based on the number of indices they'll have, so instead of int matrix1[2][2] it should be int matrix [3][3]
Assume the matrices to be of the form,
The required output on stdout using C language should be
My code:
#include<stdio.h>
int main(void)
{
int size, i=0, j=0;
printf("Enter the size of the array:");
scanf("%d",&size);
int A[size][size], B[size][size], C[size][size];
//Entering the values in A[][]
printf("enter the elements of Array A:\n");
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
scanf("%d",&A[i][j]);
//Entering the values in B[][]
printf("enter the elements of Array B:\n");
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
scanf("%d",&B[i][j]);
// Calculating C[][]=A[][]+B[][]
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
C[i][j]=A[i][j]+B[i][j];
i=0;
j=0;
while(i<size)
{
if( i==size/2)
printf("%*c%*c\n\n",6*size+1,'+',13*(size-1),'=');
while(j<size)
printf("%d\t",A[i][j++]);
j=0;
while(j<size)
printf("%d\t",B[i][j++]);
j=0;
while(j<size)
printf("%d\t",C[i][j++]);
j=0;
printf("\n\n");
i++;
}
}
But this code only gives the desired output when size=2.
But I need a solution which works for all values of size entered by the user.
you use a tab (8 columns) to go to the next column, so replace
printf("%*c%*c\n\n",6*size+1,'+',13*(size-1),'=');
by
printf("%*c%*c\n\n",8*size-4,'+',8*size,'=');
example :
of course that supposes all numbers need up to 7 columns
If you want to always have 1 line between each line with numbers modify the while to have :
while(i<size)
{
if( i==size/2)
printf("%*c%*c\n",8*size-4,'+',8*size,'=');
else
putchar('\n');
while(j<size)
printf("%d\t",A[i][j++]);
j=0;
while(j<size)
printf("%d\t",B[i][j++]);
j=0;
while(j<size)
printf("%d\t",C[i][j++]);
j=0;
putchar('\n');
i++;
}
producing :
Out of that I encourage you to check scanf always return 1 else you do not detect an invalid input
This code will solve my question,
int size_odd_or_even=size%2;
int check=1;
while(i<size)
{
if( size_odd_or_even==0 && i==size/2 && check==1)
{
printf("\n%*c%*c\n",8*size-4,'+',8*size,'=');
check=0;
continue;
}
if( size_odd_or_even==1 && i== (int)(size/2) )
{
while( j<size-1)
printf("%d\t",A[i][j++]);
printf("%d + ",A[i][j]);
}
else
{
while( j<size)
printf("%d\t",A[i][j++]);
}
j=0;
if( size_odd_or_even==1 && i== (int)(size/2))
{
while( j<size-1)
printf("%d\t",B[i][j++]);
printf("%d = ",B[i][j]);
}
else
{
while(j<size)
printf("%d\t",B[i][j++]);
}
j=0;
while(j<size)
printf("%d\t",Sum[i][j++]);
j=0;
if( size_odd_or_even==0 && !(i==size/2-1) )
printf("\n\n");
else if(size_odd_or_even==1)
printf("\n\n");
i++;
}
This code gives the outputs for size=4 and size=5 respectively as,
If this code can be optimised then please do tell.
I need to make some functions for 2-dimensional arrays (a.k.a. matrixes) and the problem just starts with the first one.
I allocated the matrix in the heap memory using malloc() and then I tried to make a function that initializes the matrixes using a for loop of scanf()s, but after 3 times it takes the input, the program crashes.
Here is the code I made
void initMatrix(int **mat,int row,int col)
{
for(int i=0;i<row;i++){
printf("\n");
for(int j=0;j<col;i++){
printf("Cell (%d,%d): ",i,j);
scanf("%d",&mat[i][j]);
}
}
}
int main()
{
int r,c;
printf("Number of rows: ");
scanf("%d",&r);
printf("Number of columns: ");
scanf("%d",&c);
int **arr = (int **)malloc(sizeof(int*) * r);
for(int i=0;i<r;i++)
arr[i]=(int*)malloc(sizeof(int) * c);
// int count=0;
// for (int i = 0; i < r; i++)
// for (int j = 0; j < c; j++)
// arr[i][j] = ++count;
for (int i = 0; i < r; i++){
printf("\n");
for (int j = 0; j < c; j++)
printf("%d ", arr[i][j]);
}
initMatrix(arr,r,c);
printf("\n");
free(arr);
}
If I manually insert the content of the matrix, the program does work (without the initmatrix() function), I don't know why… I probably made a mistake somewhere.
I'm very new to this and to C programming. It's my first year and things are not very clear for me. Hopefully I can get better very soon.
I have a code here where i input a number and I get results based on the table I have below.
I would like to know: If i have a given string (in the code it's: test[7]="2 B 1 C")
How can I compare the result i have to this string and see if it's the same to print=good?
it's very hard to explain so please let me know if i'm not clear with my question. You can test the code to see how it works.
#include <stdio.h>
#include <string.h>
void initialize(int poss[1296][4]);
int main()
{
int table[1296][4];
char str[5];
char tmp[5];
int i, j, k;
int bull = 0;
int cow = 0;
char test[7]={"2 B 0 C"};
initialize(table);
printf("Enter 4 digits: ");
scanf("%s", str);
for (i=0; i<1296; i++) // building this table
{
strcpy(tmp, str); // copying string
for (j=0; j<4; j++)
{
for (k=0; k<4; k++)
{
if (table[i][j]==tmp[k]-'0' && j==k) // gets the string as an integer
{
tmp[k] = -1;
bull++;
break;
}
else if (table[i][j]==tmp[k]-'0' && j!=k)
{
tmp[k] = -1;
cow++;
break;
}
}
}
printf ("%d B %d C\n\n", bull, cow);
bull = 0;
cow = 0;
}
}
//------------------------------------TABLE---------------------------------//
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}
You can use sprintf to generate the result into a string instead of printing it, then use strcmp to compare that string to what you expect it to be. You can also then use printf to print the string you produced with sprintf. (When you sprintf, don't include the newlines since those aren't in your test string; only output those with printf).
What's not clear from your question, however, is that you only have one test string but print 1296 lines ... if those lines aren't all the same then you need an array of 1296 test results ... or a clearer question.
sample
#include <stdio.h>
#include <string.h>
int main(){
char test[8]={"2 B 0 C"};
char result[8];
int bull = 0;
int cow = 0;
bull = 2;//set by program
cow = 0;
sprintf(result, "%d B %d C", bull, cow);
if(strcmp(result, test)==0){
printf("match!\n");
} else {
printf("not match!\n");
}
return 0;
}