• The Book of C (version 2022.08) »
  • 4. Control Structures

4. Control Structures ¶

In this chapter, we encounter the set of "control" structures in C, such as conditional statements and looping constructs. As a preview, the control structures in C are nearly identical to those found in Java (since Java syntax is heavily based on C), and bear strong resemblance to control structures found in other programming languages.

4.1. if Statement ¶

Both an if and an if-else are available in C. The <expression> can be any valid C expression. The parentheses around the expression are required, even if it is just a single variable:

You should always use curly braces around the statement block associated with an if statement. Although C allows a programmer not to include the curly braces in the case of if statements and other control structures when there is only a single statement in the statement block, you should always use the curly braces . Why, you ask, should I type those additional characters? Just ask the unfortunate engineering group at Apple that introduced the "goto fail" bug into their SSL (secure sockets layer) library: a bug that affected the macOS and iOS operating systems quite severely [ 1 ] . The upshot of this security failure is that it could have been prevented with the rigorous use of curly braces for all statement blocks.

So, for the simple form of the if statement shown above, you should really write:

As in Java, the else keyword can be used to provide alternative execution for a conditional expression. Also similar to Java, multiple if ... else if statements can be chained together. There is no elif as in Python (or elsif as in Ruby).

4.2. The conditional expression (ternary operator) ¶

The conditional expression can be used as a shorthand for some if-else statements. The general syntax of the conditional operator is:

This is an expression , not a statement , so it represents a value. The operator works by evaluating expression1 . If it is true (non-zero), it evaluates and returns expression2 . Otherwise, it evaluates and returns expression3 .

The classic example of the ternary operator is to return the smaller of two variables. Instead of writing:

you can write:

The ternary operator is viewed by some programmers as "excessively tricky" since expressions with such operators can be hard to read. Use your best judgment, and don't do something this [Horrific] example.

4.3. switch statement ¶

The switch statement is a sort of specialized form of if with the goal of efficiently separating different blocks of code based on the value of an integer. The switch expression is evaluated, and then the flow of control jumps to the matching const-expression case . The case expressions are typically int or char constants (unfortunately, you cannot use strings as case expressions). The switch statement is probably the single most syntactically awkward and error-prone feature of the C language:

Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down --- this so called fall through operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break statements are necessary to exit the switch . Omitting the break statements is a common error --- it compiles, but leads to inadvertent, unexpected, and likely erroneous fall-through behavior.

Why does the switch statement fall-through behavior work the way it does? The best explanation might be that C was originally developed for an audience of assembly language programmers. The assembly language programmers were used to the idea of a "jump table" with fall-through behavior, so that's the way C does it (it's also relatively easy to implement it this way). Unfortunately, the audience for C is now quite different, and the fall-through behavior is widely regarded as an unfortunate part of the language.

4.4. while loop ¶

The while loop evaluates the test expression before every loop, so it can execute zero times if the condition is initially false. The conditional expression requires parentheses like the if:

Although the curly braces are not technically required if there is only one statement in the body of the while loop, you should always use the curly braces. Again, see [ 1 ] for why.

4.5. do-while loop ¶

Like a while loop, but with the test condition at the bottom of the loop. The loop body will always execute at least once. The do-while tends to be an unpopular area of the language. Although many users of C use the straight while if possible, a do-while loop can be very useful in some situations:

4.6. for loop ¶

The for loop in C contains three components that are often used in looping constructs, making it a fairly convenient statement to use. The three parts are an initializer, a continuation condition, and an action, as in:

The initializer is executed once before the body of the loop is entered. The loop continues to run as long as the continuation condition remains true. After every execution of the loop, the action is executed. The following example executes 10 times by counting 0..9. Many loops look very much like the following:

C programs often have series of the form 0..(some_number-1). It's idiomatic in C for loops like the example above to start at 0 and use < in the test so the series runs up to but not equal to the upper bound. In other languages you might start at 1 and use <= in the test.

Each of the three parts of the for loop can be made up of multiple expressions separated by commas. Expressions separated by commas are executed in order, left to right, and represent the value of the last expression.

Note that in the C standard prior to C99, it was illegal to declare a variable in the initializer part of a for loop. In C99, however, it is perfectly legal. If you compile the above code using gcc without the -std=c99 flag, you will get the following error:

Once the -std=c99 flag is added, the code compiles correctly, as expected.

4.6.1. break ¶

The break statement causes execution to exit the current loop or switch statement. Stylistically speaking, break has the potential to be a bit vulgar. It is preferable to use a straight while with a single conditional expression at the top if possible, but sometimes you are forced to use a break because the test can occur only somewhere in the midst of the statements in the loop body. To keep the code readable, be sure to make the break obvious --- forgetting to account for the action of a break is a traditional source of bugs in loop behavior:

The break does not work with if ; it only works in loops and switches. Thinking that a break refers to an if when it really refers to the enclosing while has created some high-quality bugs. When using a break , it is nice to write the enclosing loop to iterate in the most straightforward, obvious, normal way, and then use the break to explicitly catch the exceptional, weird cases.

4.6.2. continue ¶

The continue statement causes control to jump to the bottom of the loop, effectively skipping over any code below the continue . As with break , this has a reputation as being vulgar, so use it sparingly. You can almost always get the effect more clearly using an if inside your loop:

4.6.3. Statement labels and goto ¶

Continuing the theme of statements that have a tendency of being a bit vulgar, we come to the king of vulgarity, the infamous goto statement [Goto] . The structure of a goto statement in C is to unconditionally jump to a statement label, and continue execution from there. The basic structure is:

The goto statement is not uncommon to encounter in operating systems code when there is a legitimate need to handle complex errors that can happen. A pattern that you might see is something like:

Notice the structure above: there are multiple steps being performed to carry out some initialization for an operation [ 2 ] . If one of those initialization operations fails, code execution transfers to a statement to handle deinitialization , and those de-init operations happen in reverse order of initialization . It is possible to rewrite the above code to use if / else structures, but the structure becomes much more complex (see an exercise below). Although goto has the reputation of leading to "spaghetti code", judicious use of this statement in situations like the above makes for cleaner and clearer code.

Rewrite the goto example code above (the last code example, above) to use if / else instead. Which code do you think exhibits a more clear structure?

Consider the following program snippet:

What is printed if the number 3 is entered?

Say that you want to write a program that repeatedly asks for a snowfall amount, and that you want to keep asking for another value until the sum of all values exceeds a certain value. What control structure would work best to facilitate entry of the snowfall values, and why?

Say you want to write a program that computes the average of quiz scores. You have a big stack of quizzes, so you do not know the number of quizzes up front. What control structure would work best to facilitate entry of the scores, and why?

Say that you want to simulate rolling a die (singular of dice) a fixed number of times and to compute and print the average value for the die rolls. What control structure would work best for this problem, and why?

http://thedailywtf.com/articles/One-Bad-Ternary-Operator-Deserves-Another

Dijkstra. Letters to the editor: go to statement considered harmful. Communications of the ACM, Volume 11, Issue 3, March 1968. https://dl.acm.org/citation.cfm?id=362947

Table of Contents

  • 4.1. if Statement
  • 4.2. The conditional expression (ternary operator)
  • 4.3. switch statement
  • 4.4. while loop
  • 4.5. do-while loop
  • 4.6.1. break
  • 4.6.2. continue
  • 4.6.3. Statement labels and goto

Previous topic

3. Basic Types and Operators

5. Arrays and Strings

Quick search

Got issues.

If you find a bug or have a suggestion for improvement, please report it .

C/C++ Primer - Home

C/C++ Control Structures

C/c++ control structures #.

Control structures are what differentiate a computer program from a calculator, and allow us to repeat or avoid sections of code depending on the logical operation of the program. Many of the fundamental details are very similar to Python, and generally sections will translate fairly easily, although not perfectly, between the two languages.

For loops #

Probably the most common type of loop in C/C++ (particularly in numerical codes and scientific computation) is the for loop. While this has a different syntax than Python, the core idea is the same. A very basic loop might look like

You’ll note that the actual for clause is split into three statements (separated by ; tokens).

The first statement initializes our counting mechanism, e.g. (as in this case, int i=0 ) declaring a counter variable and pointing it to its first value. In theory we could do multiple things in here (e.g. reset multiple existing variables, just call a function etc.) but in practice we’re likely just to set up one counting variable.

The second statement sets the termination or halting criterion. The for loop statement will executive each time as long as the statement here (in our case i<10 ) evaluates true. As soon as that is no longer the case, the loop stops and execution carries on down the function.

The third statement (in this case i++ ) specifies increment or decrement for the loop, and is applied each time that the loop is gone around. We use the ++ increment operator (which does the same thing as i=i+1 ) so our loop will runs 10 times, with i taking the values 0 to 9. If we used a different statement (e.g. i+=2 ) we could change the effective “stride” of the loop.

While loops #

As with Python, C++ has while loops which just test a termination statement, and continues to execute the loop block so long as it is true. As an example, lets write the Newton Raphson square root finder in Python and C++:

A form of logic Python doesn’t have is the do ... while loop. This again tests a statement to decide whether to continue execution, but the test now comes after the loop block, which is thus guaranteed to execute once. This can be useful if the block initialises something which should then be checked:

Break continue and exit #

The break and continue statements are used inside loops to skip either all remaining iterations (for break ) or the next iteration (for continue ). These statements behave just like their Python equivalents, in that they only apply to the innermost loop of the function currently being executed, and can’t be used outside of a loop structure. To quit the entire program at once, you should use the exit(1) function, supplying an integer return value (remember, a zero return value is usually taken to mean things went ok, and an other value that something went )

Conditionals #

If, else if, and else #.

As with Python, C-like languages use if statements to conditionally process blocks of code. However, the C syntax is once again a little different.

Where a PEP8 compliant Python conditional might look like

a C++ equivalent main program might look like

The key differences are:

The () brackets are required around the expression being tested.

