Which of the following for loops correctly reads and sums all the values stored in the file linked with file object inFile? (the file has been opened and contains one integer per line) Question 10 options: tot = 0 for line in inFile: tot += line tot = 0 for number in inFile: tot += int(inFile.readline( )) tot = 0 for line in inFile: tot += int(line) for number in inFile: tot += number
Added by Thomas A.
Step 1
We want to read integers from a file and sum them up. Each line in the file contains one integer. Show more…
Show all steps
Your feedback will help us improve your experience
Akash M and 57 other AP CS educators are ready to help you.
Ask a new question
Labs
Want to see this concept in action?
Explore this concept interactively to see how it behaves as you change inputs.
Key Concepts
Recommended Videos
The file has: 65 78 65 89 25 98 -999 87 34 89 99 26 78 64 34 -999 -999 23 99 98 97 26 78 100 63 87 23 -999 62 35 78 99 12 93 19 -999 C++ will not output correctly #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { int sum; int num; int counter; ifstream infile; infile.open("Exp_5_24.txt"); counter = 0; infile >> num; while (infile) { sum = 0; sum = sum + num; infile >> num; while (num != -999) { sum = sum + num; infile >> num; } cout << "Line " << counter + 1 << ": Sum = " << sum << endl; counter++; infile >> num; } infile.close(); return 0; } Line 1: Sum = 420 Line 2: Sum = 511 Line 3: Sum = -305 Line 4: Sum = 398 This is what it is supposed to be: Line 1: Sum = 420 Line 2: Sum = 511 Line 3: Sum = 0 Line 4: Sum = 694 Line 5: Sum = 398
Akash M.
Write a C++ program that will read a file of integers. Your program should find the file in the current directory of your project. The file name should be random.txt. This file contains a long list of random numbers. Your program should open the file, read all the numbers in the file, and calculate the following: a) the number of numbers in the file b) the sum of all the numbers in the file (a running total) c) the average of all the numbers in the file
Aarya B.
A file named numbers.txt contains an unknown number of lines, each consisting of a single integer. Write some code that computes the sum of all these integers, and stores this sum in a variable name sum.
Liam H.
Recommended Textbooks
Computer Science and Information Technology
Introduction to Programming Using Python
Computer Science - An Overview
Transcript
18,000,000+
Students on Numerade
Trusted by students at 8,000+ universities
Watch the video solution with this free unlock.
EMAIL
PASSWORD