In: Computer Science
C++ . It should all be in one code and using WHILE loops
2. Write a piece of code that asks the user for a number and adds up the even numbers from 1 to that entered number.
3. Write a piece of code that asks the user for 2 numbers and adds up the numbers between and including the numbers.
4. Write another piece of code that asks the user for a random file name and adds all of the numbers in the file and reads until the end of the file.
CODE:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a;//declaring a variable
cout<<"Enter a number : ";
cin>>a;//taking number from user
int sum=0,i=1;//declaring variables
//while loop to calculate the sum of evens.
while(i<=a)
{
if(i%2==0)//condition to check number is even.
{
sum+=i;//adding number to sum
}
i++;//incrementing i.
}
cout<<"The even sum is : "<<sum<<endl;
int b,c;//declaring variables
cout<<"Enter two numbers : ";
cin>>b>>c;
int sum1=0;//declaring variables
//while loop to calculate the sum of numbers between.
while(b<=c)
{
sum1+=b;//adding number to sum
b++;//incrementing b.
}
cout<<"The sum of numbers is :
"<<sum1<<endl;
char filename[30];//declaring variables
cout<<"Enter a file name : ";
cin>>filename;//taking random file name from user.
ifstream file(filename);//declaring file stream.
int s,sum2=0;//declaring variables
//while loop to iterate through file and add numbers
while(file>>s)
{
sum2+=s;//adding the read numbers.
}
cout<<"The sum of numbers in file is :
"<<sum2<<endl;
file.close();//closing the file
}
CODE
OUTPUTS:
OUTPUTS:
txt files:
Please do comment
for any queries.
Please like it.
Thank you.