C Programming
In this exercise section of the tutorial we will write some C program.
So, we first have to take the value of n (integer) from the user as input.
Then, we have to check if the value of n satisfies the condition 1 <= n <= 10 i.e., n must be greater than or equal to 1 and n must be less than or equal to 10. So, n can take any value from 1 to 10.
Lets write the C program.
/** * file: hello_world.c * author: yusuf shakeel * date: 2010-12-15 * description: hello world program */ #include <stdio.h> int main(void) { //variable int n, i; //user input printf("Enter value of n between 1 to 10: "); scanf("%d", &n); //check condition if (n >= 1 && n <= 10) { //print Hello World for (i = 1; i <= n; i++) { printf("Hello World\n"); } } else { printf("Error: Value of n must be between 1 to 10.\n"); } printf("End of code\n"); return 0; }
Output
Enter value of n between 1 to 10: 5 Hello World Hello World Hello World Hello World Hello World End of code
If we enter some other value of n then we will get an error message.
Enter value of n between 1 to 10: 100 Error: Value of n must be between 1 to 10. End of code
The formula to find the volume of a sphere is given below.
V = (4πr3)/3 where, V = Volume of the sphere r = Radius of the sphere
To solve this lets take the PI value as 3.14 so, we can re-write the expression as follows
V = (4 * PI * r * r * r) / 3 where, V = Volume of the sphere PI = 3.14 approx. value of π r = Radius of the sphere
/** * file: sphere_volume.c * author: yusuf shakeel * date: 2010-12-20 * description: volume of sphere program */ #include <stdio.h> #define PI 3.14 int main(void) { //variable float r, volume; //user input printf("Enter radius: "); scanf("%f", &r); //compute volume = (4 * PI * r * r * r) / 3; //output printf("Volume: %f\n", volume); printf("End of code\n"); return 0; }
Enter radius: 7 Volume: 1436.026611 End of code
Pattern: * * * * * * * * * * * * * * * * * * * * *
Looking at the above pattern we can tell that there are 6 rows and 6 columns.
So, we can write the first for loop for the rows and the second for loop for the column.
Another thing to note is that: 1st row contains 1 star 2nd row contains 2 stars 3rd row contains 3 stars and so on...
Lets write the program in C.
/** * file: pattern.c * author: yusuf shakeel * date: 2010-12-10 * description: patterns program */ #include <stdio.h> int main(void) { //variables int r, c; for (r = 1; r <= 6; r++) { for (c = 1; c <= r; c++) { printf("* "); } printf("\n"); } printf("End of code\n"); return 0; }
* * * * * * * * * * * * * * * * * * * * * End of code