본문 바로가기
학부공부/C_Basic

2. Loop[C Basic]

by sonpang 2021. 11. 6.
반응형

2.1.

Write a program that

(1) inputs two integers (integer1 and integer 2)

(2) prints sum of all integers between integer1 and integer2

(3) Use while() statement

#include<stdio.h>
int main()
{
	int n1, n2, sum=0, temp;
	printf("Enter two integers : ");
	scanf("%d %d", &n1, &n2);
	temp = n1; 
	if (n1 > n2) {
		temp = n2;
		n2 = n1;
		n1 = temp;
	}
	while (n1 <= n2)
		sum += n1++;
	printf("The sum of all integers between %d and %d is %d", temp,n2,sum);

	return 0;

}

 

2.2.

Write a program that reads a nonnegative integer, and computes and prints its factorial (For example, 5! = 5x4x3x2x1 = 120)

#include<stdio.h>
int main()
{

	int n,i=1, fac=1;
	printf("Enter a positive integer : ");
	scanf("%d", &n);
	while (n < 0){
		printf("Enter a positive integer : ");
		scanf("%d", &n);
	}

	while (i <= n) {
		fac *= i++;
	}
	printf("%d! is %d", n, fac);

	return 0;
}

 

2.3.

Write a program that reads an integer, and determines and prints how many digits in the integer are 7s

#include<stdio.h>
int main()
{
	
	int n=1000, nc, cnt=0;
	while (n < 10000 || n > 100000){
		printf("Enter a 5-digit number : ");
		scanf("%d", &n);
	}
	nc = n;
	while (n > 0) {
		if (n % 10 == 7)
			cnt++;
		n /= 10;
	}
	printf("The number %d is has %d seven(s) in it", nc, cnt);

	return 0;	
}

 

2.4.

Write a program that reads two integers, and determines and prints if the first is a multiple of the second

#include<stdio.h>
int main()
{
	int n1, n2;
	printf("Input two integers : ");
	scanf("%d %d", &n1, &n2);
	if (n1%n2 == 0)
		printf("%d is a multiple of %d by a factor of %d", n1, n2, n1 / n2);
	else
		printf("%d is not a multiple of %d", n1, n2);

	return 0;
}

 

2.5.

Write a program that reads the integers and terminates when it reads 0. 

Then determines and prints the sum, the largest integers, the smallest integers, the odd integers count, the even integers count, the negative number count in the group.

#include<stdio.h>
int main()
{
	int n=1,sum=0, large=0, small=0, odd_c=0, even_c=0, negative_c=0;
	while (n != 0) {
		printf("Input the number : ");
		scanf("%d", &n);
		sum += n;
		if (n > large)
			large = n;
		if (n < small)
			small = n;
		if (n > 0 && n % 2 == 0)
			even_c++;
		if (n > 0 && n % 2 == 1)
			odd_c++;
		if (n < 0)
			negative_c++;

	}
	printf("------------------------\n");
	printf("Sum : %d\nLargest : %d\nSmallest : %d\nOdd number count : %d\nEven number count : %d\nNegative number count : %d",sum,large,small,odd_c,even_c,negative_c);
	
	return 0;
}

 

 

 

반응형

'학부공부 > C_Basic' 카테고리의 다른 글

6. Pointer[C Basic]  (0) 2021.11.07
5. Array and Functions[C Basic]  (0) 2021.11.07
4. Function[C Basic]  (0) 2021.11.07
3. Loop[C Basic]  (0) 2021.11.07
1. Input and Output[C Basic]  (0) 2021.11.06

댓글