Share
Explore

Using LOGCAT

📌 Simple Kotlin Program: Loop to Add Numbers (1 to 5) and Print Sum with Logcat Debugging

This ready-to-copy-paste Android program will: ✅ Loop through numbers 1 to 5Calculate the sumPrint each step using Logcat (Log.d)Provide instructions to filter and observe Logcat output

📜 Step 1: Copy and Paste this Code in MainActivity.kt

package com.example.logcatdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

private val TAG = "SumCalculator" // Logcat TAG

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate: Activity Started")

calculateSum()
}

private fun calculateSum() {
var sum = 0
for (i in 1..5) {
sum += i
Log.d(TAG, "Loop Iteration: i = $i, Current Sum = $sum") // Log each step
}

Log.d(TAG, "Final Sum: $sum") // Log final result
}
}

📌 Step 2: Run the App in Debug Mode

1️⃣ Open Android Studio. 2️⃣ Click the "Run" ▶ Button or press Shift + F10. 3️⃣ Open Logcat:
Go to View → Tool Windows → Logcat.

📌 Step 3: Filter Logs in Logcat

To see only the logs from this program, filter by TAG:

🔍 Logcat Filter Command

In the Logcat search bar, enter:
tag:SumCalculator

OR use this to see only logs with "Sum":
tag:SumCalculator message:"Sum"

Set Log Level to "Debug" or "Verbose" (top-right dropdown in Logcat).
Now you will see the following output in Logcat:
D/SumCalculator: onCreate: Activity Started
D/SumCalculator: Loop Iteration: i = 1, Current Sum = 1
D/SumCalculator: Loop Iteration: i = 2, Current Sum = 3
D/SumCalculator: Loop Iteration: i = 3, Current Sum = 6
D/SumCalculator: Loop Iteration: i = 4, Current Sum = 10
D/SumCalculator: Loop Iteration: i = 5, Current Sum = 15
D/SumCalculator: Final Sum: 15

📌 Step 4: Observe Execution in Logcat

Each loop iteration logs the current value of i and the updated sum.
The final sum is printed at the end.
Filter by tag:SumCalculator to only see logs from this class.

🚀 Summary

Loops through numbers 1 to 5 and calculates sum. ✅ Uses Log.d(TAG, message) to track execution in Logcat. ✅ Filters Logcat output to see only relevant logs (tag:SumCalculator). ✅ Teaches debugging best practices for logging values inside loops.
Now run the app, open Logcat, filter logs, and watch the sum being calculated! 🎯🚀
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.