C random matrix with numbers between 0 and 9 - c

I'm a C newbie and I'm trying to make a matrix 5x4 only with numbers between 0 and 9 where each number needs to be there 2 times (I'm trying to make the memory game). I got this code but I think that this is quite a mess and its not working, so my question is, how can I improve my code or how can I make this matrix in a different way?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MaxC 4
#define MaxL 5
int main(){
int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0, n7=0, n8=0, n9=0, n0=0;
int i=0,j=0,r;
int n[MaxL][MaxC];
srand(time(NULL));
while(i<5){
j=0;
while(j<4){
r=(rand()%10);
if(r==0 && n0<2){
n0++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==1 && n1<2){
n1++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==2 && n2<2){
n2++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==3 && n3<2){
n3++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==4 && n4<2){
n4++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==5 && n5<2){
n5++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==6 && n6<2){
n6++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==7 && n7<2){
n7++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==8 && n8<2){
n8++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
if(r==9 && n9<2){
n9++;
j++;
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
}
i++;
}
return 0;
}

Here is a little change to make your program shorter.
I've placed n0, n1, .... into an array indexed by r.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MaxC 4
#define MaxL 5
int main()
{
int na[10] = {0};
int n[MaxL][MaxC], i=0;
srand((unsigned)time(NULL));
while(i<MaxL)
{
int j=0;
while(j<MaxC)
{
int r = rand() % 10;
if(na[r]<2)
{
++na[r];
n[i][j] = r;
printf(" %3d ",n[i][j]);
++j;
}
}
++i;
printf("\n");
}
return 0;
}
Example output:
2 6 1 8
4 7 0 2
5 3 7 8
9 1 0 3
5 6 4 9
Your code keeps trying random number until you have had each number twice. That is not the best approach.
Instead you could initialize the matrix with the 20 numbers at fix locations and then do a random shuffle of the matrix.

First off, you've placed j++ in every if statement. It'll look a lot cleaner if you just leave j++ at the end of the loop. Same goes for the print statement.
Second, if you could post what the program is printing out or describe how it's not working, that would help you get an answer to your problem. I don't see what functional issue your code has without trying it myself.
EDIT: See 4386427's answer for further ways to simplify your code.

May I help you? You can simplify your code if you replace ten the nX variables on array. Look at this:
int main(){
int c[10] = {0};
int i=0,j=0,r;
int n[MaxL][MaxC];
srand(time(NULL));
for(i = 0; i < 5; i++) {
for(j = 0; j < 4; j++) {
do {
r=(rand()%10);
} while( c[r] > 2);
++c[r];
n[i][j]=r;
printf(" %3d ",n[i][j]);
}
printf("\n");
}
return 0;
}

Related

Why is the output of these 2 programs not same

I am trying to find the numbers that are not divisible by 3,5,7 and counting them
And printing the ones that are divisible
The two approaches are
#include <stdio.h>
int main()
{
int count=0;
for(int i = 1; i<=500;i++)
{
if(i%3==0 && i%5==0 && i%7==0) {
printf("%d \n", i);
}
else {
count++;
}
}
printf(" the count is : %d \n", count);
}
/*
WAP to count the numbers from (1-500) which are not divisible by 3, 4 and
*/
#include <stdio.h>
int main()
{
int count=0;
for(int i = 1; i<=500;i++)
{
if(i%3!=0 && i%5!=0 && i%7!=0) {
count++;
}
else {
printf("%d \n", i);
}
}
printf(" the count is %d \n", count);
}
The problem is that the output should be same but it is not
Because these two if statements are not opposite from each other. The negation from
if(i%3==0 && i%5==0 && i%7==0)
would be
if(!(i%3==0 && i%5==0 && i%7==0))
which changes equals to not equals, but also changes ANDs to ORs. So the second code should have something like this
if(i%3!=0 || i%5!=0 || i%7!=0)

How to get sequence of numbers and then print the last 5?

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).
I can assume that the user will input all the numbers in one line and will end it with 0.
I wrote that code but something is wrong with it, I think its something about the scanf line.
Input:
1 6 9 5 2 1 4 3 0
Output: no output
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);
}
return 0;
}
This comparison
if (j == '0') {
does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.
You need to write at least
if (j == 0) {
Due to these sub-statements of the if statement
last_input = N;
break;
this for loop
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
is never executed and does not make a sense.
This statement
last_input=-1;
results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.
You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.
The program can look the following way.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
else
{
puts( "There are no entered numbers." );
}
}
The program output might look like
Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9
I made some changes based on ur comments and now its work fine!
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);
}
return 0;
}
thank u guys <3.

