Unpredictable result in counting pairs of integers - c

The task of the program is to count how many times there are two consecutive integers their value exceeds 40. So, the problem here is that the result of the program is way wrong.
To solve this problem, I tried το change some initial values and investigating the mechanism of the code, but I didn't notice any mistakes. The code is below.
#include <stdio.h>
int main() {
int a,i,e=0;
int A[31];
for(i=0; i<=30; i++) {
scanf("%d",&a);
A[i]=a;
}
if (A[i]>40 && A[i+1]>40) {
e=e+1;
}
printf("%d",e);
return 0;
}
The expected result if we enter the integer 41 in all of 31 places of the matrix, the result should be 30, while the result there is always zero (0)
Thank you in advance for your help.

"if statement" must be in loop.
And, Please aware the condition of 2nd loop what I set it as '< 30' instead of '<= 30' because your program want to compare the next variable together as "if (A[i] > 40 && A[i + 1] > 40)".
#include <stdio.h>
int main()
{
int a, i, e = 0;
int A[31];
for (i = 0; i <= 30; i++) {
scanf("%d", &a);
A[i] = a;
}
for (i = 0; i < 30; i++){
if (A[i] > 40 && A[i + 1] > 40)
e = e + 1;
}
printf("%d", e);
return 0;
}

Related

Find minimum number of wires to connect the bulbs code

I have written this C code to find a minimum number of wires required to switch on all the bulbs.
The problem is that there is x number of computers, some of which are On and some are Off and the distance between these bulb from the first bulb is given. The computer can be switched ON by connecting it to its nearby ON the bulb.
So the inputs are as follows:
X = 6 (number of bulbs)
1 0 1 1 0 1(1 means the bulb is ON and 0 means the bulb is OFF)
2 4 8 36 37 40 (distance between one bulb from the first bulb)
and the output will be:
3 (Reason: 4 - 2 = 2, 37 - 36 = 1, 2 + 1 = 3)
#include <stdio.h>
int main(){
int n,pre,post,sum = 0;
scanf("%d",&n);
int arr[n],dist[n];
for(int i =0;i<n;i++){
scanf("%d ",&arr[i]);
}
for(int i =0;i<n;i++){
scanf("%d ",&dist[i]);
}
for(int i =0;i<6;i++){
if(arr[i] == 0){
pre = dist[i]-dist[i-1];
post = dist[i+1]-dist[i];
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
}
printf("\n %d",sum);
}
It keeps on taking the inputs. Please tell me what is the error in this code?
Thanks in advance.
Edited: I missed that scanf("%d",n) by mistake. It was there in my original code and the problem still persists.
As Sandrin mentioned, n is not defined.
Assuming your input file is:
6
1 0 1 1 0 1
2 4 8 36 37 40
You need to add code to set n:
scanf("%d ",&n);
And, you need to insert this before the definitions of your matrix
Here's the refactored code:
#include <stdio.h>
int
main(void)
{
int n, pre, post, sum = 0;
#if 1
scanf("%d ",&n);
#endif
int arr[n], dist[n];
for (int i = 0; i < n; i++)
scanf("%d ", &arr[i]);
for (int i = 0; i < n; i++)
scanf("%d ", &dist[i]);
for (int i = 0; i < 6; i++) {
if (arr[i] == 0) {
pre = dist[i] - dist[i - 1];
post = dist[i + 1] - dist[i];
if (pre > post) {
sum += post;
}
else {
sum += pre;
}
}
}
printf("\n %d", sum);
return 0;
}
Putting a side technical errors (e.g. n not initialized), the algorithms assumes that all problems can be solved by single pass. This is not true for cases like:
1 0 0 0 0 1
0 1 3 4 6 7
Where the code will choose to connect bulbs [0,1], [2,3], and [4,5], based on pre/post distances. However, bulbs 2 and 3 will remain disconnected.
A better algorithm will attempt to find, for each sequence of off bulbs, which is the most expensive connection, and avoid it.
I have come up with this solution for my code and I have tried to consider all the test cases. If you find any test case that won't run feel free to tell.
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av){
int n,pre,post,sum = 0;
scanf("%d",&n);
int *input,*distance;
input = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &input[i]);
}
distance = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &distance[i]);
}
for(int i =0;i<6;i++){
if(input[i] == 0){
pre = distance[i]-distance[i-1];
if(input[i+1]==1){
post = distance[i+1]-distance[i];
input[i] =1;
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
else{
sum = sum+pre;
}
printf("%d.....%d....%d\n",pre,post,sum); //Debugging
}
}
printf("\n %d",sum);
free(input);
free(distance);
}

What exactly is "Error] name lookup of 'N' changed for ISO 'for' scoping [-fpermissive]"?

I just wrote a program that calculates the EAN or UPC's last digit. and here is the process:
1.Calculate the sum of the digits in the odd numbered positions and multiply this sum by 3(Even numbers)
2.Calculate the sum of the digits in the even numbered positions(Odd numbers)
Add the results of the first sum to the second sum and subtract 1 from the total.
Calculate the remainder when divided by 10.
Subtract the remainder from 9
#include <stdio.h>
int main(void)
{
int A[12], sumEven, total;
int sumOdd = 0;
printf("Enter your 12-digits number:");
scanf("%s", &A);
for(int N = 0; N < 12; N += 2);
{
sumOdd = sumOdd + A[N];
}
for(int L = 1; L < 12; L += 2);
{
sumEven += A[L];
}
total = (sumEven * 3 + sumOdd) - 1;
total %= 10;
total = 9 - total;
printf("The digit is:%d", total);
return 0;
}
And here are the error messages:
[Error] name lookup of 'N' changed for ISO 'for' scoping [-fpermissive]
[Note] (if you use '-fpermissive' G++ will accept your code)
[Error] name lookup of 'L' changed for ISO 'for' scoping [-fpermissive]
I guess that it has something to do with my loops, but I don't know where exactly because I have seen similar usage of loop before. Please tell me, thank you
You accidentally put ; at the end of your for loops
for(int N = 0; N < 12; N += 2); // <-- note the semicolon here
{
sumOdd = sumOdd + A[N];
}
So this code part
{
sumOdd = sumOdd + A[N];
}
is out of scope of your for loop where N is not defined. Just remove those semicolons at the end of your for loops to get rid of that error. Note that there are other problems with your code, but this is the cause of this particular error.
There are many faults with the code:
The loop controls end in ; which makes them a complete loop, and the control variables N and L used in the next code blocks are out of scope.
The array is the wrong type, and is too short to hold 12 digits (with the null termintator).
The scanf statement should drop the &, and restrict the input length to prevent buffer overflow.
The data entered is character digits. If you subtract '0' that converts to the numeric value.
One variable int sumEven was not initialised.
I amended and commented where changed.
#include <stdio.h>
int main(void)
{
char A[13]; // change type, and length
int sumEven = 0; // initialise
int sumOdd = 0;
int total;
printf("Enter your 12-digits number:");
scanf("%12s", A); // restrict the length and remove &
for(int N = 0; N < 12; N += 2) // remove ;
{
sumOdd = sumOdd + A[N] - '0'; // ASCII adjustment
}
for(int L = 1; L < 12; L += 2) // remove ;
{
sumEven = sumEven + A[L] - '0'; // ASCII adjustment
}
total = (sumEven * 3 + sumOdd) - 1;
total %= 10;
total = 9 - total;
printf("The digit is:%d", total);
return 0;
}
as #Eraklon said you should not put that ; after for loops .for(...); this is wrong.
also note your sumEven is uninitialized that will probably cause crash.

How do I print a cross to the console in C?

I've just started studying information technologies and I am currently stuck on a programming assignment.
I have to write a code in C which displays a cross to the console, the size of the cross being determined by an initial input.
So the console output should look like this:
size?: 5(user input)
xooox
oxoxo
ooxoo
oxoxo
xooox
(replace the os with blank space)
I've now come as far as this:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j) )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
But this only displays one diagonal of the cross, I'm thinking that the opposite diagonal can be created by another condition after the if however I am lost as to what that condition might be.
You're definitely on the right track! Don't give up.
The way to think about this is to think about the loop counters. You've figured out one half of it. If the row and column are the same, you need to output a *. So what's the other condition? Well, think about counting backwards. If the row is the same as the column counted backwards, we also want a *.
I don't want to do your homework for you, so I'll hold off on writing the code, but hopefully that gives you a hint as to what you need to do.
Replace if( (i==j) ) with if( (i==j)||(i+j)==n+1 ), That is,:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j)||(i+j)==n+1 )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Should you need some help, you have to check the column from the other side as well:
#include <stdio.h>
int n;
int main(void) {
printf("size?: ");
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if (i == j || i == n - j + 1) printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
Edit: There are suggestions to do i + j == n + 1, but I believe i == n - j + 1 makes more sense, since:
i is your current row
j is your current column
n is the size of your square (max row / max column)
i == n - j + 1 means draw * at max - current + 1 column
First thing's first, C compilers don't like
for (int i = 0; i < n; i++)
They like
int i = 0;
for (i = 0; i < n; i++)
But if you're using a C++ compiler, you probably won't get that problem.
Now; back to solving the problem at hand!
On the line:
if( (i==j) )
With this conditional, you're plotting points at (1, 1), (2, 2), (3, 3) ...
You want to also plot points at (1, n), (2, n - 1), (3, n - 2) ...
So you need to add a second conditional to this if statement:
if ( (i==j) || (i == (n - j) + 1 ) )
Then you can simplify this up a bit if you want...
if ( (i==j) || (i == n - j + 1 ) )
And there you go! It now prints a cross, like you described in your question.

issues randomly populating a 2d array of structure type in C

I'm trying to populate a 20x20 matrix where each entry is of structure type. My goal is to randomly assign 100 ants and 5 doodlebugs on this 2D array. Even though I got it to work, I don't always get the amount of ants or doodlebugs I need in the matrix. I added a counting function to always verify how many of them I have each time I run the program, but I'm always slightly short. I'm trying to force those number to work (100 ants and 5 doodlebugs) by using a do/while loop in my populating function, although it's not working. Can someone spot where is my logic is failing me?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define N 20
struct cellState {
int emptyInt;
int antInt;
int dBInt;
char emptyChar;
char antChar;
char dBChar;
};
struct cellState gridState[N][N];
// function to populate world
void pop_mtx(struct cellState gridState[N][N], int antsNeeded, int dBNeeded) {
int i, j;
do {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if ((gridState[i][j].emptyInt = rand() % 3) == 0) {
gridState[i][j].emptyChar = '.';
} else
if (((gridState[i][j].antInt = rand() % 3 == 1) && antsNeeded != 0)) {
gridState[i][j].antChar = 'a';
antsNeeded--;
} else
if (((gridState[i][j].dBInt = rand() % 3 == 2) && dBNeeded != 0)) {
gridState[i][j].dBChar = 'D';
dBNeeded--;
}
}
}
} while (dBNeeded != 0 && antsNeeded != 0);
}
//function to display current state of the world
void display_mtx(struct cellState gridState[N][N]) {
int i, j;
char charToDisplay;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
charToDisplay = 'a';
else
if (gridState[i][j].dBChar == 'D')
charToDisplay = 'D';
else
charToDisplay = '.';
printf("%c ", charToDisplay);
}
printf("\n");
}
printf("\n\n");
}
//function to count ants and doodlebugs
void count_mtx(struct cellState gridState[N][N]) {
int i, j, antCount = 0, dBcount = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
antCount++;
else
if (gridState[i][j].dBChar == 'D')
dBcount++;
}
}
printf("ant count: %i, doodlebug count: %i\n", antCount, dBcount);
}
int main(void) {
srand((unsigned int)time(NULL));
//populate grid state with 5 doodlebugs and 100 ants
int antsNeeded = 100, dBNeeded = 5;
pop_mtx(gridState, antsNeeded, dBNeeded);
count_mtx(gridState);
display_mtx(gridState);
}
There are several problems. First, each time you call rand() you obtain a different value, so it is possible that none of the three tests pass. You should call rand () once and save the value.
Second, there is nothing that guarantees that over NxN calls of rand() you will get as many ones and twos as you need. The outer loop is therefore necessary. You should also preserve already populated squares from one iteration to the next because it might take a long time before you reach an iteration that produces enough ones and twos.
Third, this method is biased toward the squares at the beginning of the grid. It will not give you one out of all possible distributions of 100 ants and 5 doodlebugs over 400 squares with equal probability.
Here is the proper way to do it:
Consider the grid as a uni-dimensional array. First fill it, in order, with 100 ants, 5 doodlebugs, and empty spaces. Then perform a random shuffle of the array.
This procedure will return each possible distribution of the ants and doodlebugs on the grid with equal probability.

Weird Output with first case integer

Here are two functions below that compile perfectly but I seem to be getting a weird error with the very first inputted integer. I have tried debugging in GDB but when it's only the first inputted value that is having this weird error, then it makes things complicated.
#include <stdio.h>
#include "Assg9.h"
#include <stdlib.h>
#include <assert.h>
#include <math.h>
void getPrimes(int usernum, int* count, int** array){
(*count) = (usernum - 1);
int sieve[usernum-1], primenums = 0, index, fillnum, multiple;
for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){
sieve[index] = fillnum;
}
for (; primenums < sqrt(usernum); primenums++)
{
if (sieve[primenums] != 0){
for (multiple = primenums + (sieve[primenums]); multiple < usernum - 1; multiple += sieve[primenums])//If it is not crossed out it starts deleting its multiples.
{
if(sieve[multiple]) {
--(*count);
sieve[multiple] = 0;
}
}
}
}
int k;
for (k = 0; k < usernum; k++)
if (sieve[k] != 0)
{
printf("%d ", sieve[k]);
}
*array = malloc(sizeof(int) * (usernum +1));
assert(array);
(*array) = sieve;
}
void writeToOutputFile(FILE *fpout, const int *array, int n, int count){
int i;
fprintf(fpout, "There are %d prime numbers less than or equal to %d \n", count, n);
for(i = 0; i < count; i++)
{
if(*(array + i) != 0){
fprintf(fpout, "%d ", *(array + i));
}
}
}
Our Output:
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2 32664
Do you want to try again? Press Y for Yes and N for No: y
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2
Do you want to try again? Press Y for Yes and N for No: n
Good bye. Have a nice day
Expected output should obviously just display 2. This is the case for any integer from 2-2000 for the very first inputted integer. The very last, or last 2, prime numbers print very large numbers, sometimes even negative numbers. I have no clue why, but after the first inputted value everything works perfectly. Tried debugging this with GDB like crazy but with no luck. Would really appreciate someone's help for this bizarre error
You aren't initializing the sieves array to 0s. So you're looping from 0 to usernum-1, printing out every number that isn't a 0. Since you didn't initialize the array, the 2nd element is a random value and is being printed out
This code is a problem:
(*array) = sieve;
You are are assigning the address of sieve, a temporary local array, to *array. You need to copy the array contents instead.
Are you also this person who has asked three questions about identical code?

Resources