In: Computer Science
Write a series of codes using WHILE loops C++
1. Ask the user for a number and adds even numbers for 1 to the user entered number.
2. Write another piece of code that asks the user for 2 numbers and adds up the numbers between and including the numbers.
3. Write another piece of code that asks user for a file name and then add up all the numbers for the file.
First Code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cout<<"Enter the no: \n";
cin>>t;
int j=1;int sum=0;
while(j<=t)
{
if(j%2==0)
sum++;
j++;
}
cout<<sum<<"\n";
return 0;
}
Second Code :
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,y;
cout<<"Enter the first number: ";
cin>>x;
cout<<"Enter the second number: ";
cin>>y;
int sum=0;
while(x<=y)
{
sum=sum+x;
x++;
}
cout<<sum<<"\n";
return 0;
}
Third Code:
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ifstream fin;
char filename[20];
cout<<"Enter The File Name With Extension\n";
cin>>filename;
fin.open(filename);
if (!fin)
{
cout<< "File not found." << endl;
return -1;
}
string line;
getline(fin, line);
istringstream str(line);
int sum = 0, next = 0;
while (str >> next)
sum += next;
fin.close();
cout<<sum<<"\n";
return 0;
}