EDIT: Problem is solved thank you all. I know the problem is not very well explained, sorry for that.
#include <stdio.h>
int main()
{
int line=0;
int longest=0;
int v1[3][3]={{1,0,0},{1,1,1},{7,8,9}};
for(int i=0 ; i<3;i++){
for(int j=0; j<2 ;j++ ){
if(v1[i][j]==0){
int temp=1;
for(int k=j+1; k< 3; k++){
printf("%d\n",k);
if( v1[i][k]==0 ){
temp++;
}
if( v1[i][k]=!0 ){
if( temp>longest ){
longest=temp;
line=i+1;
}
}
}
}
}
}
printf("line:%d\nlenght:%d",line,longest);
}
I have a code like this. When I try to use else statement with if statement, else statement won't work when the requirements inside if statement are not met.
if( v1[i][k]==0 ){
temp++;
}
else{
if( temp>longest ){
longest=temp;
line=i+1;
}
But when I use another if statement it would run when v1[i][k]!=0 condition is met.
if( v1[i][k]==0 ){
temp++;
}
if( v1[i][k]!=0 ){
if( temp>longest ){
longest=temp;
line=i+1;
}
In this statement
if( v1[i][k]=!0 ){
there is a typo. There should be
if( v1[i][k] != 0 ){
But in any case the first and the second programs have a logical error. This if statement
if( temp>longest )
must be placed outside the inner for loop.
for(int k=j+1; k< 3; k++){
And moreover the condition in the this loop
for(int j=0; j<2 ;j++ ){
shall be j < 3
instead of j < 2
. Otherwise the situation when a row contains only the last element equal to zero will be ignored.
Here is a demonstrative program that shows how the for loops can be written.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
enum { N = 10 };
int a[N][N];
srand( ( unsigned int )time( NULL ) );
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
a[i][j] = rand() % 2;
}
}
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
putchar( '\n' );
int line = 0;
int longest = 0;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0, k = 1; j < N - longest; j += k, k = 1 )
{
if ( a[i][j] == 0 )
{
while ( j + k < N && a[i][j + k] == 0 ) ++k;
if ( longest < k )
{
longest = k;
line = i + 1;
}
}
}
}
if ( line != 0 )
{
printf( "line: %d, length: %d\n", line, longest );
}
else
{
puts( "There is no row with elements equal to 0" );
}
return 0;
}
The program output might look like
0 0 0 1 1 0 0 1 0 0
1 1 0 1 0 1 1 0 1 1
1 1 0 1 1 0 0 0 1 1
1 1 0 1 0 1 0 0 0 0
1 1 0 1 0 0 0 0 1 1
1 0 0 1 1 1 0 1 1 1
1 0 0 1 0 0 0 0 0 0
0 1 1 0 0 0 1 1 0 0
0 1 0 1 1 0 0 1 1 0
0 0 0 0 1 0 0 1 0 0
line: 7, length: 6