C Programming Code Examples
C > Functions Code Examples
C program to check prime, armstrong, perfect number using functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/* C program to check prime, armstrong, perfect number using functions
Write a C program to check whether a number is prime, armstrong, perfect number or not using functions. How to check prime or armstrong or perfect number in C programming using functions.
Function declarations to check prime, armstrong and perfect numbers are same. Hence, I will only explain how to declare a function to check prime number.
First give a meaningful name to our prime checking function say isPrime() function will check a number for prime.
Next, since our function checks a number for prime condition. Hence, it must accept a number, say isPrime(int num);.
Finally, the function should return a value to the caller, so that the caller can know whether the integer passed to the function is prime or not. For this we must return boolean true or false depending on the prime check result. Therefore return an integer from function either 1 or 0.
The function declaration to check prime number is int isPrime(int num);. Similarly you can declare functions to check armstrong and perfect numbers. */
#include <stdio.h>
#include <math.h>
/* Function declarations */
int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
// Call isPrime() functions
if(isPrime(num))
{
printf("%d is Prime number.\n", num);
}
else
{
printf("%d is not Prime number.\n", num);
}
// Call isArmstrong() function
if(isArmstrong(num))
{
printf("%d is Armstrong number.\n", num);
}
else
{
printf("%d is not Armstrong number.\n", num);
}
// Call isPerfect() function
if(isPerfect(num))
{
printf("%d is Perfect number.\n", num);
}
else
{
printf("%d is not Perfect number.\n", num);
}
return 0;
}
/**
* Check whether a number is prime or not.
* Returns 1 if the number is prime otherwise 0.
*/
int isPrime(int num)
{
int i;
for(i=2; i<=num/2; i++)
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if(num%i == 0)
{
return 0;
}
}
return 1;
}
/**
* Check whether a number is Armstrong number or not.
* Returns 1 if the number is Armstrong number otherwise 0.
*/
int isArmstrong(int num)
{
int lastDigit, sum, originalNum, digits;
sum = 0;
originalNum = num;
/* Find total digits in num */
digits = (int) log10(num) + 1;
/*
* Calculate sum of power of digits
*/
while(num > 0)
{
// Extract the last digit
lastDigit = num % 10;
// Compute sum of power of last digit
sum = sum + round(pow(lastDigit, digits));
// Remove the last digit
num = num / 10;
}
return (originalNum == sum);
}
/**
* Check whether the number is perfect number or not.
* Returns 1 if the number is perfect otherwise 0.
*/
int isPerfect(int num)
{
int i, sum, n;
sum = 0;
n = num;
for(i=1; i<n; i++)
{
/* If i is a divisor of num */
if(n%i == 0)
{
sum += i;
}
}
return (num == sum);
}
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc.
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Round to nearest. Returns the integral value that is nearest to x, with halfway cases rounded away from zero. Rounds a floating-point number to an integer value. The round() functions round a floating-point number to the nearest integer value, regardless of the current rounding direction setting in the floating-point environment. If the argument is exactly halfway between two integers, round() rounds it away from 0. The return value is the rounded integer value.
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,
Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language: Simple assignment operator. Assigns values from right side operands to left side operand. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
Compute common logarithm. Returns the common (base-10) logarithm of x. Calculates the base-10 logarithm of a number. The log10() functions calculate the common logarithm of their argument. The common logarithm is the logarithm to base 10. The common logarithm of a number x is defined only for positive values of x. If x is negative, a domain error occurs; if x is zero, a range error may occur. Function returns common logarithm of x. If x is negative, it causes a domain error. If x is zero, it may cause a pole error (depending on the library implementation).
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Raise to power. Returns base raised to the power exponent: baseexponent. The function pow() is used to calculate the power raised to the base value. It takes two arguments. It returns the power raised to the base value. It is declared in "math.h" header file.
Read a 'five-letter' Word into the pc, and then encode the word on a letter-by-letter basis by subtracting 30 from the Numerical value that is used to represent each Letter. Thus if ASCII
Program print Strong numbers between 1 to n. Strong number is a special number whose sum of factorial of digits is equal to original number. For example: 145 is strong number.
Interrupts are messages to the Pentium chip to halt it current activity, and perform our requested job. We can almost do anything using interrupts without using functions...