C Program to Print Integer Numbers Till N

Write a C program to print integer numbers till user entered limit(num).

Natural numbers are all the numbers from 1, 2, 3, 4, 5, … They are the numbers you usually count and they will continue till infinity.

Whole numbers are all natural numbers including 0.
e.g. 0, 1, 2, 3, 4, 5, …

Integer numbers include all whole numbers and their negative counterpart
e.g. …, -4, -3, -2, -1, 0,1, 2, 3, 4, 5, …

Related Read:
C Program to Print Natural Numbers from 1 to N using While loop
C Program to Print Natural Numbers from 1 to N using for loop

scale

Expected Input/Output

User Input:
Enter an integer number
-5
Output:
Integer numbers from -1 to -5 are …
-1
-2
-3
-4
-5

Video Tutorial: C Program to Print Integer Numbers Till N



YouTube Link: https://www.youtube.com/watch?v=K67VDa5iLLI [Watch the Video In Full Screen.]

Source Code: C Program to Print Integer Numbers Till N: using For loop

#include<stdio.h>

int main()
{
    int num, i;

    printf("Enter an integer number\n");
    scanf("%d", &num);

    if(num < 0)
    {
        printf("Integer numbers from -1 to %d are ...\n", num);
        for(i = -1; i >= num; i--)
            printf("%d\n", i);
    }
    else if(num > 0)
    {
        printf("Integer numbers from 1 to %d are ...\n", num);
        for(i = 1; i <= num; i++)
            printf("%d\n", i);
    }
    else
    {
        printf("You entered zero!\n");
    }

    printf("\n");

    return 0;
}

Output 1:
Enter an integer number
0
You entered zero!

Output 2:
Enter an integer number
5
Integer numbers from 1 to 5 are …
1
2
3
4
5
Output 3:
Enter an integer number
-5
Integer numbers from -1 to -5 are …
-1
-2
-3
-4
-5

Logic To Print Integer Numbers Till N: using For loop

For a integer number input there are 3 possible cases: Either user can input positive number, negative number or a zero. So we cover all these 3 possibilities in our program.

If user enters a number less than 0, then its a negative number. So we initialize i value to -1(which is the biggest negative number), and iterate the for loop until i is greater than or equal to the user entered number. For each iteration we reduce the value of i by 1. Inside for loop, we print the value of i.

If user entered number is greater than 0, then its a positive number. So we initialize i value to 1(smallest positive number), and iterate the for loop until i is less than or equal to user entered number, and for each iteration we increment the value of i by 1. Inside for loop we print the value of i.

If user enter number is nether greater than 0 and nor less than zero, then the user input number must be 0. In that case, we simply output the message that – user entered zero!

Note:
1. When user inputs a negative number, it’ll always be smaller than or equal to -1.
2. When user inputs a positive number, it’ll always be greater than or equal to 1.

Source Code: C Program to Print Integer Numbers Till N: using while loop

#include<stdio.h>

int main()
{
    int num, count;

    printf("Enter a integer number\n");
    scanf("%d", &num);

    if(num < 0)
    {
        count = -1;
        printf("Integer numbers from -1 to %d are ...\n", num);
        while(count >= num)
        {
            printf("%d\t", count);
            count--;
        }
    }
    else if(num > 0)
    {
        count = 1;
        printf("Integer numbers from 1 to %d are ...\n", num);
        while(count <= num)
        {
            printf("%d\t", count);
            count++;
        }
    }
    else
    {
        printf("You entered zero!\n");
    }

    printf("\n");

    return 0;
}

Logic To Print Integer Numbers Till N: using While loop

1. For negative value input: We initialize count value to -1, as its the biggest negative number. In while loop condition we check if user input number is less than or equal to value of count(-1), if true, we print the value of count. And for each iteration we decrement the value of count by 1.

2. For positive value input: We initialize count value to 1, as its the smallest positive number. In while loop condition we check if user input number is greater than or equal to value of count(1), if true, we print the value of count. And for each iteration we increment the value of count by 1.

Note:
1. For negative value input, we initialize count value to -1, because we want to print from -1 till user input number.
2. For positive value input, we initialize count value to 1, because we want to print from 1 till user input number.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Prime Numbers using Sieve of Eratosthenes: C Program

Implement in a c program the following procedure to generate prime numbers from 1 to 100. This procedure is called Sieve of Eratosthenes.

Step 1: Fill an array num[100] with numbers from 1 to 100.

Step 2: Starting with the second entry in the array, set all its multiples to zero.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Step 4: Repeat Step 3 till you have set up the multiples of all the non-zero elements to zero.

Step 5: At the conclusion of Step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.

Simpler Version of Sieve of Eratosthenes

You can watch our previous video tutorial for simpler version of Sieve of Eratosthenes method to find prime numbers from 2 to N: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Visual Representation

