why the program cannot count the number? c language - c

i am making a minesweeper game in c language. in this stage, i want to the program to count the number of mines in specific row or column. what the program supposed to do is that after the user input the locations of the mines, he can count the no. of mines in specific row by typing 1 (row no.) or count the no. of mines in specific col by typing 2(col no.). however, my program cannot count the no. and always print out 0. i can't figure out why. plz kindly help me t o find out the problems of my program
here is the pictures that show what my program do
#include <stdio.h>
#include <stdlib.h>
// Possible square states.
#define VISIBLE_SAFE 0
#define HIDDEN_SAFE 1
#define HIDDEN_MINE 2
// The size of the starting grid.
#define SIZE 8
// The possible command codes.
#define DETECT_ROW 1
#define DETECT_COL 2
#define DETECT_SQUARE 3
#define REVEAL_SQUARE 4
#define GAMEPLAY_MODE 5
#define DEBUG_MODE 6
#define REVEAL_RADIAL 7
// Add any extra #defines here.
void initialise_field(int minefield[SIZE][SIZE]);
void print_debug_minefield(int minefield[SIZE][SIZE]);
// Place your function prototyes here.
int main(void) {
int minefield[SIZE][SIZE];
int mines;
int pair1, pair2;
int detect;
int count = 0;
initialise_field(minefield);
printf("Welcome to minesweeper!\n");
printf("How many mines? ");
scanf("%d",&mines);
// TODO: Scan in the number of pairs of mines.
printf("Enter pairs:\n");
for( int i = 0; i < mines; i++){
scanf("%d %d",&pair1, &pair2);
minefield[pair1][pair2] = HIDDEN_MINE;
}
// TODO: Scan in the pairs of mines and place them on the grid.
printf("Game Started\n");
print_debug_minefield(minefield);
while(scanf("%d %d", &detect, &pair2) != EOF){
if ( detect == DETECT_ROW){
for( int i = 0; i < pair2; i++){
if(minefield[pair2][i] == HIDDEN_MINE){
count++;
}
}
printf("There are %d mine(s) in row %d\n",count,pair2);
print_debug_minefield(minefield);
}
else if( detect == DETECT_COL){
for(int j = 0; j < pair2; j++){
if( minefield[j][pair2] == HIDDEN_MINE){
count++;
}
}
printf("There are %d mine(s) in column %d\n",count,pair2);
print_debug_minefield(minefield);
}
}
// TODO: Scan in commands to play the game until the game ends.
// A game ends when the player wins, loses, or enters EOF (Ctrl+D).
// You should display the minefield after each command has been processed.
return 0;
}
// Set the entire minefield to HIDDEN_SAFE.
void initialise_field(int minefield[SIZE][SIZE]) {
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
minefield[i][j] = HIDDEN_SAFE;
j++;
}
i++;
}
}
// Print out the actual values of the minefield.
void print_debug_minefield(int minefield[SIZE][SIZE]) {
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
printf("%d ", minefield[i][j]);
j++;
}
printf("\n");
i++;
}
}