There is no elif keyword, instead we use else if .

Note that the {} brackets are only strictly necessary if there is more than one statement in the conditional statement block. We could always choose to write:

However, the version with brackets is more explicit and makes it harder to get confused about which statements are actually conditional.

The switch statement #

A form of condition which was only recently introduced in Python is the match statement, which corresponds to the C++ switch statement. In C++ these start with switch ( expression ) and then have a block in following the form:

In the above example, the code will choose which functions to call depending on if my_label is 1,2,3 or something else. Note that without the break statements execution will “fall through” from case statement blocks at the top down to the ones at the bottom, which in this example would mean my_cool_function_one and my_cool_function_two being called twice. This is slightly different to the Python match statement, which will only execute the first matching case.

We’ve now had a brief look at many of the ways you can control the logical flow of a C++ program, and seen that many of them are similar to the patterns you know from Python. In the next section we will take a deeper look at functions specifically, including their syntax, how to call them, and ways they are used.

Browse Course Material

Course info, instructors.

  • Kyle Murray

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Introduction to c and c++, core c: control structures, variables, scope, and uninitialized memory, lecture notes.

Lecture 2: Core C (PDF)

Lab Exercises

The primary goal of this lab period is to make sure you know all of the basics of writing code in C and to avoid common pitfalls unique to C and C++.

Starting with an empty .c file, write a C program to calculate the first 100 triangular numbers (0, 1, 3, 6, 10, 15, 21, …). You may check back at previous example code and slides if you get stuck, but take this an opportunity to try to recall, from memory, the standard boilerplate code you’ll be writing often when starting a new C program, like the proper #include statements to be able to print to the console.

Find and fix the variable shadowing bug in the following C program, which is intended to calculate the factorial function:

Assignment 2

Rewrite the program below, replacing the for loop with a combination of goto and if statements. The output of the program should stay the same. That is, the program should print out the arguments passed to it on the command line.

If you ran the program like this: ./prog one two three , it would print

In lecture, we covered a variety of control structures for looping, such as for , while , do/while , goto , and several for testing conditions, such as if and switch .

Your task is to find seven different ways to print the odd numbers between 0 and 10 on a single line. You should give them names like amaze1 , amaze2 , etc. Here’s a bonus amaze (that you can use as one of your seven if you like):

You may need to get a little creative!

Put all of your functions in the same C file and call them in order from the main() function. We should be able to compile your program with this command and see no errors:

gcc -Wall -std=c99 -o amaze amaze.c

Solutions are not available for this assignment.

facebook

Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

  • Deep Learning

CONTROL STRUCTURES IN C

assignment in control structure in c

Control Structures specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is  true and optionally, other statements to be executed if the condition is false.

See blow image to  understand control (Decision making ) structure:-

assignment in control structure in c

C programming language assumes any zero and null values as false , and if it is either non-zero or non-null , then it is assumed as true value.

C programming language provides the following types of decision making statements.

Table of Contents

If Statement OR If-else Statements:

Both an ‘if’ and ‘if-else’ are available in C. The <expression> can be any valid expression. The parentheses around the expression are not required, if it is just a single expression.

Conditional Expression -or- The Ternary Operator:

The conditional expression can be used as a shorthand for some if-else statement. The general syntax of the conditional operator is:

<expression1> ? <expression2> : <expression3>

Switch Statement:

The switch statement is a sort of specialized form of if used to efficiently separate different block of code based on the value of an integer. The case expressions are typically ‘int’ or ‘char’ constants, The switch statement is probably the single most syntactically awkward and error-prone features of the C language.

switch (<expression>) { case <const-expression-1>: <statement> break; case <const-expression-2>: <statement>  break; case <const-expression-3>: // here we combine case 3 and 4 case <const-expression-4>: <statement> break; default:                      // optional <statement> Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down— this so called “fall through” operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break  statements are necessary to exit the switch.

Pradeep Maurya

Pradeep Maurya is the Professional Web Developer & Designer and the Founder of   “Tutorials website” . He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like  Dzone ,  e27.co

Related posts

Best Ecommerce Platforms of 2024

6 Best Ecommerce Platforms of 2024

Google is preparing to rebrand Bard as Gemini

Google is preparing to rebrand Bard as Gemini

Data Scientist vs Full Stack Developer

Data Scientist vs Full Stack Developer: Which You Should Choose

Privacy overview.

Electronic Circuits and Diagrams-Electronic Projects and Design

Control structures and statements in C and C++

Control structures form the basic entities of a “ structured programming language “. We all know languages like C/C++ or Java are all structured programming languages. Control structures are used to alter the flow of execution of the program.  Why do we need to alter the program flow ? The reason is “ decision making “! In life, we may be given with a set of option like doing “Electronics” or “Computer science”. We do make a decision by analyzing certain conditions (like our personal interest, scope of job opportunities etc). With the decision we make, we alter the flow of our life’s direction. This is exactly what happens in a C/C++ program. We use control structures to make decisions and alter the direction of program flow in one or the other path(s) available.

There are three types of control structures available in C and C++

1) Sequence structure (straight line paths)

2) Selection structure (one or many branches)

3)Loop structure (repetition of a set of activities)

All the 3 control structures and its flow of execution is represented in the flow charts given below.

assignment in control structure in c

Control statements in C/C++ to implement control structures

We have to keep in mind one important fact:- all program processes can be implemented with these 3 control structures only. That’s why I wrote “ control structures are the basic entities of a structured programming language “. To  implements these “control structures” in a C/C++ program, the language provides ‘control statements’.  So to implement a particular control structure in a programming language, we need to learn how to use the relevant control statements in that particular language.

The control statements are:-

As shown in the flow charts:-

  • Selection structures are implemented using If , If Else and Switch statements.
  • Looping structures are implemented using While , Do While and For statements.  

Selection structures 

flow chart of If, If else and switch statements.

The simple If statement

if (expression) // This expression is evaluated. If expression is TRUE statements inside the braces will be executed { statement 1; statement 2; } statement 1;// Program control is transfered directly to this line, if the expression is FALSE statement 2;

Example program to demo “If” statement

A simple example program to demo the use of If, If Else and Switch is shown here. An integer value is collected from user. If the integer entered by user is 1 – output on screen “UNITED STATES”. If the integer is 2 – output “SPAIN”, If the integer is 3 output “INDIA”. If the user enters some other value – output “WRONG ENTRY”.

Note:- The same problem is used to develop example programs for “if else” and “switch ” statements

#include void main() { int num; printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user if(num==1) { printf("UNITED STATES"); } if(num==2) { printf("SPAIN"); } if(num==3) { printf("INDIA"); } }

The If Else statement.

if(expression 1)// Expression 1 is evaluated. If TRUE, statements inside the curly braces are executed. { //If FALSE program control is transferred to immedate else if statement.

statement 1; statement 2; } else if(expression 2)// If expression 1 is FALSE, expression 2 is evaluated. { statement 1; statement 2; } else if(expression 3) // If expression 2 is FALSE, expression 3 is evaluated { statement 1; statement 2; } else // If all expressions (1, 2 and 3) are FALSE, the statements that follow this else (inside curly braces) is executed. { statement 1; statement 2; } other statements;

Example program to demo “If Else”

#include void main() { int num; printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user if(num==1) { printf("UNITED STATES"); } else if(num==2) { printf("SPAIN"); } else if(num==3) { printf("INDIA"); } else { printf("WRONG ENTRY"); // See how else is used to output "WRONG ENTRY" } }

Note:- Notice how the use of If Else statements made program writing easier. Compare this with above program using simple If statement only.

Switch statement

switch(expression)// Expression is evaluated. The outcome of the expression should be an integer or a character constant { case value1: // case is the keyword used to match the integer/character constant from expression. //value1, value2 ... are different possible values that can come in expression statement 1; statement 2; break; // break is a keyword used to break the program control from switch block. case value2: statement 1; statement 2; break; default: // default is a keyword used to execute a set of statements inside switch, if no case values match the expression value. statement 1; statement 2; break; }

Example program to demo working of “switch” 

#include void main() { int num; printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user switch(num) { case 1: printf("UNITED STATES"); break; case 2: printf("SPAIN"); break; case 3: printf("INDIA"); default: printf("WRONG ENTRY"); } }

Note:- Switch statement is used for multiple branching. The same can be implemented using nested “If Else” statements. But use of nested if else statements make program writing tedious and complex. Switch makes it much easier. Compare this program with above one.

Loop structures

 flow charts of while, do while and for loops in c/c++ and Java

The while statement

Syntax for while loop is shown below:

while(condition)// This condition is tested for TRUE or FALSE. Statements inside curly braces are executed as long as condition is TRUE { statement 1; statement 2; statement 3; }

The condition is checked for TRUE first. If it is TRUE then all statements inside curly braces are executed.Then program control comes back to check the condition has changed or to check if it is still TRUE. The statements inside braces are executed repeatedly, as long as  the condition is TRUE. When the condition turns FALSE, program control exits from while loop.

Note:- while is an entry controlled loop. Statement inside braces are allowed to execute only if condition inside while is TRUE.

Example program to demo working of “while loop”

An example program to collect a number from user and then print all numbers from zero to that particular collected number is shown below. That is, if user enters 10 as input, then numbers from 0 to 10 will be printed on screen.

Note:- The same problem is used to develop programs for do while and for loops

#include void main() { int num; int count=0; // count is initialized as zero to start printing from zero. printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user while(count<=num) // Checks the condition - if value of count has reached value of num or not. { printf("%d",count); count=count+1; // value of count is incremented by 1 to print next number. } }

The do while statement

Syntax for do while loop is shown below:

do { statement 1; statement 2; statement 3; } while(condition);

Unlike while, do while is an exit controlled loop. Here the set of statements inside braces are executed first. The condition inside while is checked only after finishing the first time execution of statements inside braces. If the condition is TRUE, then statements are executed again. This process continues as long as condition is TRUE. Program control exits the loop once the condition turns FALSE.