prime numbers from 2 to 100 sieve of erathosthenes

Video Tutorial: Prime Numbers using Sieve of Eratosthenes: C Program



YouTube Link: https://www.youtube.com/watch?v=oL9jzKm6uZQ [Watch the Video In Full Screen.]

Input num[N] with numbers 1 to 100

Step 1:

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 0; i < N; i++)
            printf("%d\t", num[i]);

    return 0;
}

Output:
This code outputs natural numbers from 1 to 100.

Note:
Array index starts from 0. So elements from index 0 to 99 will have 100 elements.

At index 0 we’ll store number 1, and at index 1 we’ll store number 2 and so on until index 99 where we store number 100. i.e., the index number is 1 less than the element/number present at that index.

Starting with the second entry in the array, set all its multiples to zero.

Step 2:

    int limit = sqrt(N);

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

Here we initialize i to second entry in the array, which has element 2(first prime number). Iterate the for loop until i is less than or equal to square root of N or you can even write (num[i] * num[i]) <= N as the condition for outer for loop. We’ve shown the reason for writing that condition in our other video tutorial present here: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program.

Step 3: Proceed to the next non-zero element and set all its multiples to zero.

Inside inner for loop: for any non-zero element we check for their multiples and if we find any, we store 0 – indicating that it was a composite number.

We repeat Step 3 till we have set up the multiples of all the non-zero elements to zero.

Initialized j to pow(num[i], 2) ?

Because the first number to be struck off by num[i] will be pow(num[i], 2) or (num[i] x num[i]). In other words, the first number or the first multiple of num[i] where our program will insert 0 is pow(num[i], 2) or (num[i] x num[i]).

j = j + num[i]
It can also be written as j += num[i]. For each iteration of inner for loop, j value should increment by num[i] times, so that the position (j – 1) will have the multiple of number present at num[i]. In that case num[j – 1] will be multiple of num[i], and hence composite number – so we store 0 at num[j – 1].

Step 5: Print Prime Numbers
Finally all the non-zero numbers/elements are prime numbers.

Source Code: Prime Numbers using Sieve of Eratosthenes: C Program

using math.h library file

#include<stdio.h>
#include<math.h>

#define N 100

