value of an integer changes out of nowhere - c

I am trying to run the code below whilst using the debugger. At the end of the following loop "for (i=0;i<n;i++) pin[i]=0;", n's value changes from the value I've given it and becomes 0. I can't understand why that happens, so your help as to why it happens would be greatly appreciated. Oh, and one other thing. If I ignore it and as soon as I've given n a value, I assign that value to another integer, in order to be able to use it when n becomes 0, my program crashes. It's a crash of the type you get when, for example, you're using a variable you've not assigned a value to.
main()
{
int i,j,k,n,pin[n];
printf("Give the size of the array:\n");
scanf("%d", &n);
do{
printf("Give the number of the iterations:\n");
scanf("%d", &k);
}while (k<1||k>n);
for (i=0;i<n;i++)
pin[i]=0;
for (j=0;j<k;j++){
for (i=0;i<n;i++){
if (i%j==0){
if (pin[i]==0)
pin[i]=1;
else
pin[i]=0;
}
}
}
for (i=0;i<n;i++)
printf("%d ", pin[i]);
}

You must not divide by 0 and define pin[n] where n is initialized.
#include <stdio.h>
int main() {
int i, j, k, n;
printf("Give the size of the array:\n");
scanf("%d", &n);
int pin[n];
do {
printf("Give the number of the iterations:\n");
scanf("%d", &k);
} while (k < 1 || k > n);
for (i = 0; i < n; i++)
pin[i] = 0;
for (j = 0; j < k; j++) {
for (i = 0; i < n; i++) {
if (j != 0 && i % j == 0) {
if (pin[i] == 0)
pin[i] = 1;
else
pin[i] = 0;
}
}
}
for (i = 0; i < n; i++)
printf("%d ", pin[i]);
}
Test
Give the size of the array:
3
Give the number of the iterations:
2
1 1 1
Test 2
Give the size of the array:
5
Give the number of the iterations:
4
1 1 0 0 0

Related

The sum of differences of array elements from each other

That is my code. But the output is wrong. My expected output is:
input: 1 2 3
output: 3 2 3;
but the actual output is 2 1 0 on my code.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n; // create a variables to decide how many number that they want to store on array
int position[10];
int sumdiffs[10];
printf("How many number you want to enter here: ?\n"); // let users enter how much number
scanf("%d", &n);
// accept users number
for (int m = 0; m < n; m++) {
printf("Please enter number %d:", m + 1);
scanf("%d", &position[m]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sumdiffs[i] = abs(position[i] - position[j]);
}
printf("%d\n", sumdiffs[i]);
}
return 0;
}
That is my test.
How many number you want to enter here: ?
3
Please enter number 1:1
Please enter number 2:2
Please enter number 3:3
2
1
0
You are not computing the sum of differences, you only store each difference so the array sumdiffs contains the last difference.
Note also that your code has undefined behavior for n greater than 10 because you access the arrays beyond their boundaries.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("How many numbers you want to enter here?\n");
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
// arrays defined with the correct size (hopefully not too large)
int position[n];
int sumdiffs[n];
// read the numbers from the user
for (int m = 0; m < n; m++) {
printf("Please enter number %d: ", m + 1);
if (scanf("%d", &position[m]) != 1)
return 1;
}
for (int i = 0; i < n; i++) {
sumdiffs[i] = 0;
for (int j = 0; j < n; j++) {
sumdiffs[i] += abs(position[i] - position[j]);
}
printf("%d\n", sumdiffs[i]);
}
return 0;
}
First, clear the accumulated sums:
for (int i = 0; i < n; i++) {
sumdiffs[i] = 0;
Then, just change
sumdiffs[i] = abs(position[i] - position[j]);
into
sumdiffs[i] += abs(position[i] - position[j]);
to accumulate the differences.

Check if the first and last row of a matrix has only negative values

i have some problem making this program
I have created two arrays where I go to insert the first and the last line, then I check if every element is > 0 but it doesn't seem to work..
That's my code:
int main()
{
int i, j, n, m;
int matrix[10][20];
int first_row[m];
int last_row[m];
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(matrix[i=0][j]) // First row
first_row[i] = matrix[i=0][j];
if(matrix[i=n-1][j]) // second row
last_row[i] = matrix[i=n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=j+1;j<n;j++)
{
if(last_row[i] < 0)
printf("Negative element");
}
}
}
I assume in the if conditions matrix[i=0][j] and matrix[i=n-1][j] was to check if the current row being input is the first or last row respectively. If that was the case then you just need to simply check if i is 0 (i == 0) or n - 1 (i == n-1) instead of using matrix[i=0][j] and matrix[i=n-1][j].
Also the line first_row[i] = matrix[i=0][j]; and last_row[i] = matrix[i=n-1][j]; will update i which is what you should avoid in a for loop where i is index. If you intended to assign values to first_row and last_row, you should change them to first_row[j] = matrix[0][j]; and last_row[j] = matrix[n-1][j]; to a get the desire result (note that j should be used for indexing first_row and last_row instead of i because j represents matrix column).
If you want to check every element in the matrix for negative values, then the for loop for (j=j+1;j<n;j++) should be changed to for (j=0;j<m;j++) and matrix[i][j] should be used instead of last_row[i].
Edit: Also as #chux suggested, you should consider initializing matrix, first_row and last_row arrays after you input n and m in order to avoid segmentation fault for any n and m values that are larger than 10 and 20 respectively.
#include <stdio.h>
int main()
{
int i, j, n, m;
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
int matrix[n][m];
int first_row[m];
int last_row[m];
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(i == 0) // First row
first_row[j] = matrix[0][j];
if(i == n-1) // second row
last_row[j] = matrix[n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=0;j<m;j++)
{
if(matrix[i][j] < 0)
printf("Negative element %d\n", matrix[i][j]);
}
}
}

