Swapping elements from an array that are prime numbers - arrays

I need to input my own array and give its own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example:
My array: 4 6 3 5 7 11 13
The new array: 4 6 5 3 11 7 13
Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same.
#include <stdio.h>
#define array 100
int prime(int b
)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return b; // not prime
}
break;
}
return b;
}
int main()
{
int n, i, a[array];
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]))
{
int temp;
temp = prime(a[i]);
prime(a[i]) == prime(a[i + 1]);
}
}
printf("\nThe new array is:\n");
printf("%d ", prime(a[i]));
return 0;
}
I haven't learned pointers so is there a way without it or?

there are few things needs to modify
need to change function prime return type to bool. since we are interest to check if array element is Prime. if array element is Prime, return True
int prime(int b)
changed to
bool prime(int b)
also need to extend check if prime() function return true and if array index is not last element then only swap array element to next, else skip
if (prime(a[i]) == 1 && a[i-1] != n)
prost(a[i]) looks typo (I guess). corrected to a[i + 1]
this is not optimized code, it just modified version of your code. if you have concern specific performance, please follow suggestion mentioned by
chux - Reinstate Monica
code:
#include <stdbool.h>
#include <stdio.h>
#define array 100
bool prime(int b)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return false; // not prime
}
break;
}
return true;
}
int main()
{
int n, i, a[array];
int temp;
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]) == 1 && a[i] != a[n-1]) /* enter loop only array element is Prime number and it is not last element */
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
a[i++];
}
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output for above code: check out this link
How many elements does the array have?
7
Put in 7 elements from the array!
4
6
3
5
7
11
13
My array is:
4 6 3 5 7 11 13
The new array is:
4 6 5 3 11 7 13
...Program finished with exit code 0
Press ENTER to exit console.

First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.

Related

Looking for the sum of factors equal to the number of oneself

I'm trying to finish my homework, while there is something trapped me.
Here the question:
In the range of N, output those numbers whose factors sum is equal to themselves according to the following format.
Input:
1000
output:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
Here my code, please tell me why can't i get the right output. Appreciate it if
you can improve it for me.
Thanks in advance.
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
Making the same a little clean,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
Modifications retaining your code:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
I have made modifications in your code and corrected/commented where you have made mistakes.

In C program counting occurrences of digits 0 through 9 in an NxM array. Mine counts the number of numbers instead of individual number counts?

This first part defines the arrays and variables needed: i refers to rows, j refers to columns, k refers to the element in the array that stores number counts, and l refers to the number being tested, c and d are the user entries for the array size.
#include <stdio.h>
int main(void) {
int i, j, k, l;
int c, d;
printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
Here the array is created as the user specifies.
scanf("%d %d", &c, &d);
int charlesbarkley[c - 1][d - 1];
int javariparker[9];
for (j = 1; j <= d; j++) {
printf("Enter row #%d #'s", j);
for (i = 0; i < c; i++) {
scanf("%d", &charlesbarkley[i][j - 1]);
}
}
Here is four nested for loops that are designed to go to each element of the array (charlesbarkely[i][j]), test that element against numbers 0 - 9 incrementally (l++), then increment the individual array element (specified by javariparker[k], k then increments) every time the user defined array element equals the incrementing value of l starting at 0.
for (k = 0; k <= 9; k++) {
for (j = 0; j < d; j++) {
for (i = 0; i < c; i++) {
for (l = 0; l <= 9; l++) {
if (charlesbarkley[i][j] != l)
javariparker[k] = javariparker[k];
else
javariparker[k] = (javariparker[k] + 1);
}
}
}
}
Here I am trying to print the array with the number counts (0 - 9), but if my array is like 5x5 for example, it just spits 25 10 times back at me, so it's checking each element for every number instead of checking each element for just one number each time, how do i get this to work like I want it or am I going to a dead end?
for (k = 0; k <= 9; k++) {
printf("%d", javariparker[k]);
}
}
You are accessing your arrays out of bounds. If you declare an array like int a[n]; the valid indices are 0 ... n-1.
Using the counter variables uninitialized also invokes undefined behavior, you should initialize them with int javariparker[10]={0};:
You also do not need a fourth loop to count the occurrences.
This should work:
#include <stdio.h>
int main(void)
{
int i, j, k, l;
int c, d;
printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
scanf("%d %d", &c, &d);
int charlesbarkley[c][d];
int javariparker[10]={0};
for(j=0;j<d;j++)
{
printf("Enter row #%d #'s", j+1);
for(i=0;i<c;i++)
{
scanf("%d",&charlesbarkley[i][j]);
}
}
for(k=0;k<=9;k++)
{
for(j=0;j<d;j++)
{
for(i=0;i<c;i++)
{
if(charlesbarkley[i][j]==k)
javariparker[k]++;
}
}
}
for(k=0;k<=9;k++)
{
printf("%d ",javariparker[k]);
}
return 0;
}

