Decision-making expressions are essential in C and C++ programming, and numerous developers often produce ineffective code unknowingly. By employing these expressions, you can govern the program’s flow using if-else, switch, and the ternary operator. But are you utilizing the most efficient one? Misuse of nested if statements, unnecessary conditions, or mishandling of false in switch cases could impede your code’s performance. Are you committing these prevalent errors? This piece dissects decision-making expressions in C/C++, presenting syntax, examples, and optimal practices to assist you in crafting cleaner and more efficient code.
Decision-making is a vital aspect of programming. It permits the execution of distinct code blocks based on specific conditions. We implement decision-making expressions within the program to direct its flow according to logical conditions. Decision-making expressions, alternatively recognized as conditional statements, are grounded in conditions that regulate the program’s trajectory. Generally, these conditions are represented as Boolean expressions, with the code executing solely when the condition holds true; otherwise, it remains untouched.
For instance, if we aim to determine whether a number is Positive, Negative, or zero, we would utilize decision-making expressions in C/C++ for such scenarios.
Application of Decision-Making Expressions in C/C++
Here are some practical instances where conditional statements find application in C/C++:
Loop Management: Conditional statements are widely employed within loops to manage execution.
Error Handling: Conditional expressions assist in addressing errors or unforeseen conditions.
Authentication: Conditional statements are extensively utilized in authentication mechanisms to compare user inputs against stored credentials, determining whether to permit or refuse access.
Execution Flow: By utilizing decision-making expressions, we gain the ability to effortlessly govern the execution flow within a program.
Categories of Decision-Making Expressions in C/C++
C and C++ offer a variety of decision-making expressions. Let’s delve into them in detail:
if Statement
if-else Statement
if-else-if Statement
Nested if Statement
Switch Statement
Conditional (Ternary) Operator
Jump Statements in C/C++
1. if Statement in C/C++
In C and C++, the if statement serves as a primary decision-making expression that enables the program to run a block of code solely if the specified condition is accurate. It bypasses the code if the condition is false.
Syntax:
if (condition) { // Code to execute if the condition holds true }
Functioning of the if statement:
If the condition evaluates as true, then the code within the {} block executes.
If the condition evaluates as false, then the code within the {} block is omitted.
Example of an if statement in C:
C
Code Copied!
editor7366.setValue(decodedContent); // Establish the initial text
editor7366.clearSelection();
editor7366.setOptions({
maxLines: Infinity
});
function decodeHTML7366(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to transfer code to clipboard
function copyCodeToClipboard7366() {
const code = editor7366.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “c”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output7366”).html(“
"+data+"");
jQuery(".maineditor7366 .code-editor-output").show();
jQuery("#runBtn7366 i.run-code").hide();
}
})
}
function closeoutput7366() {
var code = editor7366.getSession().getValue();
jQuery(".maineditor7366 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn7366").addEventListener("click", copyCodeToClipboard7366);
document.getElementById("runBtn7366").addEventListener("click", runCode7366);
document.getElementById("closeoutputBtn7366").addEventListener("click", closeoutput7366);
Output:
In C, the if statement ascertains whether a condition is valid or not; if it is valid, it executes the code block, otherwise, it bypasses the code. It accepts input using scanf(), and through an if statement, it determines whether the number exceeds zero. If confirmed, it displays “The number is positive: using printf(). If the condition is untrue, the statement omits the blocks and advances to the next execution.
Example of an if statement in C++:
Cpp
Code Copied!
Output:
``````html
In C++, the if statement functions identically to its C counterpart, employing cin and cout for input and output. It initially evaluates the condition. If deemed true, it executes the block and displays the result. Conversely, if the condition is false, it bypasses the block and proceeds to the subsequent statement.
2. if-else Statement in C/C++
To execute a specific block of code, the if-else statement is utilized:
When the condition holds true, the program runs the first block.
When the condition is false, the first block is skipped, and the else block is executed.
Syntax:
if (condition) { // Code runs if the condition is true } else { // Code executes if the condition is false }
When the statement is true, it runs the if block.
When the statement is false, it runs the else block.
function closeoutput56033() {
var code = editor56033.getSession().getValue();
jQuery(".maineditor56033 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn56033").addEventListener("click", copyCodeToClipboard56033);
document.getElementById("runBtn56033").addEventListener("click", runCode56033);
document.getElementById("closeoutputBtn56033").addEventListener("click", closeoutput56033);
Result:
In C, the if-else statement determines whether the number is positive or negative. If the value is positive, it executes the if statement. If the value is negative, the else statement is triggered.
Sample of an if-else statement in C++:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor13423.setValue(decodedContent); // Initialize the text
editor13423.clearSelection();
editor13423.setOptions({
maxLines: Infinity
});
function decodeHTML13423(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard13423() {
const code = editor13423.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor13423 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor13423 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode13423() {
var code = editor13423.getSession().getValue();
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output13423").html("
"+data+"");
jQuery(".maineditor13423 .code-editor-output").show();
jQuery("#runBtn13423 i.run-code").hide();
}
});
}
function closeoutput13423() {
var code = editor13423.getSession().getValue();
jQuery(".maineditor13423 .code-editor-output").hide();
}
// Link event listeners to the buttons
document.getElementById("copyBtn13423").addEventListener("click", copyCodeToClipboard13423);
document.getElementById("runBtn13423").addEventListener("click", runCode13423);
document.getElementById("closeoutputBtn13423").addEventListener("click", closeoutput13423);
Output:
In C++, the if-else statement evaluates if the number is positive or negative; if the value is positive, the if statement is executed. Otherwise, the else statement is triggered. Afterward, it displays the results using cout.
3. if-else-if Statement in C/C++
Multiple conditions can be evaluated sequentially using an if-else-if statement. The initial if condition starts the evaluation. If the condition holds true, the corresponding statement runs, skipping the remaining statements. If false, it advances to the next else-if condition, continuing until a true condition is encountered. The final else block acts as the default when none of the conditions are met. This structure is effective for situations with binary outcomes, like grading systems, voting systems, etc.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the conditions are true
}
If condition1 evaluates to true, it executes the block and bypasses the others.
If it is false, it promptly checks condition2.
If no conditions are satisfied, the else block is executed by default.
Sample of an if-else-if statement in C:
C
Code Copied!
var isMobile = window.innerWidth ");
editor84892.setValue(decodedContent); // Initialize the text
editor84892.clearSelection();
editor84892.setOptions({
maxLines: Infinity
});
function decodeHTML84892(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard84892() {
const code = editor84892.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor84892 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor84892 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
data: {
language: "c",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output84892").html("
"+data+"");
jQuery(".maineditor84892 .code-editor-output").show();
jQuery("#runBtn84892 i.run-code").hide();
}
})
}
function closeoutput84892() {
var code = editor84892.getSession().getValue();
jQuery(".maineditor84892 .code-editor-output").hide();
}
// Link event listeners to the buttons
document.getElementById("copyBtn84892").addEventListener("click", copyCodeToClipboard84892);
document.getElementById("runBtn84892").addEventListener("click", runCode84892);
document.getElementById("closeoutputBtn84892").addEventListener("click", closeoutput84892);
Output:
In C, the program above employs scanf() for input and verifies the range utilizing an if-else-if structure. If the marks exceed 90, it outputs “Grade A’, if they are within 80-89 it displays “Grade B”. Should the marks drop below 60, it communicates “Grade F”. The else block functions as a fallback for scores less than 60.
Illustration of an if-else-if structure in C++:
Cpp
Code Copied!
Output:
The programs above behave similarly to C but utilize cin and cout for input and output. It adheres to the same methodology of sequential condition checking and grade printing.
4. Nested if Statement in C/C++
Nested if statement refers to an if statement within another if statement, employed for assessing several interconnected conditions. Initially, the outer if condition is evaluated, and if it proves false, the inner if is bypassed. If the outer condition is validated, the inner if condition is subsequently reviewed, and upon being true, the inner if block is executed. This approach is instrumental in scenarios like user authentication (where the username is checked first, followed by the password) or eligibility confirmation (where age verification precedes other checks).
Syntax:
if (condition1) { // Code executes if condition1 is true if (condition2) { // Code executes if both condition1 and condition2 are true
``````html
} }
Initially, it verifies condition1.
If condition1 evaluates to true, it assesses condition2.
If condition1 evaluates to false, it promptly bypasses the inner if.
Illustration of a nested-if statement in C:
C
Code Duplicated!
var isMobile = window.innerWidth ");
editor13301.setValue(decodedContent); // Set the default text
editor13301.clearSelection();
editor13301.setOptions({
maxLines: Infinity
});
function decodeHTML13301(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard13301() {
const code = editor13301.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor13301 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor13301 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error duplicating code: ", err);
});
}
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "c",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output13301").html("
"+data+"");
jQuery(".maineditor13301 .code-editor-output").show();
jQuery("#runBtn13301 i.run-code").hide();
}
})
}
function closeoutput13301() {
var code = editor13301.getSession().getValue();
jQuery(".maineditor13301 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn13301").addEventListener("click", copyCodeToClipboard13301);
document.getElementById("runBtn13301").addEventListener("click", runCode13301);
document.getElementById("closeoutputBtn13301").addEventListener("click", closeoutput13301);
Result:
Initially, the application prompts the user for input regarding both age and citizenship. In the outer ‘if’, we determine if the user is 18 years or older. Otherwise, it outputs, “You must be at least 18 years old to vote,” and exits. Within the first if, if the age condition is fulfilled, it further checks if the user is a citizen (Y or y). If confirmed, it outputs “You are eligible to vote; otherwise, it declares, “You must be a citizen to vote.”
function hideOutput72665() {
var code = editor72665.getSession().getValue();
jQuery(".maineditor72665 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn72665").addEventListener("click", copyCodeToClipboard72665);
document.getElementById("runBtn72665").addEventListener("click", executeCode72665);
document.getElementById("closeoutputBtn72665").addEventListener("click", hideOutput72665);
Result:
The C++ program uses cin and cout for input and output. Within the first if condition, if the age criteria meets, it checks whether the user is a citizen (Y or y). If true, it outputs “You are eligible to vote," otherwise it displays “You must be a citizen to vote.”
5. Switch Statement in C/C++
The switch statement assesses a value and performs the corresponding case, thus sidestepping multiple if-else constructions. In this instance, each case executes specific code, and a break is included to halt execution from proceeding to the next case. If none of the conditions match, the default block will be executed.
Structure:
switch (expression) { case value1: // Code to run if expression == value1 break; case value2: // Code to run if expression == value2 break; case value3: // Code to run if expression == value3 break; default: // Code to run if there are no matches }
The expression is assessed only when the corresponding case is executed.
The break statement prevents the flow from entering the subsequent case.
If no matches are identified, the default case is activated.
Sample of a switch statement in C:
C
Code Duplicated!
var isMobile = window.innerWidth nint main() {n char op;n double num1, num2, result;nn // Input promptn printf("Enter an operator (+, -, *, /): ");n scanf(" %c", &op);n n printf("Enter two numbers: ");n scanf("%lf %lf", &num1, &num2);nn // Switch statement handling the selected operationn switch (op) {n case '+':n result = num1 + num2;n printf("Result: %.2lfn", result);n break;n case '-':n result = num1 - num2;n printf("Result: %.2lfn", result);n break;n case '*':n result = num1 * num2;n printf("Result: %.2lfn", result);n break;n case '/':n if (num2 != 0)n printf("Result: %.2lfn", num1 / num2);n elsen printf("Error! Division by zero is not permissible.n");n break;n default:n printf("Invalid operator!n");n }nn return 0;n}nn");
editor80308.setValue(decodedContent); // Set the default text
editor80308.clearSelection();
editor80308.setOptions({
maxLines: Infinity
});
function decodeHTML80308(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Method to duplicate code to clipboard
function copyCodeToClipboard80308() {
const code = editor80308.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");
"+data+"");
jQuery(".maineditor80308 .code-editor-output").show();
jQuery("#runBtn80308 i.run-code").hide();
}
})
}
function closeoutput80308() {
var code = editor80308.getSession().getValue();
jQuery(".maineditor80308 .code-editor-output").hide();
}
// Link event handlers to the buttons
document.getElementById("copyBtn80308").addEventListener("click", copyCodeToClipboard80308);
document.getElementById("runBtn80308").addEventListener("click", executeCode80308);
document.getElementById("closeoutputBtn80308").addEventListener("click", closeoutput80308);
Result:
Based on the operator (+, -, *, /), the switch statement functions. In the default case, an error message is generated if an invalid operator is provided. For division, the program verifies that the divisor is not zero before attempting the operation to prevent errors. The break statement ensures that only the corresponding case is executed.
Example of a switch statement in C++:
Cpp
Code Duplicated!
Result:
The C++ program operated similarly to the previous one, but uses cin and cout for inputs and outputs. Depending on user input, the switch statement selects the appropriate arithmetic operation. If an invalid operator is input, the default case handles it.
6. Ternary Operator in C/C++
The ternary operator is akin to the if-else statement. It is formatted as: condition ? value_if_true : value_if_false. Based on this single line, these operators are utilized to execute different code paths, returning two values depending on whether the condition holds true or false.
function closeoutput16158() {
jQuery(".maineditor16158 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn16158").addEventListener("click", copyCodeToClipboard16158);
document.getElementById("runBtn16158").addEventListener("click", runCode16158);
document.getElementById("closeoutputBtn16158").addEventListener("click", closeoutput16158);
Outcome:
The program above accepts two numbers, utilizing the ternary operator to verify if num1 exceeds num2. If it does, num1 is allocated to max; otherwise, num2 is allocated. The largest number is printed using printf().
Illustration of a conditional statement in C++:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor18033.setValue(decodedContent); // Set the initial text
editor18033.clearSelection();
editor18033.setOptions({
maxLines: Infinity
});
function decodeHTML18033(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard18033() {
const code = editor18033.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor18033 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor18033 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
// Additional code execution function can go here...
``````javascript
jQuery(".output-tab").click();
jQuery.ajax({
url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php",
type: "post",
data: {
language: "cpp",
code: code,
cmd_line_args: "",
variablenames: "",
action: "compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
function closeoutput18033() {
var code = editor18033.getSession().getValue();
jQuery(".maineditor18033 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn18033").addEventListener("click", copyCodeToClipboard18033);
document.getElementById("runBtn18033").addEventListener("click", runCode18033);
document.getElementById("closeoutputBtn18033").addEventListener("click", closeoutput18033);
Output:
The preceding code functions identically to the earlier version; it takes two numbers using the ternary operator to evaluate if num1 surpasses num2. If it does, max is set to num1; otherwise, it defaults to num2. The largest number is then displayed using cout.
7. Jump Statements in C/C++
Jump statements are utilized to alter the execution flow within the code by transferring control from one segment to another. They allow for skipping iterations, exiting loops, or leaping to specific locations using these statements. Supported by C and C++, the jump statements include:
break: Immediately exits the nearest loop or switch statement.
continue: Skips the ongoing iteration of a loop and advances to the next one.
goto: Redirects control to a labeled statement located elsewhere in the program.
return: Terminates a function and optionally returns a value (within functions).
What is Semantic Equivalence?
Semantic equivalence signifies that two programs yield the same output or perform identical operations. This concept is particularly effective in code refactoring, optimizing code, and teaching programming principles.
The most prevalent control statements that can be exchanged are:
if-else and switch
for and while, and do-while
loop and recursion
Using if-else
The following code exemplifies the application of if-else:
Example:
Cpp
Code Copied!
var isMobile = window.innerWidth ");
editor35781.setValue(decodedContent); // Assign the default text
editor35781.clearSelection();
editor35781.setOptions({
maxLines: Infinity
});
function decodeHTML35781(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard35781() {
const code = editor35781.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor35781 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor35781 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode35781() {
var code = editor35781.getSession().getValue();
function closeoutput75062() {
var code = editor75062.getSession().getValue();
jQuery(".maineditor75062 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn75062").addEventListener("click", copyCodeToClipboard75062);
document.getElementById("runBtn75062").addEventListener("click", runCode75062);
document.getElementById("closeoutputBtn75062").addEventListener("click", closeoutput75062);
Output:
This is a script that employs a switch to determine the day and display the weekday, where day = 2 indicates Tuesday.
Summary:
In C and C++, based on the conditions, decision-making statements are crucial for guiding the flow of a program. These statements consist of if, if-else, switch, and ternary operators, which assist in executing a specific block of code in a program. Moreover, jump statements are vital when changing the execution flow. By mastering the principles of decision-making statements, developers can seamlessly implement logical expressions such as loops and error-handling. These decision-making statements improve readability and efficiency.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.