💻 Online C++ Compiler
Write • Compile • Run • Get Output
- Write your C++ program in the editor.
- Enter input in the I/O section if required.
- Press the green RUN ▶ button below.
- Check the output in Console.
This blog will give you best solutions to all your programming problems.
C programming is one of the most popular and powerful programming languages for beginners. It was developed by Dennis Ritchie at Bell Laboratories. C is often called a foundation programming language because many modern programming languages such as C++, Java, and others have been influenced by C.
C programming is widely used in system programming, operating systems, embedded systems, application development, and software development. Learning basic C programs helps students understand important programming concepts such as variables, data types, input and output, operators, expressions, and conditional statements.
The following is a simple Hello World program in C. It uses the printf() function to display a message on the screen.
#include <stdio.h>
int main()
{
printf("Hello, Welcome to C Programming!");
return 0;
}
Hello, Welcome to C Programming!
This C program takes two numbers as input from the user using the scanf() function and calculates their sum using the addition operator +.
#include <stdio.h>
int main()
{
int num1, num2, sum;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("Sum = %d", sum);
return 0;
}
Enter first number: 10 Enter second number: 20 Sum = 30
This program accepts three numbers from the user and calculates their average. The float data type is used to store decimal values.
#include <stdio.h>
int main()
{
float num1, num2, num3, average;
printf("Enter three numbers: ");
scanf("%f %f %f", &num1, &num2, &num3);
average = (num1 + num2 + num3) / 3;
printf("Average = %.2f", average);
return 0;
}
Enter three numbers: 10 20 30 Average = 20.00
This program performs the four basic arithmetic operations on two numbers: addition, subtraction, multiplication, and division.
#include <stdio.h>
int main()
{
float num1, num2;
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("\nAddition = %.2f", num1 + num2);
printf("\nSubtraction = %.2f", num1 - num2);
printf("\nMultiplication = %.2f", num1 * num2);
if(num2 != 0)
printf("\nDivision = %.2f", num1 / num2);
else
printf("\nDivision is not possible because divisor is zero.");
return 0;
}
Enter two numbers: 20 5 Addition = 25.00 Subtraction = 15.00 Multiplication = 100.00 Division = 4.00
This C program calculates simple interest by taking the principal amount, rate of interest, and time from the user.
#include <stdio.h>
int main()
{
float principal, rate, time, simpleInterest;
printf("Enter Principal Amount: ");
scanf("%f", &principal);
printf("Enter Rate of Interest: ");
scanf("%f", &rate);
printf("Enter Time in Years: ");
scanf("%f", &time);
simpleInterest = (principal * rate * time) / 100;
printf("Simple Interest = %.2f", simpleInterest);
return 0;
}
Enter Principal Amount: 10000 Enter Rate of Interest: 5 Enter Time in Years: 2 Simple Interest = 1000.00
This program converts temperature from Celsius to Fahrenheit.
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit = %.2f", fahrenheit);
return 0;
}
Enter temperature in Celsius: 25 Temperature in Fahrenheit = 77.00
This program finds the largest number among three numbers using the conditional operator. The conditional operator ? : is also known as the ternary operator in C programming.
condition ? expression1 : expression2;
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
printf("Maximum number = %d", max);
return 0;
}
Enter three numbers: 10 25 18 Maximum number = 25
These basic C programs are useful for beginners who are learning C programming and preparing for programming practicals, assignments, viva questions, and coding practice.
| Program No. | C Program Name |
|---|---|
| 1 | Hello World Program in C |
| 2 | Sum of Two Numbers in C |
| 3 | Average of Three Numbers in C |
| 4 | Four Arithmetic Operations in C |
| 5 | Simple Interest Program in C |
| 6 | Temperature Conversion Program in C |
| 7 | Maximum of Three Numbers Using Conditional Operator in C |
To write a C program to calculate the area of a circle.
Area of Circle = π × r × r
Where r is the radius of the circle and π = 3.14159.
#include <stdio.h>
int main()
{
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = 3.14159 * radius * radius;
printf("Area of the circle = %.2f", area);
return 0;
}
Enter the radius of the circle: 5 Area of the circle = 78.54
Enter the radius below to calculate the area of the circle:
If the radius of the circle is 5 units:
Area = π × r × r
= 3.14159 × 5 × 5
= 78.54 square units
In this C program, we will learn how to find the square root of a number without using the built-in sqrt() function. This is useful for beginners to understand how a square root can be calculated using a simple loop and approximation.
The square root of a number is a value which, when multiplied by itself, gives the original number.
Example:
The following program finds the square root approximately without using sqrt().
#include <stdio.h>
int main()
{
float num, i;
printf("Enter a number: ");
scanf("%f", &num);
i = 0;
while (i * i <= num)
{
i = i + 0.01;
}
printf("Square root of %.2f is approximately %.2f", num, i);
return 0;
}
Suppose the user enters:
Initially:
i = 0
The while loop checks whether:
i * i <= num
The value of i is gradually increased:
0.00
0.01
0.02
0.03
...
4.98
4.99
5.00
When i = 5:
5 × 5 = 25
Therefore, the square root is approximately 5.
The statement:
i = i + 0.01;
means that 0.01 is added to the current value of i each time the loop runs.
For example:
i = 0
i = 0.01
i = 0.02
i = 0.03
...
i = 4.99
i = 5.00
We can also write:
i = i + 0.1;
In this case, the value increases by 0.1 each time:
0
0.1
0.2
0.3
0.4
...
4.8
4.9
5.0
This makes the program faster because fewer iterations are required, but the answer is less precise.
| Increment | Accuracy | Speed |
|---|---|---|
| i = i + 1 | Low | Fast |
| i = i + 0.1 | About 1 decimal place | Faster |
| i = i + 0.01 | About 2 decimal places | Slower |
| i = i + 0.001 | About 3 decimal places | More iterations |
Enter a number: 25
Square root of 25.00 is approximately 5.01
The result may show 5.01 because the loop stops after the value becomes slightly greater than the actual square root.
sqrt() function is used.while loop.i * i is used to check the square of the current value.i = i + 0.01 gradually increases the value of i.
This simple C program demonstrates how a square root can be approximated without using the built-in
sqrt() function. It is a good beginner example for understanding
loops, floating-point numbers, conditions, and approximation.
In this C program, we will learn how to calculate an electricity bill based on the number of units consumed. The program uses if-else conditions to apply different rates for different ranges of electricity consumption.
An electricity bill is generally calculated according to the number of electricity units consumed. Different unit ranges may have different rates.
For this example, we will use the following rates:
| Units Consumed | Rate per Unit |
|---|---|
| 0 – 100 units | ₹5 |
| 101 – 200 units | ₹7 |
| 201 – 300 units | ₹10 |
| Above 300 units | ₹12 |
These rates are used only for learning the C programming concept. Actual electricity tariffs vary by electricity provider and consumer category.
#include <stdio.h>
int main()
{
int units;
float bill;
printf("Enter electricity units consumed: ");
scanf("%d", &units);
if (units <= 100)
{
bill = units * 5;
}
else if (units <= 200)
{
bill = (100 * 5) + ((units - 100) * 7);
}
else if (units <= 300)
{
bill = (100 * 5) + (100 * 7) + ((units - 200) * 10);
}
else
{
bill = (100 * 5) + (100 * 7) + (100 * 10)
+ ((units - 300) * 12);
}
printf("Electricity Bill = Rs. %.2f", bill);
return 0;
}
First, the program asks the user to enter the number of electricity units consumed.
Enter electricity units consumed: 250
The program then checks the number of units using if-else if-else statements.
Suppose the consumer has used 250 units.
The calculation will be:
First 100 units:
100 × ₹5 = ₹500
Next 100 units:
100 × ₹7 = ₹700
Remaining 50 units:
50 × ₹10 = ₹500
Total Bill:
₹500 + ₹700 + ₹500 = ₹1700
Enter electricity units consumed: 250
Electricity Bill = Rs. 1700.00
The first condition checks whether the units are less than or equal to 100:
if (units <= 100)
{
bill = units * 5;
}
If the units are between 101 and 200, the first 100 units are charged at ₹5 and the remaining units are charged at ₹7.
bill = (100 * 5) + ((units - 100) * 7);
Similarly, for units between 201 and 300, the program calculates the charges for the first 100 units, the next 100 units, and then the remaining units separately.
Suppose the user enters 150 units.
The first 100 units are already charged at ₹5. Therefore, only the remaining 50 units need to be charged at ₹7.
150 - 100 = 50
Therefore:
100 × ₹5 = ₹500
50 × ₹7 = ₹350
Total = ₹850
if-else if-else is used to select the appropriate slab.%.2f displays the bill with two digits after the decimal point.This C program is a useful beginner example for understanding if-else conditions, arithmetic operators, user input, and slab-based calculations. Similar logic can be used in programs for calculating water bills, telephone bills, income tax, and other charges.
In this C program, we will take a number N from the user and print all the numbers from 1 to N using a while loop.
#include <stdio.h>
int main()
{
int n, i = 1;
printf("Enter the value of n: ");
scanf("%d", &n);
while (i <= n)
{
printf("%d ", i);
i++;
}
return 0;
}
Enter the value of n: 10 1 2 3 4 5 6 7 8 9 10
| i | Condition (i <= n) | Output | i++ |
|---|---|---|---|
| 1 | 1 <= 10 → True | 1 | 2 |
| 2 | 2 <= 10 → True | 2 | 3 |
| 3 | 3 <= 10 → True | 3 | 4 |
| ... | ... | ... | ... |
| 10 | 10 <= 10 → True | 10 | 11 |
| 11 | 11 <= 10 → False | Loop stops | - |
This is a simple example of using a while loop in C. It is useful for understanding initialization, condition checking, and incrementing a loop variable.
These basic C programs help beginners understand important concepts such as input and output, variables, arithmetic operators, conditional operators, and mathematical calculations in C programming. Try changing the input values and experiment with these programs to improve your programming skills.
<!DOCTYPE html>
<html>
<head>
<title>Super Market</title>
<style>
body{
font-family: Arial;
background-color: #f2f2f2;
}
h1{
color: white;
background-color: green;
text-align: center;
padding: 10px;
}
.container{
width: 80%;
margin: auto;
}
.product{
background-color: white;
padding: 10px;
margin: 10px;
border: 1px solid gray;
}
</style>
</head>
<body>
<h1>Fresh Super Market</h1>
<div class="container">
<div class="product">
<h3>Rice</h3>
<p>Price: ₹60 per kg</p>
</div>
<div class="product">
<h3>Milk</h3>
<p>Price: ₹50 per litre</p>
</div>
<div class="product">
<h3>Bread</h3>
<p>Price: ₹30</p>
</div>
<div class="product">
<h3>Apples</h3>
<p>Price: ₹120 per kg</p>
</div>
<div class="product">
<h3>Eggs</h3>
<p>Price: ₹6 per egg</p>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Resume</title>
</head>
<body style="font-family: Arial; background-color: #f4f4f4;">
<h1 style="color: blue;">Manisha Bhardwaj</h1>
<p style="font-size:18px;">Email: manisha@email.com</p>
<p style="font-size:18px;">Phone: 9876543210</p>
<h2 style="color: green;">Career Objective</h2>
<p style="font-size:16px;">To work in a challenging environment where I can use my skills and knowledge.</p>
<h2 style="color: green;">Education</h2>
<ul style="font-size:16px;">
<li>B.Tech / MCA</li>
<li>12th from CBSE</li>
<li>10th from CBSE</li>
</ul>
<h2 style="color: green;">Skills</h2>
<ul style="font-size:16px;">
<li>HTML</li>
<li>CSS</li>
<li>Python</li>
</ul>
<h2 style="color: green;">Hobbies</h2>
<ul style="font-size:16px;">
<li>Reading</li>
<li>Music</li>
<li>Traveling</li>
</ul>
</body>
</html>
The Real-Life Question: "How can we create a dashboard that shows the current season, but makes it look like a high-tech app where the buttons glow and the boxes pop out when you touch them?"
index.html)This is the Structure. We are creating a "Container" to hold our four "Season Cards."
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Season Watcher 3000</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="main-title">Smart Home: Season Monitor</h1>
<div class="dashboard">
<div class="card" id="spring">
<div class="icon">🌸</div>
<h2>Spring</h2>
<p>Status: Blooming</p>
<button class="btn">View Garden</button>
</div>
<div class="card" id="summer">
<div class="icon">☀️</div>
<h2>Summer</h2>
<p>Status: Sunny</p>
<button class="btn">Check AC</button>
</div>
<div class="card" id="autumn">
<div class="icon">🍂</div>
<h2>Autumn</h2>
<p>Status: Windy</p>
<button class="btn">Clear Leaves</button>
</div>
<div class="card" id="winter">
<div class="icon">❄️</div>
<h2>Winter</h2>
<p>Status: Freezing</p>
<button class="btn">Heat On</button>
</div>
</div>
</body>
</html>
style.css)This is the Style. We use "Flexbox" to align the boxes and "Transitions" to make them move smoothly.
/* General Page Setup */
body {
background-color: #1a1a2e; /* Dark "Space" Blue */
color: white;
font-family: 'Segoe UI', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 50px;
}
.main-title {
margin-bottom: 40px;
text-transform: uppercase;
letter-spacing: 3px;
border-bottom: 2px solid #0f3460;
}
/* The Grid/Dashboard Layout */
.dashboard {
display: flex;
gap: 20px;
flex-wrap: wrap;
justify-content: center;
}
/* Designing the Individual Cards */
.card {
background-color: #16213e;
border: 2px solid #0f3460;
border-radius: 20px;
padding: 30px;
width: 200px;
text-align: center;
/* This makes the animation smooth! */
transition: all 0.4s ease;
}
/* Real-Life Interaction: The Hover Effect */
.card:hover {
transform: scale(1.1) rotate(2deg); /* Grows and tilts slightly */
border-color: #e94560;
box-shadow: 0px 10px 30px rgba(233, 69, 96, 0.5);
}
.icon {
font-size: 50px;
margin-bottom: 10px;
}
/* Making the Buttons Glow */
.btn {
background-color: #e94560;
color: white;
border: none;
padding: 10px 20px;
border-radius: 50px;
cursor: pointer;
font-weight: bold;
margin-top: 15px;
}
.btn:hover {
background-color: white;
color: #e94560;
}
The "Pop" (Scale): In the CSS, transform: scale(1.1) makes the card grow when you touch it with the mouse. This feels like a modern app.
The "Glow" (Box-Shadow): Using box-shadow on hover makes the card look like it’s lighting up.
Flexbox: The display: flex command in the .dashboard section acts like a magnet, pulling all the cards into a neat line automatically.
Spring is a time of rebirth. Flowers bloom and the weather turns mild.
Summer is the hottest season. It is perfect for vacations and swimming.
In Autumn, leaves change color to gold and red before falling.
Winter brings snow and ice. It is the coldest time of the year.
This project uses Linear Regression for continuous prediction and Logistic Regression for binary classification problems such as pass/fail and disease prediction.
MINOR PROJECT IDEAS
Problem:
Classify if a person has heart disease.
Inputs:
Age
BP
Cholesterol
Heart rate
Output:
Disease / No disease
Problem:
Classify if a person has heart disease.
Inputs:
Age
BP
Cholesterol
Heart rate
Output:
Disease / No disease
(Highly impressive for viva)
Predict whether a student will get placed + expected salary range.
Logistic Regression → placed / not placed
Linear Regression → expected package
CGPA trend
Coding test scores
Internship experience
Soft-skill ratings
Feature importance analysis
Probability confidence score
(Industry-oriented)
Predict:
Loan approval probability
Safe EMI amount
Logistic Regression → loan approval
Linear Regression → EMI amount
Income trend
Expenses
Credit behavior
Loan tenure
Risk tiers (Low / Medium / High)
(Engineering + Sustainability)
Forecast electricity consumption & detect over-usage risk.
Linear Regression → energy units
Logistic Regression → overload risk
Appliance usage
Seasonal effects
Household size
Monthly forecast
Warning alerts
(Engineering + AI)
Predict:
Traffic congestion level
Accident probability
Linear Regression → congestion index
Logistic Regression → accident risk
Vehicle count
Time of day
Weather
(Trending & Research-oriented)
Predict whether content is misleading.
Logistic Regression → fake / real
Linear Regression → virality score
Engagement metrics
Posting time
Account credibility
Explainable coefficients
Ethical AI discussion
(Data Science Project using Logistic Regression)
Early detection of crop diseases is critical to reduce yield loss and improve agricultural productivity.
This project aims to predict whether a crop is diseased or healthy based on environmental and crop-related parameters using Logistic Regression.
Real-world agricultural problem
Social + economic impact
Explainable ML (important for farmers)
Can be extended to yield loss prediction
Faculty-friendly & industry-relevant
Predict disease presence (Yes/No)
Analyze factors causing disease
Provide early warning
(Optional) Predict severity or yield loss
Temperature (°C)
Humidity (%)
Rainfall (mm)
Soil moisture
Soil pH
Crop type
Season
Fertilizer usage
Pesticide usage
Disease (0 = Healthy, 1 = Diseased)
📌 Datasets:
Kaggle: Crop Disease / Agriculture datasets
Government agriculture data
Synthetic dataset (acceptable for minor project)
Used because:
Output is binary
Easy to interpret coefficients
Works well with tabular data
Equation:
P(Disease)=1+e−(β0+β1x1+...+βnxn)1Predict severity level
Predict expected yield loss
Data Collection
Data Preprocessing
Feature Selection
Logistic Regression Model
Prediction
Result Visualization
Recommendation System
Load dataset
Handle missing values
Train-test split
Train Logistic Regression model
Evaluate using:
Accuracy
Confusion Matrix
Precision, Recall
Plot:
Probability curve
Feature importance
Disease prediction accuracy
Confusion matrix
Probability vs threshold graph
Feature impact analysis
Sample predictions
Image-based disease detection (CNN)
IoT sensor integration
Mobile app for farmers
Real-time weather API
Crop recommendation system
(Different from disease prediction)
Problem:
Predict crop yield before harvest.
Models:
Linear Regression → yield (tons/hectare)
Logistic Regression → low / normal yield risk
Features:
Rainfall, soil nutrients, fertilizer, season
Problem:
Predict AQI and classify health risk.
Models:
Linear Regression → AQI value
Logistic Regression → hazardous / safe
Features:
PM2.5, PM10, NO₂, SO₂, temperature
PREDITING PRICE BASES ON AREA
Predict student marks based on study hours.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Data
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) # Study hours
Y = np.array([35, 40, 50, 60, 70]) # Marks
# Model
model = LinearRegression()
model.fit(X, Y)
# Slope and intercept
m = model.coef_[0]
b = model.intercept_
# Prediction
hours = 6
predicted_marks = model.predict([[hours]])
# Plot
X_line = np.linspace(1, 6, 100).reshape(-1, 1)
Y_line = model.predict(X_line)
plt.scatter(X, Y)
plt.plot(X_line, Y_line)
plt.scatter(hours, predicted_marks)
plt.xlabel("Study Hours")
plt.ylabel("Marks")
plt.title("Linear Regression: Study Hours vs Marks")
plt.show()
# Output
print("Slope (m):", m)
print("Intercept (b):", b)
print("Equation: Y =", m, "* X +", b)
print("Predicted Marks for", hours, "hours:", predicted_marks[0])
# Logistic Regression – Example 2 (Salary Prediction)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# Dataset
data = {
'Age': [22,25,30,35,40,45,50,55],
'Experience': [0,1,3,5,7,10,15,20],
'High_Salary': [0,0,0,1,1,1,1,1]
}
df = pd.DataFrame(data)
# Features and target
X = df[['Age', 'Experience']]
y = df['High_Salary']
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1
)
# Model
model = LogisticRegression()
model.fit(X_train, y_train)
# Prediction
y_pred = model.predict(X_test)
# Results
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Intercept (β0):", model.intercept_)
print("Coefficients (β1, β2):", model.coef_)
Accuracy: 0.6666666666666666
Intercept (β0): [-13.33988536]
Coefficients (β1, β2): [[0.45410297 0.17502853]]💻 Online C++ Compiler Write • Compile • Run • Get Output How to use: ...