Learn programming logic through C and C++
A marks calculator may look simple, but it practises the same habits you need for larger programs. You decide what information the program accepts, convert input into meaningful data, test edge cases and organise the steps so someone else can understand them. In this C and C++ programming course, console exercises make those steps visible. The example project below starts with three fixed scores, grows into a C program that accepts entries and ends with a small C++ class that groups marks and calculations.
This is a useful practice path for students after Class 12, college learners and adults comparing beginner programming courses in Ambala. Use imaginary student records throughout. The exercise uses scores between 0 and 100 and gives every subject the same weight. It makes no claim about how a school calculates official grades. If your project uses different maximum marks or weighted subjects, write out that rule before you implement it. Familiarity with folders and saving text files will help. You can practise problem tracing before you have studied any object-oriented programming.
Compile and run a program from a known folder
Save a file called hello.c and use a C compiler available in your learning environment. If you use GCC, gcc hello.c -o hello builds an executable. An IDE may run the same compiler through a button. For C++, save the exercise as hello.cpp and use a C++ compiler, such as g++ hello.cpp -o hello. Run the generated program from the correct location. On Windows it can be convenient to choose an explicit output with an .exe extension. Use the terminal's current directory or your IDE project information to confirm which source file went into the build.
The compiler translates code and reports issues it understands before a program runs. A linker combines compiled code with the symbols it needs to run. A program that builds can still print an incorrect answer. Practise separating these kinds of failures. Remove a closing parenthesis in a local copy and inspect the compiler's message. Correct it and rebuild. Next, add a calculation with a deliberate arithmetic error. This time the build should succeed, but your expected result should disagree with the output. Keep notes on the symptom and cause for each case.
Read a warning before reaching for a workaround
If the compiler warns about a mismatch between a format string and the value passed to it, identify the type of the argument and look up the corresponding format. Do not silence the message by changing a variable to a different type without understanding the calculation. A marks total can be an integer. A percentage may need a floating-point result. Review which variable represents each purpose. If you can, enable commonly used warnings in your compiler and review them after building. Use a breakpoint or temporary output for values you actually need to inspect.
Start with variables, types and known inputs
Take the scores 78, 86 and 92. Before writing code, add them by hand. The total is 256 and the average is 85.333 repeating. Record 85.33 as the expected output when printed to two decimal places. If you divide two integers in C, the division discards the fractional part. Casting after dividing 256 by 3 cannot recover the missing fractional part. Convert one operand before dividing or use a floating-point divisor. Test a total that divides evenly, such as 240 across three subjects, alongside a total that exposes the difference.
#include <stdio.h>
int main(void)
{
int total = 78 + 86 + 92;
double average = (double) total / 3;
printf("Total: %d\n", total);
printf("Average: %.2f\n", average);
return 0;
}
Print the two results with meaningful labels. Learn to connect the displayed value with the corresponding type. Variables giving names to the total and average make the calculation easier to change than repeating the expression in several print calls. For a second exercise, use three named marks and add them. Then change only one mark. If the result does not change, inspect whether a literal was left in the total calculation. Keep your example small enough to predict the output without the program.
Trace assignment and comparison
Write an if statement to show a note when a score equals 100. Use the equality operator when asking if the value matches. Assignment sets a value, so it changes program state. Create a table with expected decisions for 99, 100 and 101. The last case should be caught by validation before a note is printed. Use this exercise to describe in your own words what is evaluated, what is written and why checking the value at the boundary matters.
Turn a simple rule into conditions and tests
Define the valid range as 0 through 100 inclusive. Rehearse the boundary conditions on paper. A score is out of range if it is less than 0 or greater than 100. This phrasing makes it easier to select the correct boolean operator. Values 0 and 100 are valid. A value of minus one and a value of 101 are invalid. Design the check at the point where your program receives values so later calculations can assume that values already passed the rule.
Keep decisions separate where they answer different questions. Is this input an integer? Is that integer in the allowed range? Has the learner finished entering data? Writing one large condition for parsing, validation and interaction makes it hard to know why a test failed. A mark outside the range needs an explanation different from a line containing letters. If the user reaches end of input, the programme should exit or report that it cannot continue. It should not keep asking for input that can never arrive.
Check a threshold using exact examples
If you add a practice note that appears at an average of 75 or above, test 74.99, 75.00 and 75.01 using suitable input totals or a function that receives the calculated average. Decide whether the threshold applies to the raw value or the rounded display. Rounding 74.995 to two places may display 75.00 depending on the floating-point representation, even though the value passed into your rule can be lower than 75. For this exercise, compare the calculated average to the threshold and document the choice. Better still, for equal-weight integer marks, compare total with 75 times the subject count to avoid relying on rounded output.
Practise numeric input and reject bad entries
A small console example may use a conversion function and check its return. When building a repeatable command-line tool in C, read a line using fgets with a buffer size and convert it deliberately with strtol. You can inspect whether any digits were consumed, whether the value was within range, whether the line was complete and whether trailing characters remain. If the input line is longer than the buffer can hold, discard the remainder of that line before continuing. Test end of input as well. The goal is to keep invalid data out of the array and produce a repeatable recovery message.
Before entering 78, try a blank line, the word seventy and the value 78abc. The program should reject these while expecting an integer. A text conversion that only checks the first few characters might treat 78abc as the integer 78. Compare that to the rule you wrote for the interface. If you support trailing spaces, check that other trailing text is still rejected. Then enter a valid 0 and make sure it is accepted. Programs sometimes use zero to represent failed parsing, which incorrectly rejects a valid mark when those two concepts are mixed.
Use the debugger to compare two input cases
Pause after the parse function returns and inspect both the numeric value and the status that reports whether conversion succeeded. Compare inputs 0 and zero. For 0, the status should report a successful conversion even though the value equals zero. For zero, the status should report a failure because there are no initial digits. Then pause after the range check and compare 100 and 101. Both parse correctly, but only one meets the range rule. Keep the distinction visible in your code and explain it in your project notes.
Replace repetitive code with arrays, loops and functions
Use an array when your programme needs to keep multiple marks and revisit them for totals or reporting. Start with a fixed-size exercise using three elements. If you store values at positions 0, 1 and 2, the valid iteration condition is index less than 3. A loop that uses less than or equal to 3 accesses a fourth position. Look at the array with a debugger or trace it by hand to see how the off-by-one error occurs. A program accessing beyond the array can behave unpredictably. A normal-looking output does not prove the code is safe.
Move the total calculation into a function that receives the marks and their count. A C function receiving an array argument typically works with a pointer to the first element, so pass the count explicitly. The function below assumes the caller has supplied a valid array and the number of values it contains. Its example totals fit comfortably in an integer. If your project grows to handle very large lists, review the chosen numeric type and check limits before adding.
#include <stddef.h>
#include <stdio.h>
int total_marks(const int marks[], size_t count)
{
int total = 0;
for (size_t index = 0; index < count; index++) {
total += marks[index];
}
return total;
}
int main(void)
{
const int marks[] = {78, 86, 92};
size_t count = sizeof marks / sizeof marks[0];
printf("Total: %d\n", total_marks(marks, count));
return 0;
}
Change the example array to contain a single score and then five valid scores. Check the calculated count and result without changing the loop. In interview practice, explain why sizeof can find the full size of the fixed array at its declaration site, while a parameter received as a pointer does not carry the number of entries. Test total_marks with a count of zero through a caller that passes an appropriate pointer. It should return zero. An average calculation still needs a deliberate empty-list rule to avoid division by zero.
Organise the console project into named responsibilities
- Read a line and return whether an integer was parsed.
- Check whether the parsed number is in the accepted range.
- Add a valid mark to a fixed-size array, only while room remains.
- Calculate a total and an average from the number of marks actually stored.
- Print a readable report or a message explaining why there are no scores.
Run a case where the second entry is invalid and the person corrects it. The invalid entry should not consume an array position. Next, test a full array. The code should stop accepting entries or issue a deliberate message before any value can be written past the final position. Use the loop index in a trace table. Note when it changes and which input cases leave it unchanged.
Compare a procedural C version with a C++ class
The C version keeps the array and count together in the caller and passes them to functions. For a C++ version, use a class that keeps its marks private. Define which operations other code can call. An add operation can check the range and store the score. A query can compute the average from what has already been stored. This exercise introduces encapsulation because a caller has to use the checked operation. It also introduces a useful design question: what should the query do when no data is available?
#include <iostream>
#include <optional>
#include <vector>
class MarkBook {
public:
bool add(int score)
{
if (score < 0 || score > 100) {
return false;
}
marks_.push_back(score);
return true;
}
std::optional<double> average() const
{
if (marks_.empty()) {
return std::nullopt;
}
double total = 0;
for (int score : marks_) {
total += score;
}
return total / marks_.size();
}
private:
std::vector<int> marks_;
};
int main()
{
MarkBook book;
book.add(78);
book.add(86);
book.add(92);
if (auto result = book.average()) {
std::cout << *result << '\n';
}
}
The example uses std::optional, so compile it with C++17 support. The absence of an average is distinct from a real average of zero. Call average on an empty object and confirm the result contains no value. Then add a valid zero and confirm an average is now available. Try adding 101 and verify the false return and unchanged average. Show why the object guards its own data. If you move the valid-range check outside the class, anyone calling the object from another programme could accidentally bypass it.
Compare a fixed capacity with a growing collection
A fixed array in the C lab makes memory bounds and counting visible. The vector in the C++ version grows as you add elements. It still needs input rules. For a class project, decide whether the learner should be allowed to add unlimited records or only the subjects in a named set. If the rule limits the number, put that limit in a meaningful place and return a result that distinguishes full capacity from an invalid score. Test adding the third subject when the limit is three, followed by a fourth attempt.
Debug arithmetic, branching and state with a trace
Use paper before opening the debugger. Imagine that the valid inputs are 12, 100 and 0, with a failed entry of 101 inserted before the second valid input. Record the count and total after each attempt. The count should remain at one after 101. It should be three after the valid zero, even though the total does not increase. The final total is 112 and the average is 37.33 to two decimal places. A trace that records both count and total reveals an error hidden by only checking the total.
Now reproduce a common incorrect result. Write a lab copy in which the running total is set to zero inside the loop. The final total may become only the final score. Use a breakpoint and step over each assignment to watch the reset. Move the initialisation before the loop and repeat the same test. When documenting the fix, state exactly why the previous placement erased information. Keep your original data so you can compare the outcome before and after changing the code.
Rehearse an edge-case review
- Enter the two limit values, 0 and 100, and verify both are stored.
- Enter the nearby invalid values, minus one and 101, and verify the count and average stay unchanged.
- Submit a blank line and a mixed value. Verify the error gives another chance without consuming a score.
- Finish the input early and check how the user is told that the programme has no complete result.
- Run a one-value case and a case with several values. Check exact totals and comfortable decimal formatting.
- Build with warnings enabled. Review remaining messages and confirm they belong to the code you actually ran.
This list makes a useful code review with a friend. Ask the reviewer to choose an input you did not originally plan for. For example, they might type a line longer than the input buffer. Decide how your version should handle it before adding a fix. When the test is limited to fictional data, you can keep the cases in a public README without exposing anyone's results.
Extend the calculator with new rules
Calculate results when subjects have different maximum marks
Start with a separate set of test data. In a practice evaluation, a learner earned 46 out of 50 in one subject, 32 out of 40 in another and 18 out of 20 in a third. Add the earned marks to get 96 and the possible marks to get 110. The percentage calculated from all points is 87.27 when rounded to two places. If you calculate each subject percentage first and average those results, the answer is 87.33 repeating. These are two legitimate rules with different meanings. Decide which rule the project requests before writing code, and include both hand calculations in the test note so a reviewer can tell when a different formula is applied accidentally.
Store each earned score alongside its maximum using a struct. Reject a maximum of zero to keep the calculation meaningful. Reject any earned score above its maximum. For a test, send 18 with a maximum of 20 and check that the record is accepted. Send 21 against 20 and verify the record is rejected. Next, provide three subjects with the same maximum and show that summing the points gives the same percentage as calculating the average of their percentages. This test helps you reason about whether the two formulas agree under specific conditions.
Separate a menu command from a score
Imagine a user can choose one of three console commands. They can add a score, show the current result or exit. In the command loop, the menu selection controls which operation runs. The number typed after Add is the score and belongs to a different input stage. If both are stored in a single variable, entering a score of 3 could accidentally be confused with the Exit command. Use separate variables or keep the score in a function that reads only the new record. Try the steps Add, 3, Show, Exit and make sure the score of 3 is stored before the later explicit exit command ends the program.
Decide what Show does when the list is empty. A helpful response says there are no scores yet and gives the user a clear next action. Write out the events for a valid sequence and then for a broken sequence such as Add, wrong input, valid correction, Show. Trace which prompt should appear at each stage. Keep the menu visible when the user corrects a command value. For an invalid mark, decide whether the prompt retries that mark or returns to the menu, and keep the behaviour consistent. Document where the decision is implemented so you can change it without touching the calculation.
Inspect the value that changes across function calls
Create a practice C function that receives a count as an integer value and adds one to its local copy. Print the count before calling it and after the function returns. The caller's count stays the same. Write another version that returns the new count and assign that result at the call site. The effect is now visible. This exercise explains why a helper that is supposed to add a score needs to return the updated count or work through an explicitly provided pointer or data structure. Choose one clear approach and describe what the function would do when the array is already full.
Repeat this idea in the C++ project. Write an independent function that receives a MarkBook by value and try adding a mark inside it. Compare the original object's result with the copy's result. Observe what changes when you design a helper around a reference to an existing object. For a read-only report, use a const reference where that matches the calling contract. To demonstrate the difference, call a print function with two books containing different scores. The output should depend on the argument you pass, and the report should leave both books unchanged.
Capture completion as its own state
If the school exercise expects three results, decide whether to display a provisional average after two results. A useful version can say that two marks were entered and clearly label the average as provisional. In a strict version, wait for the final mark and show progress only. Test that a failed attempt at the third entry leaves the previous two available. When a third valid score arrives, the final average should be computed from all three and the provisional label should disappear.
Create a portfolio handoff for your console programme
Give the project a clear purpose and a minimal build command. Include one example of accepted input and its output, one error case and a short note about your toolchain. Keep the C and C++ versions in separate source files or folders so a reviewer can build each one directly. Explain how the C version passes array length and how the C++ version packages data and operations. Add a screenshot of the command and the calculated results only if it helps someone reproduce the example.
A sensible extension is to give each mark a subject label, report the maximum and handle ties. Start with a plan for representing labelled marks. In C, a struct can hold the name and score together. In C++, a struct or class can do the same. Decide whether two identical labels should be allowed. Before implementing, test a paper example in which Mathematics and Computer Science each have 95. State whether your report displays both subjects or says only that the top score is 95. A clear acceptance rule helps you demonstrate why your implementation behaves the way it does.
Interview questions on C and C++ fundamentals
How would you avoid going past the end of an array?
Use an index from zero up to, and excluding, the number of valid elements. Pass the length when the function receives a C array. When accepting data, check whether you have room before writing each element. Give an example from your trace where a valid zero still consumes one position. Explain why checking only the sum would not catch an incorrect count.
Why did your first average lose its decimal part?
Show the type of each operand. With integer operands, the division operates on integers and truncates its result. Convert an operand before dividing to use floating-point arithmetic. Use 256 and 3 so the expected 85.33 makes the effect visible. Also explain why a zero count needs a separate check before the division.
When would you make something a function or a class?
Describe a calculation with a clear input and output, such as obtaining a total from an array. A function makes that calculation easy to test and reuse. For a C++ class, describe the private marks collection and the checked add operation as logic that belongs alongside that state. A short example of an incorrectly entered score shows why the rule matters.
Questions before joining a C and C++ batch in Ambala
Do I need any previous coding or advanced maths?
The introductory work uses basic arithmetic, conditions and loops. Practise explaining a rule such as an inclusive range and write out two boundary tests. Ask which tools the batch uses and whether you can build small examples on your own computer. If you have used a calculator or spreadsheet but never a compiler, start by building and running the smallest programme and writing down the exact command.
How should I choose between C and C++ practice?
Use the course outline to discuss how the batch sequences C fundamentals and C++ classes. Both examples help you practise control flow and data. The arrays exercise makes indexing and bounds explicit, while the class exercise shows how the interface can protect its state. Ask what will be assessed in your college or other learning goal and see where the training projects overlap. Confirm class timings, current fees and the support available for repeated practice before enrolling.