Learn to Code - C programming more lessons

in c-programming •  2 years ago 

image.png

Source

Yesterday i shared some c programming stuff i was doing on my system. I am again here with more of those thing.

The journey to code continues here and today i printed prime numbers in c programming language. You will not learn or find everything on net you can create some of your original examples and practice more.

Here is my code :

#include <stdio.h>

int main() {
int n, i, is_prime;

// Read a positive integer from the user
printf("Enter a positive integer: ");
scanf("%d", &n);

/  / Check if each number from 2 to n is prime
 for (int num = 2; num <= n; num++) {
is_prime = 1; // Assume the current number is prime

// Check if the current number is divisible by any number from 2 to num-1
for (int i = 2; i < num; i++) {
  if (num % i == 0) {
    // The number is divisible by i, so it is not prime
    is_prime = 0;
    break; // No need to continue checking
  }
}




// If the number is prime, print it
if (is_prime) {
  printf("%d is prime\n", num);
}
} 

return 0;
}

Below is my coding screen -

Screenshot 2022-12-12 154009.png

Let us understand the code below :-

This program first reads a positive integer from the user, then checks if each number from 2 to the entered number is prime. If a number is prime, it is printed to the screen.

To check if a number is prime, the program first assumes that the number is prime (is_prime = 1). It then checks if the number is divisible by any number from 2 to the number itself (excluded). If the number is divisible by any of these numbers, it is not prime, and the is_prime variable is set to 0. Finally, if the is_prime variable is still 1 after the loop, the number is prime and it is printed to the screen.

I hope this helps! Let me know if you have any other questions and i will try to answer them.

If you also want to learn coding then just find a good teacher on the youtube. Here is my teacher. You can access the full playlist below.

Source

I will soon call myself a trader and a small programmer together.

Happy trading and keep learning what you love.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  
  ·  2 years ago  ·  

Really nice to see someone doing coding. I learnt this a long time ago but forgot everything.

Greetings

Beautiful article. Please do not forget to support other Blurtconnect publications.

Thank you for more engagement on posts in the Blurtconnect community.

Upvotes are regularly obtained on posts published by authors that engage with fellow Blurtians through comments under articles.

Your vote, by clicking here, will mean a lot to the Witness team

Peace