Calculating the mean of an array

#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { NULL };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf_s("%d", &n);
while (n > 100 || n < 0)
{
printf("Amount of numbers should be less than 0 and more than 100\n");
scanf_s("%d", &n);
}
for (i = 0; i < n; i++)
{
scanf_s("%d", &arr[i + 1]);
}
printf("%f", mean(i-1, arr[i]));
system("pause");
}
When I run the code it gives me a read access error. The problem is with the mean() function I created but I don't know what's wrong. Help?
When I run the code it gives me a read access error. The problem is with the mean() function
Although the mean() function produces read access error, the actual problem is here:
printf("%f", mean(i-1, arr[i]));
You are not passing an array to your function, but its element (it is one past the end of what was written, too, so even the value that you pass is undefined).
You need to pass i for the length, because your mean() treats it as an exclusive upper limit, and you also need to pass arr for the array:
printf("%f", mean(i, arr));
Indexing problem when reading the data also needs to be fixed - you need to remove + 1:
scanf_s("%d", &arr[i]);
// ^
Try this:
#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { 0 };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf("%d", &n);
getchar();
while (n > 100 || n < 0)
{
printf("Amount of numbers should be more than 0 and less than 100\n");
scanf("%d", &n);
getchar();
}
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
getchar();
}
printf("%lf", mean(n, arr));
getchar();
}
Your call to the mean function was wrong. You have to pass the entire array, not just one element. Change arr[i] to arr.
Other minor modifications are what I did to make it run on my system. If it works for you otherwise, then great.

Printing prime numbers up to n

I have written some code to ask the user for n, then print the prime numbers up to n. However when I use it, i.e with 10, it only prints the non-prime numbers
/* Asks for the amount of prime numbers you would like to print, then prints them */
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}
return 0;
}
How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10
I've tried everything but I think I am missing something really trivial!
This is how it should be:
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
Also, in the inner loop you don't have to divide the number till j < i. You don't have to go beyond i/2.
As Weather Vane said, the mod operator % returns 0 if i is exactly divisible by j and if this is true then the number is not prime. Your conditional statement is backwards.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
return 0;
}
How many prime numbers would you like to print? 10
2
3
5
7
Several problems.
First, when you set check = 1, that means that i divides evenly, so n is not prime, so you shouldn't print it. You should be printing the number when check == 0.
Second, you're printing each time through the inner loop. You should test check at the end of the loop, to ensure that none of the numbers divided it.
As an improvement, there's no need to keep checking once you find one number that divides evenly. So you can break out of the inner loop as soon as you set check = 1.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
break;
}
}
if (check == 0) {
printf("%d\n", i);
}
}
return 0;
}
try looking at this code
#include <stdio.h>
int IsPrime(int num)
{
int i = 2;
for (i = 2; i < num; i++) if (num % i == 0) return 0;
return 1;
}
int main(void)
{
int n, i;
char *nStr = (char*)malloc(10);
printf("How many prime numbers would you like to print? ");
fgets(nStr, 9, stdin);
n = atoi(nStr);
for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);
getchar();
return 0;
}
and about your code, you should print the number only if check remains 0.

How to delete duplicated values in array in C?

I want to delete duplicates values in array. For example: array[1,5,6,1,3,5,9] I want to have array[6,3,9].
I have written this, but I am having troubles:
#include<stdio.h>
main() {
int array[50], i, j, k=0, c=0, array2[50], n;
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("array[%d]= ", i); scanf("%d", &array[i]);
}
for (i = 0; i < n; ) {
for (j = i + 1; j < n; j++) {
if (array[i] == array[j])
i++;
else {
array2[k++] = array[i];
c++;
}
}
}
for (k = 0; k < c; k++) {
printf("%d ", array2[k]);
}
system("pause");
}
You should start by describing your problem in pseudo code, and breaking it into smaller pieces.
Start from scratch by deleting all these redundant variables, and try to implement the following algorithm:
for each element in inputArray
if not elementIsDuplicate(element)
add to outputArray
That's a single for loop. The elementIsDuplicate is separate function.
Now try to implement the function elementIsDuplicate. This function also contains a single loop, takes input parameters (int* array, int n, int currentIdx) and returns 1 or 0 indicating whether the element at currentIdx occurs anywhere else in the array.
#include<stdio.h>
int main(){
int array[50], i, j, k=0, c, n, array2[50] = {0};
printf("Enter array dimension: "); scanf("%d", &n);
for (i = 0; i < n; ++i){
int num, dup = 0;
printf("array[%d]= ", i); scanf("%d", &num);
for(j = 0; j < k; ++j){
if(array[j] == num){
array2[j] = dup = 1;
break;
}
}
if(!dup){
array[k++] = num;
}
}
for (c=i=0; i < k; ++i){
if(!array2[i])
printf("%d ", array[c++] = array[i]);
}
printf("\n");
/*
for(i=0;i<c;++i)
printf("%d ", array[i]);
printf("\n");
*/
system("pause");
return 0;
}
#include<stdio.h>
main()
{
int n, a[50], b[50], count = 0, c, d;
printf("Enter number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for(c=0;c<n;c++)
scanf("%d",&a[c]); //enter array elements
for(c=0;c<n;c++)
{
for(d=0;d<count;d++)
{
if(a[c]==b[d])
break;
}
if(d==count)
{
b[count] = a[c];
count++;
}
}
printf("count is: %d\n",count);
printf("Array obtained after removing duplicate elements\n");
for(c=0;c<count;c++)
printf("%d\n",b[c]);
return 0;
}
This will remove multiple duplicates from the desired array..
Example: if the input array is: 3 6 5 6 2 8 6 5 9 8 6 ,,then the output array will be: 3 6 5 2 8 9

Categories

Resources