I've noticed that a counter(avariable) of the for loop, doesn't works well.
Indeed, the counter doesn't decrements correctly; I know this question seems stupid , but I can't understand why the a variable does this.
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=2;a>=0;a--) {
for (b=2;b>=0;b--) {
matrice[a][b]=scanf("%d",&i);
}
}
return 0;
}
You are going out of bounds when you read into your array.
for (a=2;a>=0;a--) {
Array has only two elements, yet you try to read into the third on the first iteration.
matrice[2]
Is the third element. This happens for both dimensions.
scanf() call is not correct. It reads the value into i, but it returns the number of read items, not the value of i.
if you are trying to read the numbers into the matrix, then this is what you are supposed to do..
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
scanf("%d",&matrice[a][b]);
}
As the array matrice[2][2] has 2*2 elements, the valid indices are 0 and 1.
Thats why the for loop should start from 1 and not 2
1) The array index start from 0, as per your code it will access matrice[2][2] which will cause undefined behavior.
2) matrice[a][b]=scanf("%d",&i); will store the return value of scanf in matrice[a][b].
#include <stdio.h>
int main() {
int a,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--)
{
for (b=1;b>=0;b--)
{
scanf("%d",&matrice[a][b]);
}
}
//Then print or do other operations on matrice
return 0;
}
You are starting out of bounds.
For an array of size n you iterate from 0 to n-1
So what you want is
for (a=1;a>=0;a--){
for (b=1;b>=0;b--){
}
}
But one word of warning with running backwards with for loops. As is you are fine because you are using integers but if you were to do something like this
for (auto i = some_vector.size()-1;i>=0;i--){
}
You would be in a lot of trouble since i would not be able to take negative values as some_vector.size() is of type unsigned so the loop would never exit. I tend to always increment in a loop for this reason unless the logic dictates otherwise.
Your matrix has a size of [2][2] but you are using a loop that runs from 2 to 0 (inclusive). In an array of size 2 the maximum permissible index is 1.
I guess that you are just learning basic stuff.. so try to run this slightly version of your code:
#include <stdio.h>
int main() {
int a,i,b,matrice[2][2];
printf("Put inside the matrix some numbers..\n");
for (a=1;a>=0;a--) {
printf("a->%d\n", a);
for (b=1;b>=0;b--) {
printf(" b->%d\n", b);
scanf("%d",&matrice[a][b]);
}
}
printf("Check:\n");
for (a=1;a>=0;a--) {
for (b=1;b>=0;b--) {
printf(" [%d][%d]:%d\n", a, b, matrice[a][b]);
}
}
return 0;
}
In the first loop, the modified code run through the correct indices that for a 2x2 array are (0,0),(0,1),(1,0) and (1,1).
Please note that I have also modified the scanf part using the correct syntax: link.
The second loop is a simple test that what you've coded the data insertion correctly, by outputting the content of the matrix.
Related
I couldn't zero down where i have missed in the input statement. I have build it to acquire four values as input but it goes one more.
manipulating the array entries to check if the fifth value is stored. Basic things
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
You have declared this
int a[2][2];
which has four items, a[0][0], a[0][1], a[1][0] and a[1][1].
However, you are starting your indexing at 1 and going up to 2, so are stepping out of bounds which is undefined behaviour.
Anything can then happen.
Change your loops i.e.:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
to index from 0.
You also need to consider your printf statement, since that oversteps too.
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=0;i<2;i++) /*go through rows - arrays in c go [0- (n-1)]*/
{
for(j=0;j<2;j++)/*go through col */
scanf("%d",&a[i][j]); /*remove \t- now will scan 4 values only */
}
printf("\n%d\t%d\n%d\t%d", a[0][0],a[0][1],a[1][0],a[1][1]);
return 0;
}
/* link many strings*/
#include<stdio.h>
char *mystrcat(char * strDest, char * strSrc);
int main(void)
{
int n;
while(scanf("%d",&n))//输入要连接的字符串个数
{
if(n==0) break;//输入0结束
else
{
char words[n][100];
int i=0;
int j;
for(i=0;i<=n;i++)
{
while(fgets(words[i],100,stdin)!=NULL)
{
j=0;
while(words[i][j]!='\n')
j++;
if(words[i][j]=='\n') words[i][j]='\0';break;
}
}//输入字符串
for(i=n;i>0;i--)
{
mystrcat(words[i-1],words[i]);
}//连接这几个字符串
fputs(words[0],stdout);//输出字符串
printf("\n");
}
}
return 0;
}
//strcat函数原型
char *mystrcat(char * strDest,char * strSrc)
{
char *res=strDest;
while(*strDest)strDest++;
while(*strDest=*strSrc)
{
strDest++;
strSrc++;
}
return res;
}
This is a string of correct code to connect multiple strings. But I think n should be n-1 in two for cycles. But if you change the n to n-1, you can only enter n-1 strings, one less than I think. Can you tell me where my idea is wrong?
for(i=0;i<=n;i++)
Accessing array index out of bound when i=n - this is undefined behavior. So of course indexing should be from n-1 to 0( at max) or 0 to n-1.
And also array indexing in C starts from 0. So there are n elements that you are accessing, not n-1.
So corrections would be
for(i=0;i<=n-1;i++)
The thing is - you are reading in the n locations having index 0 to n-1 on the array and then you concatenate them one by one and at last all concatenated strings will be in words[0]. You are printing it out.
The second loop would be like
for(i=n-1;i>0;i--)
{
mystrcat(words[i-1],words[i]);
}
The idea is no matter what while accessing array indices don't access array index out bound. Here you can simply write it like this as shown in the second case. The thing is here we have ensured that all the indices used are from {0,1,2,3...,n-1}.
First determine what you want to do, if you want to take n string and then try to concatenate them then yes you can. That's what is being done here. but a much cleaner way to do it would be that keep a different result string on which you will concatenate n strings. That will not overwrite or change the already inputted strings.
We need to take inputs upto 10^6 and sort them.
So i intialize whole array for zero on paper this code works but the problem i figure out it is that,Every Array index is not intialized to zero which cause the problem can you help me why every Index of array is not intialized to zero?
int main()
{
unsigned int j,i=0,k,t=0,n,input,flag;
unsigned int a[10^6]={0};//with this method still give garbage value
scanf("%d",&n);
flag=0;
for(k=n;k>=1;k--)
{
scanf("%u",&input);
a[input]=a[input]+1;
if(input>flag)
{
flag=input;
}
}
while(i<=flag)
{
if(a[i]>0)
{
while(a[i])
{
printf("%u\n",i);
a[i]=a[i]-1;
}
}
i++;
}
return 0;
}
In case you want to know question is here
Click here
you can see here i check fresh array for first 25 values and this is the result
The problem was solved by BLUEPIXY in short replies
with using
static unsigned int a[1000001]={0};
in the intialization part.
The code is accpeted.
Execution time=0.19 sec
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int prime(long long int);
long long int *arr; //array to hold n prime numbers
int main()
{
int i,count=4;;
long long int n;
scanf("%lli",&n);
arr=malloc(sizeof(long long int)*n);
arr[0]=2;
arr[1]=3;
arr[2]=5;
arr[3]=7;
if (n==1) printf("%lli",arr[0]);
else{ if (n==2) printf("%lli",arr[1]);
else{ if (n==3) printf("%lli",arr[2]);
else{ if (n==4) printf("%lli",arr[3]);
else
{
for(i=2;count<n;i++)
{
if(prime(6*i-1)) { /*As prime nos are always 6k+1 or
arr[count]=6*i-1; 6k-1fork>=2 I checked only for those*/
count++; }
if(prime(6*i+1)&&count<=n) {
arr[count]=6*i+1;
count++; }
}
printf("%lli",arr[count]);
}}}}
//free(arr);
return 0;
}
int prime(long long int x)
{
int j=1,flag=1;
while(arr[j]<=sqrt(x))
{
if (x%arr[j]==0)
{
flag=0;
break;
}
j++;
}
return flag;
}
The code is working only for n=1,2,3,4, i.e i=0,1,2,3 for which the values are explicitly given. For n=5 onwards it is giving 0 as O/P
There is some glitch related to the global dynamic array as free(arr) is giving core dump error.
Q: Is this the right way to declare a global dynamic array? What could be the problem in this code?
Thank You in advance.
If that is your actual code you have 4 bugs:
2 line comment scopes out a line of your code
the second if should check count < n not count <= n as if count == n you cannot write to arr[count]
You cannot print arr[count] only arr[count-1] which is probably what you mean
In the case where n is less than 4 you still set arr[1], arr[2] and arr[3] which may be out of bounds
It is of course also inefficient to call sqrt(x) in every loop iteration, potentially you should call it outside and there may be a potential rounding issue bug due to the way square roots are calculated, so you might prefer:
while( arr[j] * arr[j] < x )
It would be preferable not to make this global and to pass it into your function.
It would also be preferable to move the main loop logic of your program outside of main().
I'm surprised you say you program works for n=1, 2 and 3 as it looks like you are setting out of bounds.
Your counter goes beyond the size of the array. Specifically both conditions (6i-1 and 6i+1) are met for i=2, and therefore counter is incremented twice, resulting in using arr[5] where you only allocated 5 places in the array. This is because you check counter<=n and not counter
Not sure this could be also be the reason for free creating a core dump, but it is possible (because once corrupting the memory, free may access corrupted data).
I want to make a spiral in C using a 2D matrix, such as the one shown below:
This is the code that I worked out. But it keeps going into an infinite loop. I can't seem to get an output. Can anyone tell me what mistake I'm making in this logic?
And I know its pretty cumbersome, but the assignment is to get the output for any "n" dimensional array, and we need to use all the row_left,row_right, etc variables, as they're given in the question.
#include<stdio.h>
int main(void)
{
int array[6][6]={1},dim,row_right=0,row_left=dim-1,col_up=0,col_down=dim-1;
int i,j,num,cnt;
printf("Enter the dimensions of 2D array:\n");
scanf("%d",&dim);
num=dim*dim;
cnt=0;
while(cnt!=num)
{
for(j=col_up;j<=col_down;j++)
{
if(j=0)
array[row_right][j]=1;
else
array[row_right][j]=array[row_right][j-1]+1;
}
for(i=row_right+1;i<=row_left;i++)
array[i][col_down]=array[i-1][col_down]+1;
for(j=col_down-1;j>=col_up;j--)
array[row_left][j]=array[row_left][j+1]+1;
for(i=row_left-1;i>row_right;i--)
array[i][col_up]=array[i+1][col_up]+1;
row_right++;
row_left--;
col_up++;
col_down--;
cnt++;
}
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
printf("%d\t",array[i][j]);
printf("\n");
}
return 0;
}
if(j=0)
is almost surely wrong. This sets j to zero and always evaluates to a false condition. The correct condition uses j == 0.
Also, the code uses the variable dim before it is read by scanf.
You forgot to initialize the variable dim. That is used in following line :
int array[6][6]={1},dim,row_right=0,row_left=dim-1,col_up=0,col_down=dim-1;
With correctly formatted code you probably would have seen this.