How to write the algorithm of this matrix in this ascending order in C.Where is error in my code?

I am writing this code to print the following matrix in this spiral order(spiral by column).But my code is printing totally different thing.
a a+7 a+8 a+15
a+1 a+6 a+9 a+14
a+2 a+5 a+10 a+13
a+3 a+4 a+11 a+12
Here is what i did:
int main() {
int a;
int Sum = 0;
int i = 0, j = 0,n;
printf("Insert the value of n: ");
scanf("%d",&n);
printf("Insert the value of a number: ");
scanf("%d",&a);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",a);
a = a + 7;
printf("\t");
}
printf("%d",a);
a = a + 1 ;
printf("\n");
}
return 0;
}
The way I approached this is to build the matrix of values you actually want, but doing so in column order, where we can relatively easily control the logic of value progression by row. Then, with that matrix in hand, print out the values in row order, as you want the output:
int main()
{
int a = 7;
int n = 4;
int array[4][4];
for (int c=0; c < n; ++c)
{
for (int r=0; r < n; ++r)
{
// values ascending for even columns
if (c % 2 == 0)
{
array[r][c] = a + c*n + r;
}
// values descending for odd columns
else
{
array[r][c] = a + c*n + n-r-1;
}
}
}
for (int i=0; i < n; ++i)
{
for (int j=0; j < n; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
Output:
Demo here:
Rextester
Instead of using this complex mechanism to keep track of all elements you can just calculate the value to add at any time by simple arithmetic.
See this
int row;
int column;
printf("\n");
for (row = 0; row < n; row++) {
for (column = 0; column < n; column++) {
int base;
int flag;
if (column % 2 != 0) {
base = (column+1)/2 * 2*n - 1;
flag = -1;
}else {
base = column/2 * 2*n;
flag = 1;
}
printf( "%d ", a + base + flag * row);
}
printf("\n");
}
I hope you are able to follow this logic. If not feel free to ask.
Demo here:
Ideone
There seem to be two issues with your code as it is. As mentioned in the above comment, you are using the variable a in the loop calculation, so it is constantly being updated. This means your loop becomes invalid after a few iterations. If you define a dummy variable, this would avoid the problem. Secondly the implementation of the spiralling is close to being right, but it's not quite there.
Consider in the case n = 4. When you print along each row, the difference between a new element and the last alternates between values of (2n - 1) = 7 and 1. To take this into account, you could for example check every time you want to print whether the column index (j) is odd or even, and use this to determine which difference to add. Once you have the row machinery fixed, it shouldn't be difficult to extend it to the columns.
Simple solution using a matrix to calculate values before print them
#include <stdio.h>
int main(void)
{
int a;
int i = 0, j = 0, n;
printf("Insert the value of n: ");
scanf("%d", &n);
printf("Insert the value of a number: ");
scanf("%d", &a);
int matrix[n][n];
for (i=0; i< n*n; i++)
{
// even columns ascending
if (((i/n) % 2) == 0)
{
matrix[i%n][i/n] = a++;
}
// odd column descending
else
{
matrix[n-(i%n)-1][i/n] = a++;
}
}
for (i=0; i< n; i++)
{
for (j=0; j< n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output
Insert the value of n: 4
Insert start value: 1
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13

How to print the amount of same integers that my 2 arrays have? [C]

I have problem with my code I need to make. I have to take 14 parameters from command line and use them to make lottery numbers, winning numbers and then compare those 2 with each other.
For example using this parameter: ./a.out 2 30 17 8 6 19 24 7 6 1 2 3 5 4
Should make something like this:
Winning numbers: 2 30 17 8 6 19 24
Lottonumbers: 7 6 1 2 3 5 4
2 are the same: 6 2
My code is almost working as intended, but I can't seem to print this right: 2 are the same. It always loops like this: 1 are the same: 6 2 are the same: 2.
Number 2 is the amount of same numbers that are found when 2 arrays are compared. My question is how can I print it so that it won't duplicate the text and with the right amount? My head can't seem to work even if it's so simple :/
#include <stdio.h>
#include <stdlib.h>
int main(int args, char **argv)
{
int i;
int winningNumbers[7];
int lottoNumbers[7];
int j;
int a;
int b;
int winningNumber;
int lottoNumber;
int count = 0;
printf("Winning numbers: ");
for (i=0;i<7; i++) {
winningNumber = atoi(argv[i+1]);
winningNumbers[i] = winningNumber;
printf("%d ", winningNumber);
}
printf("\n");
printf("Lotto numbers:: ");
for (j= 8; j < args; j++) {
lottoNumber = atoi(argv[j]);
lottoNumbers[j-8] = lottoNumber;
printf("%d ", lottoNumber);
}
printf("\n");
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
printf("%d are the same: %d", count, winningNumbers[b]);
}
}
}
return 0;
}
Searching for matches and displaying the result are two separate tasks. It is simpler and more flexible not to attempt to do them at the same time.
First search for the matches and store them in an array. Then display the content of the array however you want.
int main (int argc, char *argv[])
{
int winningNumbers[7];
int lottoNumbers[7];
int commonNumbers[7];
int count = 0;
// fill winningNumbers
// fill lottoNumbers
// NOTE: the following loop assumes that in both arrays
// no number is repeated.
// You should check that this is indeed the case.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (lottoNumbers[i] == winningNumbers[j]) {
commonNumbers[count] = lottoNumbers[i];
count++;
}
}
}
printf ("%d are the same:", count);
for (int i = 0; i < count; i++) {
printf (" %d", commonNumbers[i]);
}
printf ("\n");
return 0;
}
Many simple programs should follow this structure:
read and check input
transform input to output
print output
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
}
}
printf("%d are the same: ", count);
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
printf(" %d", winningNumbers[b]);
}
}
printf("\n");
int finalArray[7];
int i;
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
finalArray[count] = lottoNumbers[a];
count = count + 1;
}
}
}
printf("%d are same: ", count);
for(i = 0; i < count; i++)
printf("%d ", finalArray[i]);

Maximum value of every contiguous subarray

Given an unsorted array A[0...n-1] of integers and an integer k; the desired algorithm in C should calculate the maximum value of every contiguous subarray of size k. For instance, if A = [8,5,10,7,9,4,15,12,90,13] and k=4, then findKMax(A,4,10) returns 10 10 10 15 15 90 90.
My goal is to implement the algorithm as a C programm that reads the elements of A, reads k and then prints the result of the function findKMax(A,4,10). An input/output example is illustrated bellow (input is typeset in bold):
Elements of A: 8 5 10 7 9 4 15 12 90 13 end
Type k: 4
Results: 10 10 10 15 15 90 90
What I've tried so far? Please keep in mind that I am an absolute beginner in C. Here is my code:
#include <stdio.h>
void findKMax(int A[], int k, int n) {
int j;
int max;
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
}
}
int main() {
int n = sizeof(A);
int k = 4;
printf("Elements of A: ");
scanf("%d", &A[i]);
printf("Type k: %d", k);
printf("Results: %d", &max);
return 0;
}
Update March 17th:
I've modified the source code, i.e. I've tried to implement the hints of Michael Burr and Priyansh Goel. Here is my result:
#include <stdio.h>
// Returning the largest value in subarray of size k.
void findKMax(int A[], int k, int n) {
int j;
int largestValueOfSubarray;
for (int i = 0; i <= n-k; i++) {
largestValueOfSubarray = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > largestValueOfSubarray)
largestValueOfSubarray = A[i+j];
}
printf("Type k: %d", k);
}
return largestValueOfSubarray;
}
int main() {
int n = 10;
int A[n];
// Reading values into array A.
for (int i = 0; i < n; i++) {
printf("Enter the %d-th element of the array A: \n", i);
scanf("%d", &A[i]);
}
// Printing of all values of array A.
for (int i = 0; i < n; i++) {
printf("\nA[%d] = %d", i, A[i]);
}
printf("\n\n");
// Returning the largest value in array A.
int largestValue = A[0];
for (int i = 0; i < n; i++) {
if (A[i] > largestValue) {
largestValue = A[i];
}
}
printf("The largest value in the array A is %d. \n", largestValue);
return 0;
}
I guess there is not so much to code. Can anybody give me a hint how to do the rest. I need an advice how to "combine" the pieces of code into a running program.
Since you are a beginner, lets begin with the simplest algorithm.
for every i, you need to find sum of k continous numbers starting from that i. And then find the max of it.
Before that you need to see how to take input to an array.
int n;
scanf("%d",&n);
int a[n];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
Also, you will need to call the function findKMax(a,n,k);
In your findKMax function, you have to implement the algorithm that I mentioned.
I will not provide the code so that you may try on your own. If you face any issue, do tell me.
HINT : You need to use nested loops.
You find max value in window many times, but output only the last max value.
The simplest correction - add output in the end of main cycle:
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
printf("Type k: %d", k);
}
The next step - collect all local max values in a single string "10 10 10 15 15 90 90" or additional array of length n-k+1: [10,10,10,15,15,90,90] and print it after the main cycle (I don't know the best approach for this in C)

Resources