Count repeated numbers in a file

So I'm having this file myFile.txt with the following numbers in it: 1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1. I'm trying to write a program that calculates how many times a number from 0 to 9 is repeated, so it would be printed out like that Number %d repeats %d times. Right now I'm stuck at printing out the n number of elements of that file, so in example, if I would like to calculate how many times the 15 first numbers repeat themselves, firstly I would print out those 15 numbers, then the number of times each number repeats. But when I'm trying to print out those 15 numbers, it prints me this: 7914880640-10419997104210821064219560-1975428800327666414848.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == '\n'))
count = count + 1;
}
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
That's the final solution.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='\n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("\nNumber %d was found %d times\n", a[i], eval);
}
}
}
return 0;
}

C Program (Prime Number in a given range)

I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}

finding a palindrome using arrays

i have this problem that i'm having troubles to solve.
the user needs to enter 15 numbers (whole numbers) and i need to check if there's a palindrome.
if there are more then one i must take the longest one, and if there are more then one with the same size, i must take the one whose index comes first. i.e:
Input:
1 2 1 3 5 6 7 8 9 4 5 6 8 9 8
Output:
Palindrome Found: 121
Input:
1 2 1 3 3 1 6 4 8 7 9 5 4 8 6
Output:
1 3 3 1
that is my code at the moment:
when i run it, the values of k and array1[k], seems to be an error. i've gor them back with the value 5373952.
even if there is a palindrome it call back that the palindrome was not found.
#include <stdio.h>
#include <stdlib.h>
int main()
{
double arr[15]={0};
int array1[15];
int i,j,k=0;
for (i=0; i<15; i++) // the program is asking for 15 numbers from the user.
{
scanf("%lf", &arr[i]);
if ((arr[i]-(int)arr[i])!= 0)// if the number is not a whole number, the program will stop immediately.
{
printf("Error \n");
return (0);
}
}
for (i=0; i<15; i++)
{
for(j=14; j>=i; j--) // going back-wards to the start. checking at each point for a match.
{
if ((int)arr[i]==(int)arr[j])
{
array1[k]=(int)arr[j];
i++;
j--;
k++;
break;
}
}
}
if ( (int)arr[j] == array1[k] )
{
printf("Palindrome Found:%d \n", array1[k]);
}
else
{
printf("Palindrome Not Found \n");
}
return (0);
}
The number must be between 0 and 9, or can be bigger? For example
1 2 13 22 16 4
Anyway, it's wise to work with the input as a string.
#include <stdio.h>
int main(void){
int arr[15]={0};
int i,j;
int start, end, max_len = 1;
for (i=0; i<15; i++){
if(1 != scanf("%1d", &arr[i]) || arr[i] < 0){
printf("input error\n");
return 1;
}
}
for(i = 0; i < 15 - max_len; ++i){
for(j=i+max_len; j<15; ++j){
if(arr[i]==arr[j]){
int found = 1;
int s, e, len = j - i + 1;
for(s=i, e=j; s < e; ++s, --e){
if(arr[s] != arr[e]){
found = 0;
break;
}
}
if(found && max_len < len){
start = i;
end = j;
max_len = len;
}
}
}
}
if(max_len == 1)
printf("Palindrome Not Found \n");
else {
printf("Palindrome Found:");
for(i=start; i<=end; ++i)
printf(" %d", arr[i]);
printf("\n");
}
return 0;
}

Resources