Write a c++ program that accept any positive no. and then display the sum of all the no. form 1 up to the no. imputed. (for loop) sample run: Enter a no: 5 The sum is: 15
#include<stdio.h> #include<stdlib.h> int main(){ // a : Required number, i : for the loop, sum : to calcule the sum int a, i=1, sum =0; // A little message to tell the user to enter a number printf("Enter a number : "); // Read the value scanf("%d",&a); // Test if the value is positive or negative, if negative show an error message! if (a < 0) printf("You entered %d, the number must be positive\n", a); // Else if positive do the work else { // calculate the sum by looping until " i <= a " for (i; i<=a; i++) sum = sum + i; // Print the result in the screen printf("The sum is : %d\n", sum); } // Prevent the program to exit system("pause"); }
You should notice please that the Comments must be in the same line because I used the // , Thank you. ktobah.
use cout and cin instead of printf and scanf for displaying output and taking input , if u r prgrmng in c++
True Mr. maheen_khizar, but still printf and scanf work well, I tried them. Thanks for your suggestion. ktobah.
yes printf and scanf work well , bt question was asked 4 c++ , thats why i suggest cin , cout
Alright, yes.
:-)
:P
#include "stdafx.h" #include <iostream> using namespace std; int x =1; int num; int sum; int _tmain(int argc, _TCHAR* argv[]) { cout<<"Enter a positive no.: "; cin>> num; cout<<endl; if (num<0) { cout<<"You entered " <<num<< " Please enter a postive number.\n"; } else { for ( int x =1; x<=num;x++) { sum += x; } cout<<"Answer: "<<sum<<endl; } system("pause"); return 0; } @ktobah thanks for replying. but, i cant understand your code. so made my own. is this correct?
Well, I tried your code and it has some error (not much), and this is a corrected version of your code : //#include "stdafx.h" // I turned this as a comment because stdafx.h is // a proprietary library that you are using. #include <iostream> using namespace std; int x =1; // you can write int x=1, num, sum; it's the same. int num; int sum; int main(int argc, char* argv[]){ cout<<"Enter a positive no.: "; cin>> num; cout<<endl; if (num<0){ cout<<"You entered " <<num<< " Please enter a postive number.\n"; }else{ for ( int x =1; x<=num;x++){ sum += x; } cout<<"Answer: "<<sum<<endl; } system("pause"); return 0; } NB : Sorry for the late reply we had here a problem with electricity, so I can't use Internet. Good luck; ktobah.
hey. thanks for replying. can you tell me what are the errors on my code?
Look at this line that you wrote : int _tmain(int argc, _TCHAR* argv[]) "_tmain" should be "main" because it's the main function, all the time your should write it like that. "_TCHAR*" should be "char*" because it's a predefined type like that. You're welcome and Good luck.
Join our real-time social learning platform and learn together with your friends!