C: Store a list of ints in Array [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What i'm trying to solve here is print a list of prime numbers into an array. I'm kinda fresh to C and the following code is what I have so far, it does not seem to accomplish what I am looking for which a list of prime numbers.
#inlude <stdio.h>
int main(void) {
int i, j, arr[40]
for (i=2; i<40; i++){
for (j=1; j<i; j++) {
if (i%j == 0){
arr[i] = 0;
}
else
arr[i] = i;
}
printf("%d\n", arr[i]);
}
}
This code prints a list 0 instead of primes

try this
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j, arr[40]; // you forgot ';' here
int flg =0; // use an additional flag
for (i=2; i<40; i++)
{
for (j=2; j<i; j++) // don't start from j=1? every number is divisable by 1
{
if (i%j == 0) flg=1; // flage raises whenever divisor found
}
if(flg == 0) arr[i]=i; // no divisor ==> prime number
else arr[i] =0; // there are divisors ==> not prime number
flg = 0; // reset flag to use in next iteration, next number
printf("%d\n", arr[i]);
}
}

It seems you posted code which is not original one. It contains many syntax error.
correct first it.
#inlude <stdio.h> must be #include <stdio.h>
put ; after int i, j, arr[40]
Array index must start with 0 but here you initialize array with i=2.
Also use of two for loop is looks bad codding style instead you can use one function which return the status of number if it's prime number or not. like
#include <stdio.h>
int prime(int n){
int j;
for (j=2;j<=n/2;j++)
if((n%j)==0)
return 0;
return 1;
}
void main(){
int i,p,index, arr[40];
for (i=2;index=0,i<=40;i++,index++)
{
p=prime(i);
if(p==1)
arr[index]=i;
else
arr[index]=0;
printf ("%d\n", arr[index]);
}
}

This might be what you want:
#include <stdio.h>
int main(void) {
int i, j, arr[40]={0};
for (i=2; i<40; i++){
for (j=2; j<i; j++) {
if (i%j == 0){
arr[i] = 0;
break;
}
arr[i] = i;
}
}
for(i = 1; i < 40; i++ )
printf("%d\n", arr[i]);
}

First of all, the code you've given doesn't compile. You've written inlude instead of include on the first line, and your declaration of i, j, and arr needs a ; at the end of the line.
With that taken care of, the code compiles, but it doesn't produce 0s - it produces
0
3
4
5
6
...
etc. Your inner loop sets arr[i] at every iteration, so your printf will only see what it was set to that last time through the loop. The last time through the loop, you had j=i-1, which will only satisfy your if when i = 2 (so j = 1)
To fix this you need to do two things:
Break out of the inner loop the first time you find a divisor, to make sure you don't overwrite the 0 that you write when you do find a divisor.
Start the inner loop from j=2 instead of j=1. Remember 1 is a divisor for primes (as well as every other integer), so if you start the loop from 1, all of the numbers will fail your test

Related

Why isn't this program showing any number above 3?

Wrote this to find the prime numbers between 2 to 1000. But it stops after showing that 2 and 3 are prime numbers. I know I can find how to write a code for finding out prime numbers on the internet. But I really need to know what's going wrong here.
#include <stdio.h>
main() {
int i, j;
int ifPrime = 1;
for (i = 2; i < 1000; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
ifPrime = 0;
break;
}
}
if (ifPrime == 1) {
printf("%d is prime\n", i);
}
}
}
The line
int ifPrime=1;
must be inside the outer for loop. There it will be initialized for every i. This corresponds to the natural language words "to check whether a number i is prime, first assume it is. Then check if it is divisible". The code you had before said "to check whether the numbers 2 to 1000 are prime, first assume they are", and this wording was too broad.
The code should be:
int main()
{
for (int i = 2; i < 1000; i++)
{
int ifPrime = 1;
for (int j = 2; j < i; j++)
I replaced main with int main since that is required since 20 years. (You should not learn programming from such old books.)
I moved the int i and the int j into the for loops so that you cannot accidentally use these variables outside the scope where they have defined values.
To avoid this bug in the future, it's a good idea to extract the is_prime calculation into a separate function. Then you would have been forced to initialize the ifPrime in the correct place.
Another way of finding the cause of this bug is to step through the code using a debugger and ask yourself at every step: does it still make sense what the program is doing?
You are not setting ifPrime back to 1 after checking for the single number. So once you get a number that is non_prime, ifPrime is now 0 and hence if(ifPrime == 1) would never return true post that and hence you only see 2, 3 as prime
#include <stdio.h>
int main(void) {
for( int i=2;i<1000;i++)
{
int ifPrime = 1;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
ifPrime=0;
break;
}
}
if(ifPrime==1)
{
printf("%d is prime\n",i);
}
}
return 0;
}

How to keep while loop in bubble sort function in C

I'm trying to make my own bubble-sort function in C.
As you can see in the code below this, I'm trying to only using while / if loop to create this function. I put 5 numbers (1,3,2,5,4) so that size of array of this would be 5, and I got 5 (I checked it with Python(C)tutor. However, It works well until tab[j] gets 3. I'm trying to figure it out, but couldn't figure it out why it keeps going out when tab[j] gets 3.
Could you anybody explain what's wrong to me? I would appreciate it.
Here is my code below:
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i;
int j;
int tem;
i = 0;
j = 0;
while(tab[i] < size)
{
if(tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
printf("%d ", tab[j]);
j++;
}
else if(tab[j] < tab[j+1])
{
printf("%d ",tab[j]);
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4};
int size = sizeof(tab)/sizeof(*tab);
ft_sort_integer_table(tab, size);
return(0);
}
You'll need an inner loop in your bubble sort, which is responsible for moving the largest element to the back and performing swaps i times (these large elements are "bubbling up"). Start the inner loop at 0 on each iteration and iterate through size - i (we know that the last i elements are sorted and in their final positions).
i controls your outer loop and should be incremented at the end of the loop (just as you would with a for loop). j controls the inner loop and should be incremented at the end of the loop.
While you're at it, it's a good idea to move your printing out of the sort function, which causes an unnecessary side effect and might frustrate your debugging efforts.
Also, it's worth mentioning that (1) for loops are more semantically appropriate here and (2) there is an optimization available by adding a boolean--as soon as you have a pass through the inner loop that performs no swaps, end early!
#include <stdio.h>
void ft_sort_integer_table(int *tab, int size)
{
int i = 0, j, tem;
while (i < size)
{
j = 0;
while (j < size - i)
{
if (tab[j] > tab[j+1])
{
tem = tab[j];
tab[j] = tab[j+1];
tab[j+1] = tem;
}
j++;
}
i++;
}
}
int main(void)
{
int tab[] = {1,3,2,5,4,6,7,1,5,6,8,9,1,4,5,1,2};
int size = sizeof(tab) / sizeof(*tab);
ft_sort_integer_table(tab, size);
for (int i = 0; i < size; i++)
{
printf("%d ", tab[i]);
}
return(0);
}
Output:
1 1 1 1 2 2 3 4 4 5 5 5 6 6 7 8 9
I'm trying to figure it out, but couldn't figure it out why it keeps
going out when tab[j] get 3.
From your code above, j increment in the same fashion as i. That means both variables will have the same value since j will be incremented by one after the if-then-else statement, and i will also be incremented by one at the end of each loop. Therefore, tab[j] is referencing the same value as tab[i]
With that being said, the boolean condition in the while loop checks whether the value in the tab[i] is less than the value of size.
When i == 3, tab[i] == 5 since in the loop, only the values in the array of index less then i are swapped/changed. Since the size variable holds that value of 5, tab[i] < size will result in a false value and exit the loop.
More information on bubble sort can be found here, https://www.geeksforgeeks.org/bubble-sort/

C programming array swap [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have been trying to do this for 4 hours with no luck and I really need to have it done. It is my school's task.
#include <stdio.h>
#include <stdlib.h>
int main() {
char strings[5][5][5][5][5];
char *temp[5];
int b[5];
int a[5];
int x;
int i;
int z;
int a_value;
int b_value;
//get 5 strings from the input
for (i = 0; i < 5; i++) {
scanf("%s", strings[i]);
}
//Get 5 numbers from the input
for (x = 0; x < 5; x++) {
scanf("%d %d", & b[x], & a[x]);
//printf("B is %d and A is %d\n", b[x], a[x]);
a_value = a[x];
b_value = b[x];
temp[b_value] = strings[a_value];
//If the values of a and b are equal to -1 denote the operation (end it)
if (b[x] == -1 && a[x] == -1) {
break;
}
}
//Get the swapped values
for (z = 0; z<=x; z++) {
printf("%s\n", temp[z]);
}
return 0;
}
Input:
aadf
bazz
abkt
bbaa
zzzz
1 3
0 4
3 2
-1 -1
The output is supposed to be like this
zzzz
bbaa
bazz
abkt
aadf
What I get is this
zzzz
bbaa
abkt
So everything works fine and strings get replaced based on that but the problem is that if b and a are not given so the swapped value should be the normal value and I don't know how to do it.
The task exactly says:
Read 5 strings from standard input and put them in an array. Each string is 4 characters length. Then prepare a function, that swaps i-th and j-th elements of the array. Indexes of i and j are given as standard input as two numbers separated by space. There can be more than one operations - each swap operation is separated by new line. Values -1 and -1 denote the end of operations. Print strings separated by new line.
Please help me and thanks ;)
Why 5D array, char strings[5][5][5][5][5] ? you just want to 5 strings as input So for this take 2D array
char strings[5][4];// total 5 strings , in each you can stores 4 characters.
Next things How will you scan data for 2D arrays, you need to rotate two loops namely for rows and columns . Assume row = 5 & col = 4
for (i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
scanf("%c", &strings[i][j]);
}
}
Next this temp[b_value] = strings[a_value]; statement you need to modify, modify according your requirement.
I hope this helps.
Here's you code, corrected and optimized:
#include <stdio.h>
#include <stdlib.h>
int main() {
char strings[5][5];
char temp[4];
int x,y;
//get 5 strings from the input
for (int i = 0; i < 5; i++) {
scanf("%s", strings[i]);
}
do{
scanf("%d %d", & x, & y);
// Assign string[x] to temp
for(int i=0;i<4;i++){
temp[i] = strings[x][i];
}
// Assign string[y] to string[x]
for(int i=0;i<4;i++){
strings[x][i] = strings[y][i];
}
// Assign temp to string[y]
for(int i=0;i<4;i++){
strings[y][i] = temp[i];
}
}while(x!=-1 && y!=-1);
//Get the swapped values
for (int i = 0; i< 5; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
I have tested it. Let me know if you need any explanation.

Frequency Count of Number in an array in C is this code effective and efficient [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have the following code in c for counting frequency of number from array:
#define MAX 10
int flag=0;
void display(int no,int cnt,int visi[]);//function declaration
int main()
{
int arr[]={1,1,1,2,3,4,2,2,3,1};//asume any array or we can enter from user
int visited[MAX];
int i,j,no,cnt=1;
clrscr();
for(i=0;i<10;i++)//loop
{
no=arr[i];
cnt=1;
for(j=i+1;j<10;j++)
{
if(no==arr[j])
cnt++;
}
display(no,cnt,visited);
}
return 0;
}
void display(int no,int cnt,int visited[])
{
int static i;
int j;
if(flag==1)
for(j=0;j<=i;j++)
{
if(visited[j]==no)
goto a;
}
i++;
flag=1;
printf("\n%d=%d",no,cnt);
visited[i]=no;
a:
}
Please help to improve my code or suggest any other technology for effectiveness
is this algorithm effective and efficient or not please give feedback.
You can sort the array first by merge sort (O(n log n)) and then calculate the frequency of a number by single loop like this-:
int j=0;
for( i = 0; i < 9; i++ )
{
if (arr[i] == arr[i+1])
cnt++;
else
{
visited[j] = cnt;
cnt = 0;
j++;
}
}
to count frequency of numbers in array, try this code
#include <stdio.h>
#define MAX 10
int countArray[MAX];
int main()
{
int arr[]={1,1,1,2,3,4,2,2,3,1},i;
for(i=0;i<MAX;i++)
countArray[i]=0;
for(i=0;i<MAX;i++)
countArray[arr[i]]++;
for(i=0;i<MAX;i++)
{
if(countArray[i])
printf("%d %d\n",i,countArray[i]);
}
return 0;
}
You don't say this explicitly, but it looks as if you had an array of non-negative numbers whsoe values is smaller than MAX.
If the range of the numbers is known, you can create an array of counts. Visit each element of the array once and increment the count for that element. Then pass through the array of counts and output it as appropriate.
This method works well if the range of valid numbers and therefore the size of the count array is small. (You have the same problem for your visited array, whose size is the same as the size of an array of counts.)
The example below implements counting with an array of counts. The code also takes care of values that fall outside the valid range of MIN to MAX inclusively.
#include <stdio.h>
#define MIN 1
#define MAX 10
int main()
{
int arr[] = {1, 1, 1, 2, 3, 4, 2, 2, 3};
int narr = sizeof(arr) / sizeof(arr[0]);
int count[MAX + 1 - MIN] = {0};
int uncounted = 0;
int i;
for(i = 0; i < narr; i++) {
if (arr[i] < MIN || arr[i] > MAX) {
uncounted++;
} else {
count[arr[i] - MIN]++;
}
}
for(i = MIN; i < MAX + 1; i++) {
if (count[i - MIN]) {
printf("element %d ocurs %d times.\n", i, count[i - MIN]);
}
}
if (uncounted) {
printf("%d elements were not accounted for.\n", uncounted);
}
return 0;
}
int main()
Is implementation dependant. You do not wan't to use this, some compilers will not accept it.
Use
int main(void)
instead
for(i=0;i<10;i++)//loop
You already defined MAX, so why not use it there. Stuff like this makes code harder to maintain.
The efficiency is dependant on the input values you have. For small arrays with small numbers, this works fine otherwise.

Challenge C programming

What should I do so that the program run without any mistakes ..
#include <stdio.h>
int i= 0;
while (i< SIZE){
j= i+1;
while (j<SIZE){
if (myList[i]+ myList [j] == target){
printf("%d AND %d\n", i, j);
}
j= j+1;
}
i=i+1;
}
In order to compile and execute this code, you must type this into an editor. Make sure that all required variables are suitably declared. Also make sure that the values are input using scanf() prior to executing these if-else statements. If you run the compiler several times, it will help you to identify the variables that must be declared.
Question: Write a C program that will read in N=1000 integers, i1, i2, …, iN. These numbers are not sorted and you may assume that these integers also do not have any regular pattern. After reading these N integers, your program must now read in a new integer called the Target. Find all pairs of integers ij and ik from these N integers such that ij + ik = Target.
Well, I tried your code, and have got it to work. I am assuming that j can be equal to k. If they cannot be equal, then I have indicated which part is to be changed in the code ( There its i and j instead of j and k ). Well here's the fixed code
#include <stdio.h>
#define SIZE 10 // You can change SIZE here
int main()
{
int myList[SIZE],target;
printf("Enter 10 Numbers\n");
for(int k=0;k<SIZE;k++)
{
scanf("%d",&myList[k]);
}
printf("Enter the target\n");
scanf("%d",&target);
int i= 0,j;
while (i< SIZE)
{
j=i; // if i and j should not be equal just change it to j=i+1
while (j<SIZE)
{
if (myList[i]+ myList [j] == target)
{
printf("%d AND %d\n", i, j);
}
j= j+1;
}
i=i+1;
}
return 0;
}
In this code, I have taken SIZE=10 for convenience because I don't want to enter 1000 numbers. You can just change SIZE to 1000 whenever you want.
Cheers.......Hope this is what you wanted.

Resources