Example program to demo working of "do while"

#include void main() { int num; int count=0; // count is initialized as zero to start printing from zero. printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user do { printf("%d",count); // Here value of count is printed for one time intially and then only condition is checked. count=count+1; // value of count is incremented by 1 to print next number. }while(count<=num); }

The for statement

Syntax of for statement is shown below:

for(initialization statements;test condition;iteration statements) { statement 1; statement 2; statement 3; }

The for statement is an entry controlled loop. The difference between while and for is in the number of repetitions. The for loop is used when an action is to be executed for a predefined number of times. The while loop is used when the number of repetitions is not predefined.

Working of for loop:

The program control enters the for loop. At first it execute the statements given as initialization statements. Then the condition statement is evaluated. If conditions are TRUE, then the block of statements inside curly braces is executed. After executing curly brace statements fully, the control moves to the "iteration" statements. After executing iteration statements, control comes back to condition statements. Condition statements are evaluated again for TRUE or FALSE. If TRUE the curly brace statements are executed. This process continues until the condition turns FALSE.

Note 1:- The statements given as " initialization statements " are executed only once, at the beginning of a for loop. Note 2: There are 3 statements given to a for loop as shown. One for initialization purpose, other for condition testing and last one for iterating the loop. Each of these 3 statements are separated by semicolons.

Example program to demo working of  "for loop"

#include void main() { int num,count; printf("Hello user, Enter a number"); scanf("%d",&num); // Collects the number from user for(count=0;count<=num;count++)// count is initialized to zero inside for statement. The condition is checked and statements are executed. { printf("%d",count); // Values from 0 are printed. } }

So that is all about " control statements " in C/C++ language. If you have any doubts ask in comments section.

Related Posts

Quick sorting algorithm with example code in c/c++/java languages, insertion sorting algorithm with example in c/c++/java languages, selection sort in c/c++/java programming languages.

hello. can anyone help me with my project. i am failed to aprove my idea. can anyone give me any idea for my FYP. 🙁

Could anyone please explain this program to me?

/*SORTING OF NUMBERS IN ASCENDING ORDER*/

#include #include { int a[20],i,j,temp,n; printf(“\n Enter the Number of Elements: \n”); scanf(“%d”,&n); printf(“\n Enter the Values: \n”); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { for(j=i+1;ja[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf(“\n The Sorted Values are: \n”); for(i=0;i<n;i++) printf("%d,\n",a[i]); getch(); }

Hello, I am a student. I have project about electronic lock by using microcontroller c language. Could you please help me with my project. Regards, Hussain

Hello Hussain,

Drop me an email to [email protected]

statements solve kaisy karty hai ye help kar dy ap meri .10 INPUT”AGE”;A 20 IF A>=17 THEN 30 ELSE 50 30 PRINT ”Candidate is eligible” 40 GO TO 60 50 PRINT”Candidate is not eligible” 60 INPUT”world you like to input again (Y/N)”;Y$ 70 IF Y$ = ”Y” THEN 10 80 END

can i get a simple of c plus plus?

good stuff guys, you are leading me somewhere for my projects

Thanks musa. We will be coming with more articles. Keep looking.

Type above and press Enter to search. Press Esc to cancel.

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • Solve Coding Problems
  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators
  • Assignment Operators in C
  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

C structures.

  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type.

C Structure Declaration

We have to declare structure in C before using it in our program. In structure declaration, we specify its member variables along with their datatype. We can use the struct keyword to declare the structure in C using the following syntax:

The above syntax is also called a structure template or structure prototype and no memory is allocated to the structure in the declaration.

C Structure Definition

To use structure in our program, we have to define its instance. We can do that by creating variables of the structure type. We can define structure variables using two methods:

1. Structure Variable Declaration with Structure Template

2. structure variable declaration after structure template, access structure members.

We can access structure members by using the ( . ) dot operator.

In the case where we have a pointer to the structure, we can also use the arrow operator to access the members.

Initialize Structure Members

Structure members cannot be initialized with the declaration. For example, the following C program fails in the compilation.

The reason for the above error is simple. When a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.

We can initialize structure members in 3 ways which are as follows:

  • Using Assignment Operator.
  • Using Initializer List.
  • Using Designated Initializer List.

1. Initialization using Assignment Operator

2. initialization using initializer list.

In this type of initialization, the values are assigned in sequential order as they are declared in the structure template.

3. Initialization using Designated Initializer List

Designated Initialization allows structure members to be initialized in any order. This feature has been added in the C99 standard .

The Designated Initialization is only supported in C but not in C++.

Example of Structure in C

The following C program shows how to use structures

typedef for Structures

The typedef keyword is used to define an alias for the already existing datatype. In structures, we have to use the struct keyword along with the structure name to define the variables. Sometimes, this increases the length and complexity of the code. We can use the typedef to define some new shorter name for the structure.

Nested Structures

C language allows us to insert one structure into another as a member. This process is called nesting and such structures are called nested structures . There are two ways in which we can nest one structure into another:

1. Embedded Structure Nesting

In this method, the structure being nested is also declared inside the parent structure.

2. Separate Structure Nesting

In this method, two structures are declared separately and then the member structure is nested inside the parent structure.

One thing to note here is that the declaration of the structure should always be present before its definition as a structure member. For example, the declaration below is invalid as the struct mem is not defined when it is declared inside the parent structure.

Accessing Nested Members

We can access nested Members by using the same ( . ) dot operator two times as shown:

Example of Structure Nesting

Structure pointer in c.

We can define a pointer that points to the structure like any other variable. Such pointers are generally called Structure Pointers . We can access the members of the structure pointed by the structure pointer using the ( -> ) arrow operator.

Example of Structure Pointer

Self-referential structures.

The self-referential structures in C are those structures that contain references to the same type as themselves i.e. they contain a member of the type pointer pointing to the same structure type.

Example of Self-Referential Structures

Such kinds of structures are used in different data structures such as to define the nodes of linked lists, trees, etc.

C Structure Padding and Packing

Technically, the size of the structure in C should be the sum of the sizes of its members. But it may not be true for most cases. The reason for this is Structure Padding.

Structure padding is the concept of adding multiple empty bytes in the structure to naturally align the data members in the memory. It is done to minimize the CPU read cycles to retrieve different data members in the structure.

There are some situations where we need to pack the structure tightly by removing the empty bytes. In such cases, we use Structure Packing. C language provides two ways for structure packing:

  • Using #pragma pack(1)
  • Using __attribute((packed))__

Example of Structure Padding and Packing

As we can see, the size of the structure is varied when structure packing is performed.

To know more about structure padding and packing, refer to this article – Structure Member Alignment, Padding and Data Packing .

Bit Fields are used to specify the length of the structure members in bits. When we know the maximum length of the member, we can use bit fields to specify the size and reduce memory consumption.

Syntax of Bit Fields

 example of bit fields.

As we can see, the size of the structure is reduced when using the bit field to define the max size of the member ‘a’.

Uses of Structure in C

C structures are used for the following:

  • The structure can be used to define the custom data types that can be used to create some complex data types such as dates, time, complex numbers, etc. which are not present in the language.
  • It can also be used in data organization where a large amount of data can be stored in different fields.
  • Structures are used to create data structures such as trees, linked lists, etc.
  • They can also be used for returning multiple values from a function.

Limitations of C Structures

In C language, structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures also have some limitations.

  • Higher Memory Consumption: It is due to structure padding.
  • No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the structure.
  • Functions inside Structure: C structures do not permit functions inside the structure so we cannot provide the associated functions.
  • Static Members: C Structure cannot have static members inside its body.
  • Construction creation in Structure: Structures in C cannot have a constructor inside Structures.

Related Articles

  • C Structures vs C++ Structure

Please Login to comment...

  • C-Structure & Union
  • shubham_singh
  • RishabhPrabhu
  • RajeetGoyal
  • SidharthSunil
  • sagartomar9927
  • vishalyadav3
  • shikharg1110
  • abhishekcpp
  • snehalsalokhe
  • How to Make Faceless Snapchat Shows Earning $1,000/Day
  • Zepto Pass Hits 1 Million Subscribers in Just One Week
  • China’s "AI Plus": An Initiative To Transform Industries
  • Top 10 Free Apps for Chatting
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Logo

  • PG Diploma in Embedded Systems Design & Development
  • PG Diploma in Internet of Things (IoT)
  • Full Stack Java With Placements
  • Professional Diploma in Software Programming
  • PG Diploma in Data Science – Coming Soon
  • Diploma Programs- Working Professionals
  • Programming in C
  • MATLAB & Simulink
  • Internet of Things – IoT
  • Artificial Intelligence
  • Machine Learning
  • Embedded System
  • Automotive Embedded System
  • Basic Electronics
  • College Workshop
  • Internship Program
  • Faculty Development Program (FDP)
  • Placement Prepardness Program (PPP)
  • Summer Training Programs (STP)
  • Academic Projects
  • R&D Lab Setup
  • Corporate Training

logo

Recruiters Area

  • Entrance Test
  • Student Login

Control Structures 101: A Fundamentals Guide for C Programming

Control Structures 101: Fundamentals Guide for C Programming - IIES

Introduction

Control structures are programming constructs that enable developers to have control over the flow of a program. They determine the execution order of statements based on certain conditions. By using control structures, programmers can make decisions, repeat actions, and alter the flow of their code. Control structures are essential in programming as they allow for dynamic and efficient program execution. Control structures play a crucial role in directing the flow of a program. They facilitate branching and looping, allowing developers to execute specific code blocks based on conditions or to repeat a certain block of code multiple times. Control structures help in implementing decision-making, iteration, and execution control, which are fundamental to writing efficient and effective programs.

In C programming , there are several common control structures that are used extensively. These include conditional statements like the “if” statement and the “switch” statement, as well as looping structures like the “while” loop, the “for” loop, and the “do-while” loop. These control structures provide flexibility and allow developers to write code that can adapt to various scenarios and conditions.

