0
0
C++programming~10 mins

Basic formatting in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print a formatted integer using cout.

C++
#include <iostream>
int main() {
    int number = 42;
    std::cout << [1] << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
A"number"
Bstd::endl
Cnumber
D42
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around the variable name, which prints the word instead of the value.
Using std::endl instead of the variable.
2fill in blank
medium

Complete the code to print a floating-point number with two decimal places using std::fixed and std::setprecision.

C++
#include <iostream>
#include <iomanip>
int main() {
    double pi = 3.14159;
    std::cout << std::fixed << std::setprecision([1]) << pi << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
A3
B0
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using setprecision without std::fixed, which changes total digits instead of decimal places.
Choosing the wrong number for precision.
3fill in blank
hard

Fix the error in the code to print a string and an integer separated by a space.

C++
#include <iostream>
#include <string>
int main() {
    std::string name = "Alice";
    int age = 30;
    std::cout << name [1] " " << age << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
A,
B<<
C+
D>>
Attempts:
3 left
💡 Hint
Common Mistakes
Using + which tries to add strings and integers causing errors.
Using , which is not valid syntax for cout.
4fill in blank
hard

Fill both blanks to create a formatted output that prints a number with a width of 5 and fills empty spaces with zeros.

C++
#include <iostream>
#include <iomanip>
int main() {
    int num = 7;
    std::cout << std::setw([1]) << std::setfill([2]) << num << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
A5
B'0'
C10
D' '
Attempts:
3 left
💡 Hint
Common Mistakes
Using a space character for fill instead of zero.
Setting width to a number other than 5.
5fill in blank
hard

Fill all three blanks to print a floating-point number with width 8, precision 3, and left alignment.

C++
#include <iostream>
#include <iomanip>
int main() {
    double value = 12.34567;
    std::cout << std::[1] << std::setw([2]) << std::setprecision([3]) << value << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
Aleft
B8
C3
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using right alignment instead of left.
Mixing up width and precision values.