The introduction to the C + + algorithm race Classic PAGE16 exercise 1-3 continuous and

Source: Internet
Author: User

Title: Input positive integer n, output 1+2+3+...+n value. Tip: The goal is to solve the problem rather than practice programming

In order to output 1+2+3+...+n, you can use the first item plus the last item multiplied by the number of items divided by the 2 formula

(1) Declares the 1+2+3+...+n and M, the positive integer n of the input:

int m,n; //

(2): Enter N:

scanf ("%d", &n);

(3) Use the formula to calculate the value of M:

M= (1+n) *n/2; //

(4) Output m:

printf ("%d", M);

Full code:

//P16 Exercise 1-3 Continuous and//Purpose: Output 1+2+3+4+...+n#include <cstdio>intM,n;//m: Temp variable N: positive integer enteredintMain () {scanf ("%d",&N); M=(1+n) *n/2;//The first item plus the last item multiplied by the number of items divided by 2printf ("%d", M); return 0;}

The introduction to the C + + algorithm race Classic PAGE16 exercise 1-3 continuous and

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.