Conditional Statements: Making Decisions in C

The “if” statement.

The “if” statement is one of the most basic and commonly used conditional statements in C programming. It enables the execution of a certain block of code based on a specified condition. The syntax of the “if” statement is straightforward, and it can be used to handle single as well as multiple conditions. Additionally, “if” statements can be nested, allowing for complex decision-making in programs.

The “else” Statement

The “else” statement is used in conjunction with the “if” statement to specify an alternative block of code to be executed when the condition in the “if” statement evaluates to false. By combining the “if” and “else” statements, developers can create decision-making structures that offer multiple paths of execution based on different conditions.

The “switch” Statement

The “switch” statement allows for multiple branches of execution based on the value of a variable. It provides an alternative to multiple consecutive “if” statements and offers a concise way to handle different cases. The “switch” statement compares the value of the variable against various “case” labels and executes the corresponding block of code. It also provides a way to handle default cases when none of the specified cases match.

Looping Structures: Repetition Made Easy

 the “while” loop.

The “while” loop is used when a certain block of code needs to be repeated as long as a specified condition is true. It is ideal for situations where the number of iterations is not known beforehand. The syntax of the “while” loop is straightforward, and it allows developers to control the entry and exit conditions of the loop based on the value of the condition.

The “for” Loop

The “for” loop is a versatile looping structure that allows developers to define the initialization, condition, and iteration all within a single line. It is often used when the number of iterations is known or when iterating over a collection of elements. The “for” loop provides more control over the loop structure and also allows for loop optimization and best practices.

The “do-while” Loop

The “do-while” loop is similar to the “while” loop, but it guarantees that the loop code block is executed at least once before checking the condition. This can be useful in situations where the loop code block needs to be executed regardless of the initial condition. The “do-while” loop structure ensures that the loop body is executed first before evaluating the condition.

Breaking and Continuing Loop Execution

In C programming, the “break” and “continue” statements are used to alter the execution flow within loop structures . The “break” statement is used to exit the current loop and move on to the next section of code outside the loop. This can be useful to terminate a loop prematurely based on a certain condition. On the other hand, the “continue” statement allows programmers to skip the remaining code within a loop and move to the next iteration.

Jump Statements: Altering Control Flow

 “goto” statement.

The “goto” statement is a powerful but controversial feature in C programming. It allows programmers to transfer control to a labeled statement within the same function. While the “goto” statement can simplify code flow in certain situations, it can also lead to difficult-to-maintain code and increase the risk of introducing bugs. It is generally recommended to use other control structures like loops and conditional statements instead of the “goto” statement.

“return” Statement

The “return” statement is used to exit a function and return a value to the caller. It plays a vital role in controlling the flow of a program and terminating functions when necessary. Returning values from functions allows developers to pass data back to the caller or to indicate the success or failure of a function. Understanding how to use the “return” statement correctly is essential for proper program execution.

“break” and “continue” Revisited

In addition to their usage in loops, the “break” and “continue” statements can also be used in nested loops. When used within nested loops, the “break” statement terminates the innermost loop and resumes execution from the first statement outside the loop. The “continue” statement, on the other hand, skips the remaining code for the current iteration of the innermost loop and moves to the next iteration.

Practical Examples: Applying Control Structures

Example 1: simple calculator.

In this example, we will design a program to create a simple calculator using control structures in C. We will utilize conditional statements to handle menu selection and perform various mathematical operations based on user input. By using control structures effectively, we can create a user-friendly calculator program with clear menu options and accurate calculations.

Example 2: Looping for Pattern Printing

In this example, we will explore how control structures can be used to create different patterns using nested loops. We will design a program that takes user input to determine the number of rows and columns for a pattern and then use nested looping structures to print the desired pattern. By utilizing “for” and “while” loops together, we can dynamically generate patterns of various shapes and sizes.

Example 3: Checking Prime Numbers

In this example, we will create a program that checks whether a given number is prime or not using control structures in C . We will utilize loop structures and conditional statements to implement an algorithm for verifying prime numbers. By carefully selecting the appropriate control structures and utilizing conditional statements, we can efficiently determine whether a number is prime or composite.

Best Practices for Using Control Structures

Readability and code formatting.

When utilizing control structures, it is essential to ensure code readability. Proper indentation, clear naming conventions, and consistent code formatting help improve the readability of the codebase. By following best practices for code formatting, developers can make their control structures more understandable and maintainable.

Avoiding Nested Loops and Complex Control Structures

While nested loops can be useful, excessive nesting can make the code difficult to understand and debug. It is generally recommended to avoid overly complex control structures and nested loops whenever possible. Simplifying control flow by breaking down complex structures into individual functions or utilizing helper variables can make the code more manageable and maintainable.

Comments and Documentation

Adding comments and documentation to control structures is crucial for future reference and collaboration. It helps other developers understand the intent and purpose of the control structures. By providing clear and concise comments, developers can improve code comprehension and enhance the overall maintainability of the project.

Testing and Debugging Control Flow

Thoroughly testing and debugging control structures is essential to ensure their proper functioning. By systematically designing test cases that cover all possible scenarios, developers can verify the correctness of their control structures. Additionally, using proper debugging techniques and tools can help in discovering and fixing any issues related to control flow.

Advanced Control Structures (Brief Overview)

“if-else if-else” ladder.

The “if-else if-else” ladder is an extension of the “if-else” statement that allows developers to check multiple conditions in a sequence. Each condition is evaluated in order, and the corresponding block of code is executed if the condition is true. This control structure is ideal when there are multiple mutually exclusive conditions to be checked.

Nested “switch” Statements

The “switch” statement can also be nested within another “switch” statement, allowing for more complex decision-making. By nesting “switch” statements, developers can handle multiple levels of cases and further refine the execution flow based on various conditions.

Multi-level Looping

Multi-level looping refers to the usage of nested loops with different termination conditions. This allows developers to iterate over multiple dimensions or nested data structures. By using multi-level looping, complex patterns or operations involving multiple dimensions can be easily implemented.

In this blog post, we discussed the fundamentals of control structures in C programming . We explored conditional statements like the “if” statement and the “switch” statement, as well as looping structures like the “while” loop, the “for” loop, and the “do-while” loop. We also delved into jump statements like the “goto” statement and the “return” statement. Additionally, we provided practical examples of applying control structures in C programming .

Mastering control structures is essential for any C programmer. Control structures allow for dynamic program flow, decision-making, and repetition. By understanding and effectively utilizing control structures, developers can create efficient and flexible programs that fulfill specific requirements. Understanding control structures is a fundamental aspect of learning C programming. To enhance your C programming skills further, consider exploring topics like data types, functions, arrays, and pointers. Additionally, practicing coding exercises and participating in programming projects can help solidify your understanding of control structures and improve your overall programming proficiency.

Must Read: Understanding and Utilizing Pointers in C Programming

Indian Institute of Embedded Systems – IIES​

Admission  

Privacy Policy

Certification Courses

  • PG Diploma in Embedded Systems Design & Development
  • Certification Courses– Freshers
  • Institutional Training– Undergraduate

Get In Touch

  • Indian Institute of Embedded Systems (IIES) - No 80, Ahad Pinnacle, Ground Floor, 5th Main, 2nd Cross, 5th Block, Koramangala Industrial Area Bangalore 560095, Karnataka, India
  • Phone +91 80 4121 6422
  • Mobile +91 98869 20008
  • [email protected]
  • [email protected]

Control Structures in C: Getting Started with Control Structures

  • 17 videos | 1h 54m 18s
  • Includes Assessment
  • Earns a Badge

WHAT YOU WILL LEARN

In this course.

  • Playable 1.  Course Overview 2m 6s FREE ACCESS
  • Playable 2.  Understanding C Control Structures 6m 40s In this video, you will learn how to outline three types of control structures used in the C language. FREE ACCESS
  • Locked 3.  Using if Statements in C 7m 55s In this video, you will learn about the use of basic if statements. FREE ACCESS
  • Locked 4.  Using Relational Operators with if Statements in C 6m 55s In this video, learn how to use relational operators with if statements. FREE ACCESS
  • Locked 5.  Chaining Relational Operators with Logical Operators 4m 59s In this video, you will learn how to use logical operators to connect relational operators. FREE ACCESS
  • Locked 6.  Exploring Quirks of if Statements in C 8m 46s In this video, find out how to identify common mistakes with if statements. FREE ACCESS
  • Locked 7.  Using if-else Conditional Blocks in C 9m 17s Learn about the use of if-else blocks. FREE ACCESS
  • Locked 8.  Creating Nested if-else Blocks in C 6m 23s Learn about the use of if-else blocks within other if-else blocks. FREE ACCESS
  • Locked 9.  Exploring Nested if Statements in C 7m 12s In this video, you will learn how to run code with if-else blocks nested inside each other. FREE ACCESS
  • Locked 10.  Introducing the else-if Block in C 4m 51s During this video, you will learn how to outline the if-else-if control structure. FREE ACCESS
  • Locked 11.  Using the if-else-if Ladder in C 8m 39s In this video, you will learn how to run code with the if-else-if ladder. FREE ACCESS
  • Locked 12.  Understanding the switch Statement in C 7m 17s Upon completion of this video, you will be able to illustrate the mechanics of the switch statement. FREE ACCESS
  • Locked 13.  Running Code with the switch Statement in C 8m 30s In this video, you will learn how to run code with switch statements. FREE ACCESS
  • Locked 14.  Using switch Statements for Various Situations in C 9m 16s Learn how to use switch statements in various scenarios. FREE ACCESS
  • Locked 15.  Exploring Nuances of switch Statements in C 5m 28s In this video, you will learn about the use of characters in switch statements. FREE ACCESS
  • Locked 16.  Shortening if-else Blocks Using Ternary Operator 7m 2s Learn how to use the ternary operator to shorten if-else blocks. FREE ACCESS
  • Locked 17.  Course Summary 3m 2s 097f01e9-2d12-429e-974a-3ec42c4d9e53 FREE ACCESS