In line minefield[pair1][pair2] = HIDDEN_MINE set mines in below co-ordinate.
(0 0), (1 1), (2 2)
But in below code.
for( int i = 0; i < pair2; i++){
if(minefield[pair2][i] == HIDDEN_MINE){
count++;
}
It only verifies co-ordinate (pair2, 0 to (pair2-1) ) whereas HIDDEN_MINE values are in co-ordinate (0-pair1, pair2).
So loop to be executed till pair2 not (pair2 -1).
for( int i = 0; i <= pair2; i++) // Will modify count properly

Related

Add a new line every 5 outputs

I have this code in which I need to find all prime numbers from 2 to 1000 and need to print them out in groups of 5 in each line. How can I do that?
#include <stdio.h>
int main() {
int i, a, count;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
count = 0;
for (a = 1; a <= i; a++) {
if (i % a == 0)
count++;
}
if (count == 2)
printf("%d\t", i);
}
return 0;
}
You can add a new counter to count the number of prime numbers printed until the current loop. If this counter value is divisable by 5, print a new line.
int main()
{
int i,a,count;
printf("Prime numbers between 2 and 1000 are : \n");
int cnt_prime = 0; // count the number of prime numbers until this loop
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2) {
printf("%d\t", i);
cnt_prime++;
if (cnt_prime % 5 == 0) // print new line after each five numbers
printf("\n");
}
}
return 0;
}
There is another faster approach to find the prime numbers in a range. You can read about sieve of eratosthenes from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
Maybe not the best answer, but you could add another counter-variable called prime_count and initialize it with value 0. Then each time you print a prime, you increment that variable. After printing a prime you then check wether prime_count is equal to 4. If that's the case you print a newline-character and reset prime_counter to 0.
The code could look something like this:
int main()
{
int i,a,count,prime_count=0;
printf("Prime numbers between 2 and 1000 are : \n");
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2)
{
printf("%d\t",i);
prime_count++;
if (prime_count == 4)
{
printf("\n");
prime_count = 0;
}
}
}
return 0;
}
You can check till square root of N to verify prime no need to check till N it makes your code O(sqrt(n)) refer this for more info about the algorithm.You can have a variable called printCounter to check total elements printed on console when it become a multiple of 5 we can print a new line.
int main() {
int i, a, printCount = 0 ;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
int isPrime = 1;
for (a = 2; a * a <= i; a++) {
if (i % a == 0){
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d\t", i);
printCount++;
}
if(printCount%5 == 0){
printf("\n");
}
}
return 0;
}

Problem with C program to find Sudoko square 3x3 if exist in Matrix RXC

#include <stdio.h>
#include <stdlib.h>
#define R 4
#define C 5
// functions for option 1 initializeCountArray and TestCount and Sudoku
void initializeCountArray(int *count)
{
int i;
for (i = 0; i < 10; i++)
count[i] = 0;
}
int TestCount(int *count)
{
int i;
for (i = 1; i < 10; i++)
if ( count[i] == 1)
count[0]++;
return 1;
}
int Sudoku(int mat[R][C])
{
int count[10] = { 0 };
int rows,cols,i,j;
for(rows=0; rows<R-2; rows++)
{
for (cols = 0; cols<C-2; cols++)
{
initializeCountArray(count);
for (i = rows; i <= rows+2; i++)
{
for (j = cols; j <= cols+2; j++)
{
count[ mat[i][j] ] ++;
printf("\n%d,%d",i,j);
}
}
printf("\n TestCount=%d",TestCount(count));
if (TestCount(count) == 9)
return 1;
}
}
return 0;
}
void main ()
{
int mat[R][C] = {{1,7,8,9,6},
{1,3,3,4,6},
{1,1,1,2,5},
{1,6,7,8,9}};
printf ("\n Check Matrix if Suduku 3X3 square found");
if (Sudoku(mat) == 1)
printf("\n Sudoku square matrix was found\n");
else
printf("\n Sudoku square matrix NOT found\n");
}
This program should solve a specific code test that we got in class with the functions that included
and we can not use other methods when running the program the TestCount function give wrong number as output I used test printouts of indexes and I can not figure what is wrong please help
First of all:
In your TestCount function you use your count[0] as a counter for the numbers that appear in the 3x3 submatrix. I guess you wanted to do:
return count[0];
instead of your:
return 1;
Second, you do this:
printf("\n TestCount=%d", TestCount(count));
if (TestCount(count) == 9)
return 1;
But notice your TestCount has some side effects. First time you call it, count[0] would get 9 for a Sudoku-styled 3x3 matrix, but the second time you continue incrementing count[0], so it would get 18 and fail the == 9 check - Eventually your Sudoku function misses it.
You should probably either set count[0] = 0; between calls of TestCount(), reset count[0] to 0 before you start counting in TestCount() or anything else you could think of (just make sure you don't overwrite it).

Problem with frequency analysis of user input array in C

I'm supposed to do a freqency analysis of a user input array. User may enter as many numbers between 0-1000 as s/he wants and a maximum of 100 numbers can be entered, user ends input by entering a negative number. A void function will calculate which number appears the most times and those 2 variables should be sent to the function as pointers.
My problem is that no matter what I do the analysis seems to calculate all the "empty" elements of the array and I can't figure out what I'm doing wrong. If i make the array smaller to lets say 10 elements it works fine. As I'm a complete novice when it comes to programming and I've changed the code about a million times so at this point I can't remeber what I've changed from my original code. When debugging I get stuck in the second for loop in the function..
#include <stdio.h>
#define MAX 100
#define INTERVAL 1000
void frequencyAnalysis(int array[],int *number, int *freq)
{
int element = 0, count = 0;
for (int i = 0; i < MAX; i++) {
int tempElement = array[i];
int tempCount = 0;
for (int j = 0; j < MAX; j++)
if (array[j] == tempElement)
tempCount++;
if (tempCount > count) {
element = tempElement;
count = tempCount;
}
}
*number = element;
*freq = count;
}
int main(void)
{
int array[MAX], i, j, number = 0, freq = 0;
printf("Hello.\n"
"Please enter a number between 0-1000. "
"Enter as many number as you want (maximum 100).\n"
"Exit by entering a negative number.\n\n");
printf("Enter a number:\n");
for (i = 0; i < MAX; i++) {
scanf("%d", &array[i]);
if (array[i] < 0)
break;
}
frequencyAnalysis(array, &number, &freq);
printf("The number:%d is the most frequent number and appears %d times.\n", number, freq);
return 0;
}
Addressing the first issue, pass in how many items the user actually entered so you're not running up to MAX (which would include all the unused cells). The key is nitems.
void frequencyAnalysis(int array[], int nitems, int *number, int *freq)
{
for (int i = 0; i < nitems; i++) {
...
for (int j = 0; j < nitems; j++)
{
// do stuff
}
}
}
int main(void)
{
int array[MAX],i, j, number = 0, freq = 0;
...
frequencyAnalysis(array, i, &number,&freq);
///
}

C - Print all prime numbers from 1 to 100 using arrays

OK so I got this challenge where I have to print all the primes from 1 to 100... However there is an error in my code that I am unable to find. Here is how I thought the problem should be done:
For any number from 3 to 100 check if there is any other number in the primes array that divides it. If there is the number is not prime. If there is not the number is prime and should be added to the array. Pretty simple, right ?
However it is not working.
Here is my code :
#include <stdio.h>
int main() {
int Primes[50] = {0};
int i, j, k;
Primes[0] = 2;
Primes[1] = 3;
for (i = 3; i < 101; i++) {
for (j = 2; j < 100; j++) {
if (i % Primes[j] != 0 && Primes[j] != 0) {
Primes[j] = i;
}
}
}
printf("Primes array : \n");
for (k = 0; k < 51; k++) {
printf("%d ", Primes[k]);
}
return 0;
}
instead of assuming the magic number as 25... that is k!=25, we can
replace it with i<=100.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int Primes[50] = {0};
int i,j,k = 0;
Primes[0]=2;
Primes[1]=3;
for(i=0; i<=100; i++) {
for(j = 2; j<=i; j++) {
if(i % j == 0 ){
if(i == j)
Primes[k++]=i;
break;
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) {
printf("%d\n", Primes[index]);
}
return 0;
}
When you do this:
if(i % Primes[j] != 0 && Primes[j] !=0)
{
Primes[j]=i;
}
You're saying "if the current number is not divisible by the given prime number, replace the given prime number with the current number". This is not what you want.
You need to check if the current number is not divisible by any prime number. So you need to loop though the list of primes to make sure your number isn't divisible by any of them, and if so add the number to the end of the list. You can do that as follows:
int num_primes = 0;
for (i=2;i<101;i++)
{
int is_prime = 1;
for(j=0; j<num_primes && is_prime; j++)
{
if(i % Primes[j] == 0)
{
is_prime = 0;
}
}
if (is_prime) {
Primes[num_primes++] = i;
}
}
In the above code, we use num_primes to count the number of primes we have so far, and is_prime to see if we found a prime that divides the current number. As you divide each number by a prime, if the remainder is 0 you know the number is not prime and set is_prime to 0. This also causes the inner loop to exit right away. Then if is_prime is still set at the end of the inner loop, you have a prime and you add it to the end of the list.
You also have an off-by-one error in the printing loop:
for(k=0;k<51;k++)
Since Primes has size 50, the largest valid index is 49. So change it to:
for(k=0;k<50;k++)
There are lot of issues in the algorithm you used. Use this simple version with issues addressed in the code.
int main(void){
int Primes[50] = {0};
int i,j,k = 0 /* use for prime count purpose */;
Primes[0]=2;
Primes[1]=3;
for(i=4 /* 3 is already stored */; k != 48; i++) { /* rotate loop until prime count doesn't reaches 48 */
for(j = 2; j<=i; j++) { /* i is the number you want to check whether its prime or not. SO rotate loop from 2 to "i" */
if(i % j == 0){ /* use i%j not i % Primes[j] as you want to check whether i is prime or not */
if(i == j) /* if its a prime numbur j reaches upto i */
Primes[k++]=i; /* store it */
break; /* comes out of inner loop */
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) { /* rotate k times not some random 51 times */
printf("%d ", Primes[index]);
}
return 0;
}
The code above doesn't actually give what we want, but beautiful code nonetheless. Here is the edited code that gives the prime numbers from 1 to 100
int main(void){
int Primes[50] = {0};
int i,j,k = 0 /* use for prime count purpose */;
Primes[0]=2;
Primes[1]=3;
for(i=0 /* 3 is already stored */; k != 25; i++) { /* rotate loop until prime count doesn't reaches 48 */
for(j = 2; j<=i; j++) { /* i is the number you want to check whether its prime or not. SO rotate loop from 2 to "i" */
if(i % j == 0){ /* use i%j not i % Primes[j] as you want to check whether i is prime or not */
if(i == j) /* if its a prime numbur j reaches upto i */
Primes[k++]=i; /* store it */
break; /* comes out of inner loop */
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) { /* rotate k times not some random 51 times */
printf("%d\n", Primes[index]);
}
return 0;
}

check common values in 2 arrays and put the different in third array

i have this code ... for a function who get 7 numbers from the user and put it into array number 1.... and second create a random numbers and put them into array number 2....check if there is a common values ...(not only in the same place for example: not only if ar1[1]==ar2[1] ... but to check for all places if there is a common values)....and to put the different values in third array...to create third array and put the not common values in it ... this is my code:
//includes
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <time.h>
//define
#define N 7
//prototype
void randomArray(int maxVal,int ar2[]);
int main()
{
//variables/arrays
int ar1[N],ar2[N],ar3[N],i,z,t,temp,maxVal,counter;
printf("Please Enter %d numbers: ",N);
for(i=0;i<7;i++)
{
scanf("%d",&ar1[i]);
}
while(1)
{
printf("Please enter a max value: ");
scanf("%d",&maxVal);
if(maxVal>0)
break;
}
randomArray(maxVal,ar2);
getch();
return 0;
}
//randomArray
void randomArray(int maxVal,int ar2[])
{
int i;
for(i=0;i<N;i++)
{
/* get random value between minVal and maxVal */
ar2[i] = (rand() % (maxVal+1 - 1)) + 1;
}
}
Here's the simple, brute force approach. It first compares each element in array 1 against every element in array 2 and stores it if it's not in array 2. Then it does the same thing for array 2. Then it prints array 3.
Note: you need to change the size of array 3 to N*2 in case there are no matches. Also, set all elements in array 3 to 0 first to mark as a non-result. Or keep track of array 3's length.
int ar3[N*2] = {0};
int index = 0;
//Check 1st array
printf("Array 1:\t");
for (int i = 0; i < N; i++) {
bool in_array = false;
for (int k = 0; k < N; k++) {
if (ar1[i] == ar2[k]) {
in_array = true;
break;
}
}
if (!in_array) {
ar3[index++] = ar1[i];
}
printf(" %d", ar1[i]);
}
//Check 2nd array
printf("\r\nArray 2:\t");
for (int i = 0; i < N; i++) {
bool in_array = false;
for (int k = 0; k < N; k++) {
if (ar2[i] == ar1[k]) {
in_array = true;
break;
}
}
if (!in_array) {
ar3[index++] = ar2[i];
}
printf(" %d", ar2[i]);
}
// Print result
printf("\r\nUnique:\t");
for (int i = 0, j = 0; i < N*2; i++) {
if (0 == ar3[i]) {
break;
}
printf(" %d", ar3[i]);
}
If this works for you, please accept as correct answer.

Resources