Factors of A Given Number

CCBeginner
Practice Now

Introduction

In this lab, we will create a C program to find the factors of a given number.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Getting User Input

First, we will get an integer input from the user. This integer will be used to find the factors of the number.

#include <stdio.h>

int main()
{
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    // code to find factors
    return 0;
}

Finding the Factors

Next, we will write a loop to find the factors of the number. Factors are numbers that divide the given number evenly without any remainder. To find the factors of a number, we will iterate from 1 to (number / 2) and check if the current number divides the given number evenly. If it does, we print the current number as a factor of the given number.

#include <stdio.h>

int main()
{
    int num, i;
    printf("Enter an integer: ");
    scanf("%d", &num);
    printf("Factors of %d are: ", num);
    for(i = 1; i <= num/2; i++)
    {
        if(num % i == 0)
        {
            printf("%d ", i);
        }
    }
    printf("%d", num);
    return 0;
}

Testing the Program

Now we will compile and run our program to test if it is working correctly. We will execute the program and enter an integer as input. The program should find and print all the factors of the given number.

Full Code

Here is the full code for the program:

#include <stdio.h>

int main()
{
    int num, i;
    printf("Enter an integer: ");
    scanf("%d", &num);
    printf("Factors of %d are: ", num);
    for(i = 1; i <= num/2; i++)
    {
        if(num % i == 0)
        {
            printf("%d ", i);
        }
    }
    printf("%d", num);
    return 0;
}

Summary

In this lab, we created a C program to find the factors of a given number. We learned how to use loops and conditional statements to write an algorithm to find the factors of a number. We also tested the program to ensure that it produces the correct output.

Other C Tutorials you may like