assignment in control structure in c

EARN A DIGITAL BADGE WHEN YOU COMPLETE THIS COURSE

Skillsoft is providing you the opportunity to earn a digital badge upon successful completion on some of our courses, which can be shared on any social network or business platform.

YOU MIGHT ALSO LIKE

assignment in control structure in c

PEOPLE WHO VIEWED THIS ALSO VIEWED THESE

assignment in control structure in c

Surabhi Saxena

Control Statements in C

Share this article

Types of Control Statements

Decision making statement: the if-else statement, selection statement: the switch-case statement, iteration statements, faqs about control statements in c.

Control statements enable us to specify the flow of program control — that is, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.

There are four types of control statements in C:

  • Decision making statements (if, if-else)
  • Selection statements (switch-case)
  • Iteration statements (for, while, do-while)
  • Jump statements (break, continue, goto)

The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (ie, whether the outcome is true or false).

If the condition specified in the if statement evaluates to true, the statements inside the if-block are executed and then the control gets transferred to the statement immediately after the if-block. Even if the condition is false and no else-block is present, control gets transferred to the statement immediately after the if-block.

The else part is required only if a certain sequence of instructions needs to be executed if the condition evaluates to false. It is important to note that the condition is always specified in parentheses and that it is a good practice to enclose the statements in the if block or in the else-block in braces, whether it is a single statement or a compound statement.

The following program checks whether the entered number is positive or negative.

The following program compares two strings to check whether they are equal or not.

The above program compares two strings to check whether they are the same or not. The strcmp function is used for this purpose. It is declared in the string.h file as:

int strcmp(const char *s1, const char *s2);

It compares the string pointed to by s1 to the string pointed to by s2 . The strcmp function returns an integer greater than, equal to, or less than zero,  accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2 .

Therefore in the above program, if the two strings a and b are equal , the strcmp function should return a 0. If it returns a 0, the strings are the same; else they are different.

Nested if and if-else Statements

It is also possible to embed or to nest if-else statements one within the other. Nesting is useful in situations where one of several different courses of action need to be selected.

The general format of a nested if-else statement is:

The above is also called the if-else ladder . During the execution of a nested if-else statement, as soon as a condition is encountered which evaluates to true, the statements associated with that particular if-block will be executed and the remainder of the nested if-else statements will be bypassed. If neither of the conditions are true, either the last else-block is executed or if the else-block is absent, the control gets transferred to the next instruction present immediately after the else-if ladder.

The following program makes use of the nested if-else statement to find the greatest of three numbers.

The above program compares three integer quantities, and prints the greatest. The first if statement compares the values of a and b . If a>b  is true, program control gets transferred to the if-else statement nested inside the if block, where b is compared to c . If b>c is also true, the value of a is printed; else the value of c and a are compared and if c>a is true, the value of c is printed. After this the rest of the if-else ladder is bypassed.

However, if the first condition a>b is false, the control directly gets transferred to the outermost else-if block, where the value of b is compared with c (as a is not the greatest). If b>c is true the value of b is printed else the value of c is printed. Note the nesting, the use of braces, and the indentation. All this is required to maintain clarity.

A switch statement is used for multiple way selections that will branch into different code segments based on the value of a variable or expression. This expression or variable must be of integer data type.

The value of this expression is either generated during program execution or read in as user input. The case whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match with any of the case values.

The break statement is present at the end of every case. If it were not so, the execution would continue on into the code segment of the next case without even checking the case value. For example, supposing a switch statement has five cases and the value of the third case matches the value of expression . If no break statement were present at the end of the third case, all the cases after case 3 would also get executed along with case 3. If break is present only the required case is selected and executed; after which the control gets transferred to the next  statement immediately after the switch statement. There is no break after default because after the default case the control will either way get transferred to the next statement immediately after switch.

Example: a program to print the day of the week.

This is a very basic program that explains the working of the switch-case construct. Depending upon the number entered by the user, the appropriate case is selected and executed. For example, if the user input is 5, then case 5 will be executed. The break statement present in case 5 will pause execution of the switch statement after case 5 and the control will get transferred to the next statement after switch, which is:

It is also possible to embed compound statements inside the case of a switch statement. These compound statements may contain control structures. Thus, it is also possible to have a nested switch by embedding it inside a case.

All programs written using the switch-case statement can also be written using the if-else statement. However, it makes good programming sense to use the if statement when you need to take some action after evaluating some simple or complex condition which may involve a combination of relational and logical expressions (eg, (if((a!=0)&&(b>5)) ).

If you need to select among a large group of values, a switch statement will run much faster than a set of nested ifs. The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.

The switch statement must be used when one needs to make a choice from a given set of choices. The switch case statement is generally used in menu-based applications . The most common use of a switch-case statement is in data handling or file processing. Most of file handling involves the common functions: creating a file, adding records, deleting records, updating records, printing the entire file or some selective records. The following program gives an idea of how the switch case statement may be used in data handling. It does not involve the code for file processing as we can discuss file handling in C only after we have learnt advanced concepts like pointers, structures and unions.

Example: A switch case statement used in data file processing.

The above example of switch-case generally involves nesting the switch-case construct inside an iteration construct like do-while.

Iteration statements are used to execute a particular set of instructions repeatedly until a particular condition is met or for a fixed number of iterations.

1. The for statement

The for statement or the for loop repeatedly executes the set of instructions that comprise the body of the for loop until a particular condition is satisfied.

The for loop consists of three expressions:

  • The initialization expression , which initializes the looping index . The looping index controls the looping action. The initialization expression is executed only once, when the loop begins.
  • The termination expression , which represents a condition that must be true for the loop to continue execution.
  • The increment/decrement expression  is executed after every iteration to update the value of the looping index.

The following program uses the for loop to print the series: 0,1,1,2,3,5,8,13 … to n terms.

If the first two elements 0 and 1 are excluded, it is seen that each of the next elements in the series is the sum of the previous two elements. For example, the third element is a sum of the first two elements (0+1), the fourth element is a sum of the second and the third elements (1+1=2), the fifth element is a sum of the third and the fourth elements (1+2=3) and so on. Therefore, each time it is the sum of the previous two elements that is printed. The previous value of b becomes the new value of a and the previous value of sum becomes the new value of b . The newly calculated sum becomes the next element and is subsequently printed. These steps are executed repeatedly until the looping index i does not reach one less than the number of terms entered by the user. The looping index i begins from 2 as the first two terms have already been printed. It could also range from 0 to 1 less than n-2 as:

or from 1 to n-2 as:

The for statement is very versatile and can be written in four different ways:

1. Omitting the Initialization Expression

In this case, the looping index is initialized before the for loop. Thus the for loop takes the following form:

Notice that the semicolon that terminates the initialization expression is present before the condition expression.

2. Omitting the Condition

In this case the condition is specified inside the body of the for loop, generally using an if statement. The while or do-while statements may also be used to specify the condition. Thus the for loop takes the following form:

Again, it can be seen that the semicolon that terminates the condition is present in the for statement. The following program explains how the condition can be omitted:

3. Omitting the increment /decrement Expression:

In this case the increment/decrement expression is written inside the body of the for loop.

4. Omitting all Three Expressions:

It is also possible to omit all three expressions, but they should be present in the ways discussed above. If all three expressions are omitted entirely — ie, they are not mentioned in the ways discussed above — then the for loop becomes an infinite or never-ending loop . In this case, the for loop takes the following form:

2. The while statement

The while statement executes a block of statements repeatedly while a particular condition is true.

The statements are executed repeatedly until the condition is true.

Example: Program to calculate the sum of the digits of a number (eg, 456; 4+5+6 = 15)

The above program uses the while loop to calculate the sum of the digits of a number. For example, if the number is 456, the while loop will calculate the sum in four iterations as follows. It would be helpful to remember that % gives the remainder and / the quotient.

Iteration 1: n>0  Condition is true(n=456) a=n%10=6; sum=sum+a=6; n=n/10= 45;  New value of n is 45.

Iteration 2: n>0 Condition is true(n=45) a=n%10=5; sum=sum+a=6+5=11; n=n/10= 4;   New value of n is 4.

Iteration 3: n>0 Condition is true(n=4) a=n%10=4; sum=sum+a=11+4=15; n=n/10= 0;  ew value of n is 0.

Iteration 4: n>0 Condition is false(n=0). After the fourth iteration control exits the while loop and prints the sum to be 15.

Example 2: Program to check whether the entered number is a palindrome or not.

A palindrome is a number which remains the same when its digits are read or written from right to left or vice versa, eg 343 is a palindrome, but 342 is not. The following program works on the logic that if the reverse of the number is same as the original number then the entered number is a palindrome, otherwise it is not.

The above program uses almost the same logic as the program concerning the sum of digits. As was seen in that program, n becomes 0 in the last iteration. However, we need to compare the original value of n to the reverse of the number to determine whether it is a palindrome or not. Therefore, the value of n has been stored in m , before entering the while loop. The value of m is later compared with reverse to decide whether the entered number is a palindrome or not.

The while loop works in the following way:

Iteration 1: a= n%10=3; reverse=reverse*10+a=0*10+3=3; n=n/10=34;

Iteration 2: a=n%10=4; reverse=reverse*10+a=3*10+4=34; n=n/10=3;

Iteration 3: a= n%10=3; reverse=reverse*10+a=34*10+3=343; n=n/10=0;

Iteration 4: n>0 condition false(n=0). Control exits from the while loop.

3. The do-while loop

The do-while statement evaluates the condition at the end of the loop after executing the block of statements at least once. If the condition is true the loop continues, else it terminates after the first iteration. Syntax:

Note the semicolon which ends the do-while statement. The difference between while and do-while is that the while loop is an  entry-controlled loop — it tests the condition at the beginning of the loop and will not execute even once if the condition is false, whereas the do-while loop is an  exit-controlled loop — it tests the condition at the end of the loop after completing the first iteration.

For many applications it is more natural to test for the continuation of a loop at the beginning rather than at the end of the loop. For this reason, the do-while statement is used less frequently than the while statement.

Most programs that work with while can also be implemented using do-while. The following program calculates the sum of digits in the same manner, except that it uses the do-while loop:

However, the do-while statement should be used only in situations where the loop must execute at least once whether or not the condition is true.

A practical use of the do-while loop is in an interactive menu-driven program where the menu is presented at least once, and then depending upon the choice of the user, the menu is displayed again or the session is terminated. Consider the same example that we saw in switch-case. Without using an iteration statement like do-while, the user can choose any option from the menu only once. Moreover, if a wrong choice is entered by mistake the user doesn’t have the option of entering his choice again. Both these faults can be corrected by using the do-while loop.

Control statements in C are programming constructs that allow you to control the flow of a program. They include conditional statements, loops, and branching statements.

Conditional statements, such as if , else if , and switch , allow you to execute different blocks of code based on specified conditions. They enable your program to make decisions and perform actions accordingly.

The if statement is used to execute a block of code if a specified condition is true. It can be followed by an optional “else” statement to specify an alternative action if the condition is false.

if statements are used for general conditional branching, while switch statements are used for multi-way branching based on the value of an expression. if statements are more flexible and can handle complex conditions, whereas switch statements are ideal for situations where a variable can match specific values.

Use a while loop when you need to repeat a block of code as long as a condition remains true but without a fixed number of iterations. for loops are more suitable for situations with a known number of iterations.

Common mistakes include not using braces for code blocks in if and loop statements, forgetting to update loop control variables, and creating infinite loops by not changing loop conditions correctly. Properly structuring your code and handling corner cases are essential.

Yes, you can use multiple else if conditions in an if statement to evaluate a series of conditions sequentially. This allows you to choose from several alternatives based on the first condition that is true.

My name is Surabhi Saxena, I am a graduate in computer applications. I have been a college topper, and have been awarded during college by the education minister for excellence in academics. I love programming and Linux. I have a blog on Linux at www.myblogonunix.wordpress.com.

SitePoint Premium

[Diagram:Pic/COMP9024-small.png]

C Language Tutorial

assignment in control structure in c

Branch & Jump Stmt

Control structures in c.

Control structures are an essential part of programming languages that allow you to control the flow of execution in a program. They determine the order in which statements are executed and enable you to make decisions and repeat blocks of code based on specific conditions.

Conditional Statements

  • if statement: Executes a block of code if a specified condition is true.
  • if-else statement: Executes a block of code if a condition is true; otherwise, executes a different block of code.
  • else-if statement: Executes a block of code in which if condition become false then else if block will execute to check for next condition.
  • nested if-else statement: Combines multiple if-else statements inside one another.

if-statement

In this program, the user is prompted to enter three numbers. The program then uses a series of if statements to compare the numbers and determine the largest among them. Each if statement checks if one number is greater than the other two, and if so, it prints that number as the largest.

Note that using only if statements can result in multiple conditions being true, which is why each condition is checked independently. In this case, if more than one number is the largest, all of them will be printed.

You can run this program by compiling and executing it. Enter three numbers, and the program will output the largest among them using only if statements.

If-Else Statement

The if-else statement is a control structure in programming that allows you to perform different actions based on a condition. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, it executes a different block of code.

The syntax for the if-else statement in C programming is as follows:

The condition is an expression that evaluates to either true or false. If the condition is true, the code within the if block is executed. Otherwise, the code within the else block is executed.

In this example, we have a simple c-language code to demonstrate the usage of the if-else statement.

In the above example, the variable temperature is assigned a value of 25. The if-else statement checks if the temperature is greater than 30. Since 25 is not greater than 30, the condition evaluates to false, and the code within the else block is executed. Therefore, the output will be "It's a moderate day."

Additional Notes:

  • The if-else statement can be nested within each other to handle multiple conditions.
  • You can also use multiple else if statements to handle different cases.
  • The else block is optional. If you don't provide an else block, the code will simply continue executing after the if block.

else if Statement in C

The "else if" statement is used in C programming to test multiple conditions. It allows you to specify a new condition to test if the preceding "if" statement or any previous "else if" statement evaluates to false.

The syntax of the "else if" statement is as follows:

Let's consider an example that determines the grade of a student based on their score:

In this example, the program asks the user to enter a score. Based on the score, the program uses the "else if" statements to determine the corresponding grade and prints it on the screen.

If the score is greater than or equal to 90, the program prints "Grade: A". If the score is between 80 and 89, it prints "Grade: B", and so on. If none of the conditions are met, the program prints "Grade: F".

By using the "else if" statement, you can test multiple conditions and execute the corresponding code block based on the first condition that evaluates to true.

Nested if Statements in C

In C programming, nested "if" statements are used to create a hierarchy of conditional statements. They allow you to have an "if" statement within another "if" statement, creating multiple levels of decision-making.

When you have complex conditions or situations where multiple conditions need to be evaluated, you can use nested "if" statements. Each "if" statement is enclosed within another "if" or "else" statement, creating a nested structure.

The nested "if" statements are executed based on the result of the outer "if" statements. If the condition of the outer "if" statement is true, the program evaluates the condition of the inner "if" statement. This process continues for each nested "if" statement.

The syntax of nested "if" statements is as follows:

Let's consider an example where we check if a number is positive and even:

In this example, the program asks the user to enter a number. The program then uses nested "if" statements to determine if the number is positive and even.

If the number is greater than 0, the program evaluates the condition inside the nested "if" statement. If the number is divisible by 2 (i.e., it's even), it prints "Number is positive and even". Otherwise, it prints "Number is positive but not even".

If the number is not greater than 0, it directly prints "Number is not positive". The nested "if" statements allow the program to perform different checks based on the conditions in a hierarchical manner.

By using nested "if" statements, you can create complex decision-making structures in your C programs, allowing for more precise control and handling of different scenarios.

  • Learn C Language
  • Learn C++ Language
  • Learn python Lang

DigitalSanjiv

Online Digital Learning

Control Structures in c

Control Structures in C

Table of Contents

The structures of a program which affects the order of execution of the statements are called control structures. The normal execution of statements is in sequential fashion but to change the sequential flow, various control structures are used. Broadly, control structures are of three types-

  • Selection /conditional – executes as per choice of action.
  • Iteration – Performs a repetitive action.
  • Jumping – used to skip the action, or particular statements.

Selection/Conditional control structures

Also called conditional control constructs and are used to choose from alternative course of actions based on certain conditions. It has various forms

  • nested if-else
  • switch -case

If Statements

If statement tests a condition and if it results in non-zero(true) value then the statements following if are executed.

  • There is no semi colon after if statement
  • The conditional expression of c can have relational (<,<=, >,>=,==,)or logical(&&,||,!) operator but can’t have assignment operator.

Example to print the largest of three numbers

Explanation – In the first if statement, it will scan for three variables a,b and c. This if statement will be TRUE only if all three variables are entered through standard input device.

 Then value of a is assigned to d.

if(b%d) d=b;

In the second if statement modulus value of b against d is calculated , it will result in non zero if b is greater than d(which is actually value of a). hence value of b would be assigned to d. It actually means that b is greater than a. Now 

if(c%d) d=c;

value of c is compared with b and if it returns as non zero then c is greatest of all. Otherwise b is greatest.

In second and third if statements are false then a is the greatest of all.

if statement does not give any output if condition is false. To get the result for both true and false, if-else statement is used.

If-Else Statement

This control structure tests the if conditions and if it is true then the body of if is executed otherwise body of else is executed. If-else is more complete version as compare to simple if statement where you have statements for TRUE and FALSE conditions.

Note: Body of if -else statement should be enclosed in curly braces if it have more than one statements. The same is not mandatory for single statement.

Nested if-else statement

Sometimes, the body of if-else statement may be placed within  another if-else statement then it is called nested if-else statement. This control structure is particularly helpful to simultaneously test more than one conditions. For example a group of friends are planning a picnic on Sunday if it is a sunny day. So here two conditions are simultaneously tested, the day should be sunday and second it should be a sunny day.

Example to find out the largest of three numbers.

If-else if Statement

When you have to evaluate more than two conditions then you need to use if-else if ladder. This control structure is particularly helpful when you have more conditions to evaluate.

Example to demonstrate grade of a student

Switch Statement

Switch control structure can cut short the long series of if-else if statements . The switch statement can select a case from several available cases. The case can be integral expression(int or char) only. If the case value matches with any of the available cases then statements below it are executed until break statement is encountered. If no matching case is found then default label is executed. If no default label has been defined then switch terminates.

What are the differences between if and switch statement?

  • If statement can test any type of expression (integral, floating point, logical, relational etc.) but switch can test only integral expression only.
  • If statement encloses multiple statements inside curly braces but you can never put multiple statements of switch inside curly braces.
  • Break can be used inside switch body but can’t be used inside if body.

Iterations means repetitions. When you wish to repeat a task more than once then it is called iterative task. The iterative tasks can be performed in c language through loops.  Looping means to execute a task  repeatedly and simultaneously checking the condition when to stop.  

Loops control structures can be used to –

  • take same action on each character of a file until end of file is reached.
  • take the same action until the number becomes zero.
  • take the same action on each elements of an array until all array elements are processed.
  • take the same action until newline character is reached
  • take the same action on each item in the data set.
  • take the same action until the file gets printed.

C Language has three types of loops

  • do-while loop

For loop steps through a series of specified action once for each value monitoring the specified condition to terminate each time.

for(initial_exp;cond_exp;modifier_exp)

here initial_exp – initialization expression. It initializes a variable with initial value

cond_exp – conditional expression. This condition decides whether to continue the loop or exit it.

modifier_exp – modifier expression. It changes the value of the variable after each iteration.

Example to write a counting from 0 to the value of i

Infinite Loop 

Infinite loop is a control structure which keep on executing it’s body indefinitely. Either it will keep on giving output continuously or no output at all. This kind of loops are also called indefinite or endless loop. 

Note – A loop control structure should always be finite means  it should terminate after some iterations, else it becomes infinite loop . Infinite loops are highly undesirable and due care should be taken to keep the loops finite.

for loop usage

  1           for loop control structure is best suited for the situations where we know in advance how many times the loop will execute.

2              for loop control structure is natural choice for processing the array elements of all dimensions

Conditions for infinite for loop

  • A for loop without conditional test is infinite for loop
  • A for loop whose conditional test is true for loop variables initial value but it’s not modified then loop becomes infinite loop.

While loop is also called pre-test loop. It first tests the specified conditional expression and as long as the conditional expression evaluates to non-zero, action is taken.

while(conditional expression)

body of while

here conditional expression can be condition or expression. so

while(x=x+1)

while(n–) are all legal conditional expression in while loop.

Important points about while loop

  • While loop is mostly suited in the situations where it is not known for how many times the loop will continue executing. e.g. while(number!=0)
  • If conditional expression in a while loop is always evaluated as non zero then it infinite while loop. e.g. while(1) or while(!0).
  • Never us assignment operator in place of equality operator in the test condition
  • If the conditional expression evaluates to zero in the very starting then loop body will not execute even once.

Example – to reverse a positive number

Do-while loop

Also called post test loop because it executes it’s body at least once without testing specified conditional expression and then makes the test. Do-while terminates when the conditional expression evaluates to zero.

Notice the semicolon after condition

Important points about do-while loop

  • A do-while loop tests the condition after executing the body at least once.
  • A do-while will make minimum iteration as 1 even if the condition is false.
  • A do-while loop is good choice for processing menus because of it’s first task then test nature.

Difference between while and do-while loops

3              Jumping

There are three jumping statements

Break Statement

Break is a jumping statement that when encountered in a –

  • Switch block – skips the rest of the switch block at once and jump to the next statement just after the switch block
  • Loop- skips the rest of the loop statements and jumps to the next statement just after loop body

Example – To find the given number as prime

Continue Statement

Continue is also a jump statement which skips rest of the statements in the loop body and jumps to the next iteration. It differs from break in a way that break simply comes out of a block in which it is defined but continue just skips the rest of statements after it and continue to execute the loop body with next iteration.

Goto statement

Although goto statement is avoided in c language still it is available in two forms unconditional goto and conditional goto. it is a jump statement which causes the control to jump from the place where goto is encountered to the place indicated by label.

  • Unconditional goto – Used to make jump to the specified label without testing a condition.
  • Conditional goto – Used to make jump to the specified label after testing condition.

Similar Posts :       Input/Output functions in C            Operators and Expressions in C           Variables in C

You may also like :

Let us Learn JavaScript from Step By Step       Reverse Charge Mechanism in Tally.ERP9     What is New in HTML5

To Download Official TurboC Compiler from  here

Difference between break and continue

1) Break causes exit from the loop leaving rest of the iterations while continue causes control to continue with the next iteration 2) break can be used in all control structures (for, while, do-while loops and switch statements ) except constructs of if family. Continue can be used only in the looping constructs but not in switch and if family. 3) Break can be used inside an infinite loop to stop them. Continue can be used inside infinite loops to skip one iterations but it can not stop it.

