C Exercises: Find and print the square of each even and odd value between 1 and a given number
C Basic Declarations and Expressions: Exercise-109 with Solution
Write a C program to find and print the square of each even and odd values between 1 and a given number (4 < n < 101).
Sample Solution:
C Code:
#include <stdio.h>
#include <math.h>
int main () {
int x, cont = 0, i;
printf("Input a number(integer): ");
scanf("%d", &x);
if (x>=5 && x<=100);
{
printf("\nSquare of each even between 1 and %d:\n",x);
for (i = 1; i <= x; i++){
if (i % 2 == 0){
cont = pow(i, 2);
printf("%d^2 = %d\n", i, cont);
}
}
printf("\nSquare of each odd between 1 and %d:\n",x);
for (i = 1; i <= x; i++){
if (i % 2 != 0){
cont = pow(i, 2);
printf("%d^2 = %d\n", i, cont);
}
}
}
}
Sample Output:
Input a number(integer): 15 Square of each even between 1 and 15: 2^2 = 4 4^2 = 16 6^2 = 36 8^2 = 64 10^2 = 100 12^2 = 144 14^2 = 196 Square of each odd between 1 and 15: 1^2 = 1 3^2 = 9 5^2 = 25 7^2 = 49 9^2 = 81 11^2 = 121 13^2 = 169 15^2 = 225
Flowchart:
C programming Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C program that reads two integer values and calculate the sum of all odd and values between them.
Next: Write a C program to find the odd, even, positive and negative number form a given number(integer) and print a message 'Number is positive odd' or 'Number is negative odd' or 'Number is positive even' or 'Number is negative even'. If the number is 0 print “Zero”.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
Static variable inside of a function in C
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
Ref : https://bit.ly/3fOq7XP
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework