Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Type Conversion C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Pass By Reference C Scope C Function Declaration C Functions Challenge C Math Functions C Inline Functions C Recursion C Function Pointers

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Structs Challenge C Nested Structures C Arrays of Structs C Structs & Pointers C Unions C typedef C Struct Padding

C Enums

C Enums

C Memory

C Memory Management C Allocate Memory C Access Memory C Reallocate Memory C Deallocate Memory C Structs and Memory C Memory Example

C Errors

C Errors C Error Challenge C Debugging C NULL C Error Handling C Input Validation

C Problem Solving

C Problem Solving C Build the Logic C Edge Cases & Errors C Test Cases

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers C Command-Line Args

C DSA

C DSA Intro C Searching C Sorting C Stacks C Queues C Linked Lists C Trees C Hash Tables C Big O

C Projects

C Projects

C Cert

C Certificate

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A

C Build the Logic


Share

What is Logic?

In the previous chapter, you learned the four steps of problem solving. For many beginners, the hardest step is to plan the solution: you understand the problem, but you do not know what code to write.

The plan is called the logic of the program: the steps and decisions that turn the input into the output.

The good news: most problems are built from a few small building blocks. When you can see which blocks a problem needs, the code is much easier to write.


The Building Blocks

These blocks go through the values one by one, with a loop. The question in the problem often tells you which block you need:

Block Use it when the question is... Code inside the loop
Count "How many ...?" if (...) count++;
Sum "What is the total ...?" sum += scores[i];
Find the biggest "Which is the highest ...?" if (scores[i] > max) max = scores[i];
Search "Is there a ...?" if (scores[i] == 100) found = 1;

This example uses all four blocks on a list of test scores:

Example

#include <stdio.h>

int main() {
  int scores[] = {72, 95, 61, 88, 79};
  int length = sizeof(scores) / sizeof(scores[0]);
  int count = 0;
  int sum = 0;
  int max = scores[0];
  int found = 0;

  for (int i = 0; i < length; i++) {
    if (scores[i] >= 70) {  // Count
      count++;
    }
    sum += scores[i];       // Sum
    if (scores[i] > max) {  // Find the biggest
      max = scores[i];
    }
    if (scores[i] == 100) { // Search
      found = 1;
    }
  }

  printf("Passed: %d\n", count);
  printf("Total: %d\n", sum);
  printf("Highest: %d\n", max);
  printf("Anyone got 100? %s\n", found ? "Yes" : "No");
  return 0;
}

Result:

Passed: 4
Total: 395
Highest: 95
Anyone got 100? No
Try it Yourself »

Tip: max starts with the first score, not with 0. That way it also works when all the values are negative.


Worked Problem: Grades

Let's build the logic for a real problem. A teacher wants to turn test scores into words:

  • 90 or more: Excellent
  • 75 or more: Good
  • 50 or more: Pass
  • Less than 50: Fail

It is tempting to start with the lowest limit. But then the code gives the wrong answer for 95:

Example

if (score >= 50) {
  printf("%d: Pass\n", score);       // 95 stops here: wrong!
} else if (score >= 75) {
  printf("%d: Good\n", score);
} else if (score >= 90) {
  printf("%d: Excellent\n", score);
}

95 is more than 50, so the first condition is true, and the program never checks the other rules.

The fix: when the rules overlap, check the strictest rule first. Start with 90, then 75, then 50:

Example

#include <stdio.h>

int main() {
  int scores[] = {95, 80, 60, 30};

  for (int i = 0; i < 4; i++) {
    int score = scores[i];

    if (score >= 90) {
      printf("%d: Excellent\n", score);
    } else if (score >= 75) {
      printf("%d: Good\n", score);
    } else if (score >= 50) {
      printf("%d: Pass\n", score);
    } else {
      printf("%d: Fail\n", score);
    }
  }

  return 0;
}

Result:

95: Excellent
80: Good
60: Pass
30: Fail
Try it Yourself »

Choose a score below, and follow its path through the conditions. The last button shows what happens with the wrong order:

Follow the path

Output

Explanation



Check the Logic With a Trace Table

A trace table lets you check your logic by hand, before you run the program. Write one row for each test value, and follow the code one condition at a time.

Here is the trace table for the grades code. A dash (-) means that the condition is never checked, because an earlier condition was already true:

score >= 90? >= 75? >= 50? Result
95 yes - - Excellent
80 no yes - Good
60 no no yes Pass
30 no no no Fail

All four results are correct. Notice how the test values were chosen: one for each possible result.


Tips for Building Logic

  • Solve the problem by hand first, and notice what you do. "I look at each number" means a loop. "I remember the biggest one" means the "find the biggest" block.
  • Write the steps in plain words before you write code.
  • When the rules overlap, check the strictest rule first.
  • Use a trace table to check your logic before you run it.

Your logic may work for the values you tried. But what about unusual input? In the next chapter, you will learn how to find edge cases and logical errors.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.