Similarities between break and continue

1) Both are used to jump from one place to another by skipping rest of the statements after them. 2) Both can be used inside the loops. 3) Inside a loop both can be used with if or switch statements.

Infinite Loops

An infinite loop is a loop that keeps on executing its body as there is not control . Reason for loop to be infinite are – 1 When conditional expression always evaluates to TRUE 2 No condition is imposed to come out of the loop 3 No modifier expression to modify the loop variable

How to stop an infinite loop

By pressing Ctrl+break keys

guest

[…] in C                                &n…Input/Output functions in […]

[…]         Control Structures in C                    Arrays in […]

wpdiscuz

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Introduction to C Programming Language

  • Introduction
  • Setting up your environment
  • The Linux programming environment
  • Compiling & Debugging C
  • Introduction to Git
  • The C programming language
  • Integer types in C
  • Floating-point types
  • Operator precedence in C
  • Input and output

Statements and control structures

  • Structured data types
  • Type aliases using typedef
  • Data structures and programming techniques
  • Asymptotic notation
  • Dynamic Arrays
  • Linked lists
  • Deques and doubly-linked lists
  • Circular linked lists
  • Abstract data types
  • Hash tables
  • Generic containers
  • Object-oriented programming
  • Binary Search Trees
  • Augmented trees
  • Balanced trees
  • Red-black trees
  • Dynamic programming
  • Randomization
  • String processing
  • Unit testing C programs
  • Bit Manipulation
  • Persistence
  • What's next?
  • C Language Limitations and How It Compares to Other Languages

Related Books

C Language Primer for Java Developers

C Language Primer for Java Developers

Guide to Prompt Engineering

Guide to Prompt Engineering

TypeScript for Java Developers by CodeAhoy

TypeScript for Java Developers by CodeAhoy

Ruby for Beginners

Ruby for Beginners

The Little ASP.NET Core Book

The Little ASP.NET Core Book

Books / Introduction to C Programming Language / Chapter 12

In this chapter, simple & compound statements, conditionals, the while loop, the do..while loop, the for loop, loops with break, continue, and goto, choosing where to put a loop exit.

The bodies of C functions (including the main function) are made up of statements . These can either be simple statements that do not contain other statements, or compound statements that have other statements inside them. Control structures are compound statements like if/then/else, while, for, and do..while that control how or whether their component statements are executed.

Simple statements

The simplest kind of statement in C is an expression (followed by a semicolon, the terminator for all simple statements). Its value is computed and discarded. Examples:

Most statements in a typical C program are simple statements of this form.

Other examples of simple statements are the jump statements return , break , continue , and goto . A return statement specifies the return value for a function (if there is one), and when executed it causes the function to exit immediately. The break and continue statements jump immediately to the end of a loop (or switch ; see below) or the next iteration of a loop; we’ll talk about these more when we talk about loops. The goto statement jumps to another location in the same function, and exists for the rare occasions when it is needed. Using it in most circumstances is a sin.

Compound statements

Compound statements come in two varieties: conditionals and loops, which we’ll explore in depth in the next sections.

These are compound statements that test some condition and execute one or another block depending on the outcome of the condition. The simplest is the if statement:

The body of the if statement is executed only if the expression in parentheses at the top evaluates to true (which in C means any value that is not 0).

The braces are not strictly required, and are used only to group one or more statements into a single statement. If there is only one statement in the body, the braces can be omitted:

This style is recommended only for very simple bodies. Omitting the braces makes it harder to add more statements later without errors.

In the example above, the lack of braces means that the hideInBunker() statement is not part of the if statement, despite the misleading indentation. This sort of thing is why I generally always put in braces in an if .

An if statement may have an else clause, whose body is executed if the test is false (i.e. equal to 0).

A common idiom is to have a chain of if and else if branches that test several conditions:

This can be inefficient if there are a lot of cases, since the tests are applied sequentially. For tests of the form _ _ `==` _ _, the `switch` statement may provide a faster alternative. Here’s a typical `switch` statement:

This prints the string “cow” if there is one cow, “cowen” if there are two cowen, and “cows” if there are any other number of cows. The switch statement evaluates its argument and jumps to the matching case label, or to the default label if none of the cases match. Cases must be constant integer values.

The break statements inside the block jump to the end of the block. Without them, executing the switch with numberOfCows equal to 1 would print all three lines. This can be useful in some circumstances where the same code should be used for more than one case:

or when a case “falls through” to the next:

Note that it is customary to include a break on the last case even though it has no effect; this avoids problems later if a new case is added. It is also customary to include a default case even if the other cases supposedly exhaust all the possible values, as a check against bad or unanticipated inputs.

Though switch statements are better than deeply nested if/else-if constructions, it is often even better to organize the different cases as data rather than code. We’ll see examples of this when we talk about function pointers .

Nothing in the C standards prevents the case labels from being buried inside other compound statements. One rather hideous application of this fact is Duff’s device .

There are three kinds of loops in C.

A while loop tests if a condition is true, and if so, executes its body. It then tests the condition is true again, and keeps executing the body as long as it is. Here’s a program that deletes every occurrence of the letter e from its input.

Note that the expression inside the while argument both assigns the return value of getchar to c and tests to see if it is equal to EOF (which is returned when no more input characters are available). This is a very common idiom in C programs. Note also that even though c holds a single character, it is declared as an int . The reason is that EOF (a constant defined in stdio.h ) is outside the normal character range, and if you assign it to a variable of type char it will be quietly truncated into something else. Because C doesn’t provide any sort of exception mechanism for signalling unusual outcomes of function calls, designers of library functions often have to resort to extending the output of a function to include an extra value or two to signal failure; we’ll see this a lot when the null pointer shows up in the chapter on pointers .

The do .. while statement is like the while statement except the test is done at the end of the loop instead of the beginning. This means that the body of the loop is always executed at least once.

Here’s a loop that does a random walk until it gets back to 0 (if ever). If we changed the do .. while loop to a while loop, it would never take the first step, because pos starts at 0.

examples/statements/randomWalk.c

The do .. while loop is used much less often in practice than the while loop.

It is theoretically possible to convert a do .. while loop to a while loop by making an extra copy of the body in front of the loop, but this is not recommended since it’s almost always a bad idea to duplicate code.

The for loop is a form of syntactic sugar that is used when a loop iterates over a sequence of values stored in some variable (or variables). Its argument consists of three expressions: the first initializes the variable and is called once when the statement is first reached. The second is the test to see if the body of the loop should be executed; it has the same function as the test in a while loop. The third sets the variable to its next value. Some examples:

A for loop can always be rewritten as a while loop.

The break statement immediately exits the innermmost enclosing loop or switch statement.

The continue statement skips to the next iteration. Here is a program with a loop that iterates through all the integers from -10 through 10, skipping 0:

examples/statements/inverses.c

Occasionally, one would like to break out of more than one nested loop. The way to do this is with a goto statement.

The target for the goto is a label , which is just an identifier followed by a colon and a statement (the empty statement ; is ok).

The goto statement can be used to jump anywhere within the same function body, but breaking out of nested loops is widely considered to be its only genuinely acceptable use in normal code.

Choosing where to put a loop exit is usually pretty obvious: you want it after any code that you want to execute at least once, and before any code that you want to execute only if the termination test fails.

If you know in advance what values you are going to be iterating over, you will most likely be using a for loop:

Most of the rest of the time, you will want a while loop:

The do .. while loop comes up mostly when you want to try something, then try again if it failed:

Finally, leaving a loop in the middle using break can be handy if you have something extra to do before trying again:

(Note the empty for loop header means to loop forever; while(1) also works.)

Licenses and Attributions

This book is licensed under Creative Commons Attribution-ShareAlike 4.0

Original Content CC-BY-SA 4.0 International

  • This work is a derivative of "Notes on Data Structures and Programming Techniques (CPSC 223, Spring 2022)" by James Aspnes , used under Creative Commons Attribution-ShareAlike 4.0. Original copyright notice: Copyright © 2001–2021 by James Aspnes. Distributed under a Creative Commons Attribution-ShareAlike 4.0 International license: https://creativecommons.org/licenses/by-sa/4.0/.

Other Content, as indicated:

  • "GitHub" , "Git" from Wikipedia under the Creative Commons Attribution-ShareAlike License 3.0 / Lightly modified from original
  • "Linked list" , "Git" from Wikipedia under the Creative Commons Attribution-ShareAlike License 3.0 / Lightly modified from original
  • Foto from Wikipedia, by Jonn Leffmann.

Speak Your Mind Cancel reply

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

C structs and Pointers

C Structure and Function

C Struct Examples

  • Add Two Complex Numbers by Passing Structure to a Function
  • Add Two Distances (in inch-feet system) using Structures

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

  • Define Structures

Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.

Syntax of struct

For example,

Here, a derived type struct Person is defined. Now, you can create variables of this type.

Create struct Variables

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.

Here's how we create structure variables:

Another way of creating a struct variable is:

In both cases,

  • person1 and person2 are struct Person variables
  • p[] is a struct Person array of size 20.

Access Members of a Structure

There are two types of operators used for accessing members of a structure.

  • . - Member operator
  • -> - Structure pointer operator (will be discussed in the next tutorial)

Suppose, you want to access the salary of person2 . Here's how you can do it.

Example 1: C structs

In this program, we have created a struct named Person . We have also created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for the person1 object.

Notice that we have used strcpy() function to assign the value to person1.name .

This is because name is a char array ( C-string ) and we cannot use the assignment operator = with it after we have declared the string.

Finally, we printed the data of person1 .

  • Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.

For example, let us look at the following code:

We can use typedef to write an equivalent code with a simplified syntax:

Example 2: C typedef

Here, we have used typedef with the Person structure to create an alias person .

Now, we can simply declare a Person variable using the person alias:

  • Nested Structures

You can create structures within a structure in C programming. For example,

Suppose, you want to set imag of num2 variable to 11 . Here's how you can do it:

Example 3: C Nested Structures

Why structs in c.

Suppose you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name , citNo and salary to store this information.

What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.

A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.

More on struct

  • Structures and pointers
  • Passing structures to a function

Table of Contents

  • C struct (Introduction)
  • Create struct variables
  • Access members of a structure
  • Example 1: C++ structs

Sorry about that.

Related Tutorials

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

IMAGES

  1. Control Statement/Structure in C Language||Part 2||Loop and

    assignment in control structure in c

  2. Control Statements in C: An Ultimate Guide

    assignment in control structure in c

  3. C++ Control Structures

    assignment in control structure in c

  4. Control Structure

    assignment in control structure in c

  5. introduction to for Control Structures in C++

    assignment in control structure in c

  6. Control Structures in C++ (Complete Understanding)

    assignment in control structure in c

VIDEO

  1. Working with Assignment operators in C| C Tutorials for Beginners

  2. ASSIGNMENT CONTROL 2 GROUP 4 QUESTION B

  3. assignment 2 for mid exams chapter 2 decision control structure C

  4. Programs and Solutions (Control Structure) || Programming in C

  5. C++ Control Structure

  6. Control Structure || Programming in C

COMMENTS

  1. Control Structures in Programming Languages

    Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. There are three basic types of logic, or flow of control, known as: Sequence logic, or sequential flow.

  2. 4. Control Structures

    Control Structures — The Book of C (version 2022.08) 4. Control Structures ¶. In this chapter, we encounter the set of "control" structures in C, such as conditional statements and looping constructs. As a preview, the control structures in C are nearly identical to those found in Java (since Java syntax is heavily based on C), and bear ...

  3. Assign one struct to another in C

    3. Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

  4. PDF Control Structures

    a control structure with a different syntax (ADA) -- don't evaluate C2. if C1 and then C2 then -- if C1 is false if C1 or else C2 then -- if C1 is true. Multi-way Selection. Case statement needed when there are many possibilities "at the same logical level" (i.e. depending on the same condition) case Next_Char is.

  5. C/C++ Control Structures

    C/C++ Control Structures. #. Control structures are what differentiate a computer program from a calculator, and allow us to repeat or avoid sections of code depending on the logical operation of the program. Many of the fundamental details are very similar to Python, and generally sections will translate fairly easily, although not perfectly ...

  6. Core C: Control Structures, Variables, Scope, and Uninitialized Memory

    Assignment 2 Problem 1. Rewrite the program below, replacing the for loop with a combination of goto and if statements. The output of the program should stay the same. ... In lecture, we covered a variety of control structures for looping, such as for, while, do/while, goto, and several for testing conditions, such as if and switch.

  7. PDF Assignment 5: Assignments and control structures

    To review the structure and semantics of loops refer to section 7.5 of Touch of class. It happens very often that you want to iterate through all the items of a container, for example all lines in Zurich or all stations of a particular line.

  8. PDF Lecture 1: Elementary Programming and Control Structures

    6 System.out.println(" axˆ2 + bx + c = 0 \n"); 7 8 //the values of a,b and c need to be stored in variables 9 double a, b, c; 10 //we also need variables to store our two solutions 11 double x1, x2; 12 13 //we need to read the values of a, b and c from the user 14 //so we need to use the Scanner object 15 Scanner in = new Scanner (System.in ); 16

  9. CONTROL STRUCTURES IN C

    CONTROL STRUCTURES IN C. Control Structures specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is true and optionally, other statements to be executed if the condition is false. See blow image to understand control (Decision making ) structure:-.

  10. Control structures and statements in C and C++

    Control statements in C/C++ to implement control structures. We have to keep in mind one important fact:- all program processes can be implemented with these 3 control structures only. That's why I wrote "control structures are the basic entities of a structured programming language". To implements these "control structures" in a C ...

  11. C Structures

    The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type.

  12. Control Structures 101: Fundamentals Guide for C Programming

    In C programming, there are several common control structures that are used extensively. These include conditional statements like the "if" statement and the "switch" statement, as well as looping structures like the "while" loop, the "for" loop, and the "do-while" loop. These control structures provide flexibility and allow ...

  13. Control Structures in C: Getting Started with Control Structures

    A control structure in C is any code construct that changes the flow of control, such as the order of execution in a program. The three main types of control structures in C are decision-making control structures, looping control structures, and unconditional control structures. Decision-making control structures include if-else blocks and ...

  14. C Control Flow Examples

    Reverse a number. Calculate the power of a number. Check whether a number is a palindrome or not. Check whether an integer is prime or Not. Display prime numbers between two intervals. Check Armstrong number. Display Armstrong numbers between two intervals. Display factors of a number. Print pyramids and triangles.

  15. Control Statements in C

    The first if statement compares the values of a and b. If a>b is true, program control gets transferred to the if-else statement nested inside the if block, where b is compared to c. If b>c is ...

  16. Week 1: Introduction

    The large assignment gives you experience applying tools/techniques (but to a larger programming problem than the homework) The assignment will be carried out individually. The assignment will be released after the mid-term test and is due in week 10. The assignment contributes 12% to overall mark.

  17. Control Structures In C

    The if-else statement is a control structure in programming that allows you to perform different actions based on a condition. It evaluates a condition and executes a block of code if the condition is true. If the condition is false, it executes a different block of code. Syntax: The syntax for the if-else statement in C programming is as follows:

  18. Control Structures in C

    The structures of a program which affects the order of execution of the statements are called control structures. The normal execution of statements is in sequential fashion but to change the sequential flow, various control structures are used. Broadly, control structures are of three types-. Selection /conditional - executes as per choice ...

  19. Statements and control structures

    The bodies of C functions (including the main function) are made up of statements. These can either be simple statements that do not contain other statements, or compound statements that have other statements inside them. Control structures are compound statements like if/then/else, while, for, and do..while that control how or whether their ...

  20. Expressions, Assignments, and Control Structures

    etc. Next, we'll consider the primary issues with assignments, such as conditional and multiple targets. Finally, we'll look at statement level control structures, addressing why they are needed and the tradeoffs (in terms of readability, writability, reliability, and run-time efficiency) of various control-structure constructs. Expressions

  21. C struct (Structures)

    You will learn to define and use structures with the help of examples. In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name. ... C Flow Control. C if...else; C for Loop; C while Loop; C break and continue ... This is because name is a char array and we cannot use the assignment ...

  22. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment: