C Basics

 avatarAdhamElshabasy
Publica year ago6 Snippets
Search
Language
Sort by
📅 Created Date
Order
This C program prompts the user to enter a number and calculates its factorial using a while loop. The factorial is computed by multiplying the number by all positive integers less than it until it reaches 1.
#include <stdio.h>

int main() {
	
	int n, factorial;
	
	factorial = 1;
	
	printf("Enter n: ");
	scanf("%d", &n);
	
	while(n > 1) {
		factorial = factorial * n;
		n = n - 1;
	}
	
	printf("Factorial = %d\n", factorial);
	
	return 0;
}
This C program demonstrates how to calculate the growth of two investments over time.
#include <stdio.h>

int main() {
	
	float invest = 1000;
	int num_years = 0;
	
	while(invest < 2000) {
		invest = invest + (invest * 0.05);
		printf("Investment = %0.2f\n", invest);
		num_years++;
	}
	
	printf("\nIt took %d years for 1000 to double\n", num_years);
	
	///////////////////////////////////////////////////////
	
	float invest_2 = 5000;
	int i;
	
	for (i = 0; i < 5; i++) {
		invest_2 = invest_2 + (invest_2 * 0.10);
	}
	
	printf("\n5000 turned into %0.2f in 5 years\n", invest_2);
	
	return 0;
}
This C program prompts the user to enter grades for 10 students and counts how many received A (above 85) and B (above 75) grades. It ensures that the grades entered are between 0 and 100, requesting re-entry for invalid inputs. At the end, it displays the number of A and B students.
#include <stdio.h>

int main() {
	
	int i;
	int grade;
	int a_students = 0;
	int b_students = 0;
	
	for (i = 0; i < 10; i++) {
		printf("Please enter student %d grade: ", i+1);
		scanf("%d", &grade);
		
		if (grade <= 100 && grade >= 0) {
			if (grade > 85) {
				a_students++;
			}
			else {
				if (grade > 75) {
					b_students++;
				}
			}
		}
		else {
			printf(">> Please enter grade from 0 to 100\n");
			i--;
		}
	}
	
	printf("A students = %d | B students = %d\n", a_students, b_students);
	
	return 0;
}
This code demonstrates the use of both a while loop and a do-while loop in C programming. The program repeatedly prompts the user to input a value for X until they enter 0, showcasing two different looping constructs.
#include <stdio.h>

int main() {
	
	int x = 1;
	
	while(x != 0) {
		printf("Enter X (while): ");
		scanf("%d", &x);
	}
	
	do {
		printf("Enter X (do-while): ");
		scanf("%d", &x);
	} while(x != 0);
	
	return 0;
}
This C program prompts the user to enter a number and uses a switch statement to check if it matches 10, 20, or 30. Depending on the input, it prints the corresponding number or a default message if the number is not one of those options.
#include <stdio.h>

int main() {
	
	int x;
	
	printf("Please enter X: ");
	scanf("%d", &x);
	
	switch(x) {
		case 10:
			printf("10");
			break;
			
		case 20:
			printf("20");
			break;
			
		case 30:
			printf("30");
			break;
			
		default:
			printf("it was not 10, 20, or 30");
	}
	
	return 0;
}
  • Total 6 snippets
  • 1
  • 2