int main()
{
    int num[N], i, j;
    int limit = sqrt(N);

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; i <= limit; i++)
    {
        if(num[i] != 0)
        {
            for(j = pow(num[i], 2); j <= N; j = j + num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

Source Code: Without using math.h library file

#include<stdio.h>

#define N 100

int main()
{
    int num[N], i, j;

    for(i = 0; i < N; i++)
        num[i] = i + 1;

    for(i = 1; (num[i] * num[i]) <= N; i++)
    {
        if(num[i] != 0)
        {
            for(j = num[i] * num[i]; j <= N; j += num[i])
            {
                num[j - 1] = 0;
            }
        }

    }

    printf("Sieve of Eratosthenes Method\n");
    printf("To find Prime numbers from 2 to %d\n\n", N);
    for(i = 1; i < N; i++)
    {
        if(num[i] != 0)
            printf("%d\t", num[i]);
    }

    printf("\n");

    return 0;
}

Output
This outputs all the prime numbers from 2 to 100.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program

Lets write a C program to find prime numbers from 2 to N, using Sieve of Eratosthenes method.

Important Note

We are working on index numbers here. Array elements will have only 2 values: 1 or 0. Wherever the value of array element is 1, that means it’s position/index number is prime orelse its composite number.

Working on array elements

This video tutorial solves text book problem statement to find prime numbers using Sieve of Eratosthenes Method: Prime Numbers using Sieve of Eratosthenes: C Program.

Visual Representation

prime numbers from 2 to 100 sieve of erathosthenes

Video Tutorial: Sieve of Eratosthenes Method To Find Prime Numbers: C Program



YouTube Link: https://www.youtube.com/watch?v=rb5bClbN3o8 [Watch the Video In Full Screen.]

Source Code: Find Prime Numbers from 2 To N using Sieve of Eratosthenes: C Program

#include<stdio.h>
#include<math.h>

#define N 101

int main()
{
    int a[N] = {[0 ... N - 1] = 1}, i, j;
    int num  = sqrt(N - 1);

    for(i = 2; i <= num; i++)
    {
        if(a[i] == 1)
        {
            for(j = i * i; j < N; j += i)
                a[j] = 0;
        }
    }

    printf("Sieve of Eratosthenes\n");
    printf("Prime numbers from 2 to %d are ...\n", N - 1);
    for(i = 2; i < N; i++)
    {
        if(a[i])
            printf("%d\t", i);
    }

    return 0;
}

Output
Above code outputs all the prime numbers between 2 to N – 1.

Logic To Find Prime Numbers from 2 To N using Sieve of Eratosthenes

1. We’re using Designated Initializers to initialize all the elements of array to 1. Here we are initializing all the elements from index 0 to N – 1. If you write 0 to N, it’ll start throwing out of bounds error. As 0 to 101(if N value is 101) will be 102 elements, which exceeds the size of array.

2. Next we find square root of N – 1. Its enough to check till square root of N – 1, to get all the prime numbers – I’ve shown you the proof in the video posted above in this article.

3. Since 2 is the first prime number, we initialize i to 2 and we iterate the for loop till square root of N – 1. For each iteration increment the value of i by 1.

4. Initially we assume that all the numbers are prime, by storing 1 in all the array elements.

5. After careful observation, we come to know that the first index position we store zero for any index i is i * i. So we initialize j value to i * i. For each iteration of the inner for loop we increment the value of j by i times. Inside inner for loop we store 0 at a[j].

If we keep adding value of i to the previous value of j, then j will always have a number which is multiple of i. So we store 0 at a[j].

6. We keep repeating Step 5 until i is less than or equal to square root of N – 1.

7. Once i is equal to square root of N – 1, we print all the index numbers or position of element which has 1 in it. So these index numbers are prime numbers from 2 to N – 1.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find First and Second Biggest Element In An Array using Recursion

Lets write a C program to find first and second biggest element/number in an array, without sorting it, and by using recursion.

Related Read:
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language

Important Video Tutorial
C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
5
2
6
4
3
First Big: 6
Second Big: 5

Visual Representation

First and Second Biggest Element In An Array using Recursion

Video Tutorial: C Program To Find First and Second Biggest Element In An Array using Recursion



YouTube Link: https://www.youtube.com/watch?v=UqNZrOZa9u0 [Watch the Video In Full Screen.]

Source Code: C Program To Find First and Second Biggest Element In An Array using Recursion

#include<stdio.h>

#define N 5

void fsBig(int *num, int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*num > first)
        {
            second = first;
            first  = *num;
        }
        else if(*num > second && *num != first)
            second = *num;

        fsBig(--num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );
            break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(&a[N - 1], N - 1, first, second);

    return 0;
}

Output 1:
Enter 5 integer numbers
5
5
4
2
1
First Big: 5
Second Big: 4

Output 2:
Enter 5 integer numbers
5
5
5
5
5
Biggest: 5
Smallest: 5

Logic To Find First and Second Biggest Element In An Array using Recursion

We ask the user to enter N integer numbers and store it inside the address of array variable a[N]. Next we assign the biggest value between a[0] and a[1] to variable first and second biggest value to variable second. Then we pass the last elements address and length of the array and variables first and second to a function fsBig().

Inside function fsBig()

void fsBig(int *num, int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*num > first)
        {
            second = first;
            first  = *num;
        }
        else if(*num > second && *num != first)
            second = *num;

        fsBig(--num, --n, first, second);
    }
}

First we write the base condition or the termination condition: Once the length of the array or the variable n value is less than 2, we print the value present in variable fbig and sbig, and the control exits the function fsBig();

Note: We are checking till n < 2, because variables first and second already has values present at index 0 and 1, so need not compare them again against themselves.

Inside else block we write the actual logic to find the first and second biggest element in the array. First we check if the value present in pointer variable *num is greater than value present in variable fbig. If true, then there is a element which is bigger than fbig, that means, now whatever is present in fbig becomes second biggest element – so we transfer value present in fbig to sbig, and then transfer the new found biggest element of the array to variable fbig.

If a number is not greater than fbig, it can still be greater than sbig. So we check for that condition in else if. If its true, then we transfer the value of *num to sbig.

Recursive call
Next we call the same method fsBig() with new values. i.e., we reduce the address of num by 1, we reduce the value of index n by 1, and we pass the new values of fbig and sbig. This keeps on iterating until value of n is less than 2. Once the value of n is less than 2, the base condition is met and the control executes the printf() statement and exits the function fsBig().

Using array variable to receive base address from main method

#include<stdio.h>
#define N 5

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(num[n] > first)
        {
            second = first;
            first  = num[n];
        }
        else if(num[n] > second && num[n] != first)
            second = num[n];

        fsBig(num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );

             break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(a, N - 1, first, second);

    return 0;
}

Output 1:
Enter 5 integer numbers
5
4
5
2
1
First Big: 5
Second Big: 4

Output 2:
Enter 5 integer numbers
5
5
4
4
2
First Big: 5
Second Big: 4

Here we do not alter the value of num while recursively calling the method fsBig(), as we compare with all the elements of the array by changing the value of index variable n.

Whenever we use array variable, compiler converts it to pointer as below

#include<stdio.h>

#define N 5

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*(num + n) > first)
        {
            second = first;
            first  = *(num + n);
        }
        else if(*(num + n) > second && *(num + n) != first)
            second = *(num + n);

        fsBig(num, --n, first, second);
    }
}

int main()
{
    int a[N], i, first, second, count = 0;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        if(a[i] != a[0])
        {
            ( (a[0] > a[i]) ?
              (first = a[0], second = a[i]) :
              (first = a[i], second = a[0]) );

             break;
        }
        else
            count++;
    }

    if(count == N)
    {
        printf("Biggest: %d\nSmallest: %d\n", a[0], a[0]);
        return 0;
    }

    fsBig(a, N - 1, first, second);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
5
5
First Big: 5
Second Big: 3

Whenever compiler encounters array variable like this a[i] or num[n] it converts it into *(a + i) and *(num + n).
i.e., Variable_name[array_index] = *(Base_address + array_index)
Note that, Variable_name holds Base_address. So Variable_name = Base_address.

Its faster to work with address than with variables. This example proves that arrays are pointers in disguise. i.e., arrays use pointers internally.

Explanation With Example

N = 5;
a[N] = {5, 4, 6, 2, 3};
first = 5;
second = 4;
n = N -1 = 5 – 1 = 4;

void fsBig(int num[], int n, int first, int second)
{
    if(n < 2)
        printf("First Big: %d\nSecond Big: %d\n", first, second);
    else
    {
        if(*(num + n) > first)
        {
            second = first;
            first  = *(num + n);
        }
        else if(*(num + n) > second && *(num + n) != first)
            second = *(num + n);

        fsBig(num, --n, first, second);
    }
}
nnum[n]–nfbigsbig
43354
32254
26165

First Big: 6
Second Big: 5

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Smallest Element in An Array using Pointers

Write a c program using pointers to find the smallest number in an array of 25 integers.

Pointers: A pointer variable is a variable which holds the address of another variable, of its own type.

Important Note:
1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.

Related Read:
C Program To Find Smallest Element In An Array
Basics of Pointers In C Programming Language
Introduction To Arrays: C Programming Language
C Program To Find Smallest Element in An Array using Recursion

Important Video Tutorial
C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
1
5
5
0
2
Smallest Element In The Array: 0

Visual Representation

Smallest Element In An Array using Pointers

Video Tutorial: C Program To Find Smallest Element in An Array using Pointers



YouTube Link: https://www.youtube.com/watch?v=bTDqhyaxPtE [Watch the Video In Full Screen.]

Source Code: C Program To Find Smallest Element in An Array using Pointers

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, *small;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    small = &a[0];

    for(i = 1; i < N; i++)
    {
        if( *(a + i) < *small)
            *small = *(a + i);
    }

    printf("Smallest Element In The Array: %d\n", *small);

    return 0;
}

Output:
Enter 5 integer numbers
5
2
6
4
3
Smallest Element In The Array: 2

Here we are assigning base address to pointer variable small.

Logic To Find Smallest Element In An Array using Pointers

We ask the user to input N integer numbers and store it inside a[N]. Next we assign base address to pointer variable small. Next we iterate through the array elements one by one using a for loop, and check if any of the elements of the array is smaller than whatever the value present at *small. If there is any element smaller than *small, we assign that value to *small.

Once the control exits the for loop, we print the value present in pointer variable *small, which holds the smallest element in the array.

Initializing *small to last elements address

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, *small;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    small = &a[N - 1];

    for(i = 0; i < N - 1; i++)
    {
        if( *(a + i) < *small)
            *small = *(a + i);
    }

    printf("Smallest Element In The Array: %d\n", *small);

    return 0;
}

Output:
Enter 5 integer numbers
5
2
6
4
3
Smallest Element In The Array: 2

Here the logic is same, but we are assigning the address of last element of the array to pointer variable small.

Here we are simply making use of array variable for comparison

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, *small;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    small = &a[0];

    for(i = 1; i < N; i++)
    {
        if( a[i] < *small)
            *small = a[i];
    }

    printf("Smallest Element In The Array: %d\n", *small);

    return 0;
}

Output:
Enter 5 integer numbers
2
1
3
4
5
Smallest Element In The Array: 1

As you can see in the above source code we are using array variable in if condition. But compiler converts a[i] to *(a + i). So internall a[i] is denoted as *(a + i) – which is *(base address + index).

Explanation With Example

N = 5;
a[N] = {5, 4, 6, 2, 3};
small = &a[0];

    small = &a[0];

    for(i = 1; i < N; i++)
    {
        if( *(a + i) < *small)
            *small = *(a + i);
    }

Here index variable i is initialized to 1. That is because pointer variable small has base address i.e., address of first element of the array. So we need not compare the value with itself. So we skip comparing it with a[0], and start the comparison from next index, which is 1.

i*(a + i) < *small*small
14 < 54
26 < 44
32 < 42
43 < 22

Smallest Element In The Array: 2

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert