Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

C if...else Statement

C while and do...while Loop

  • C break and continue

C switch Statement

  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Count Number of Digits in an Integer
  • Find LCM of two Numbers
  • Calculate the Sum of Natural Numbers

In programming, a loop is used to repeat a block of code until the specified condition is met.

C programming has three types of loops:

  • do...while loop

We will learn about for loop in this tutorial. In the next tutorial, we will learn about while and do...while loop.

The syntax of the for loop is:

  • How for loop works?
  • The initialization statement is executed only once.
  • Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
  • However, if the test expression is evaluated to true, statements inside the body of the for loop are executed, and the update expression is updated.
  • Again the test expression is evaluated.

This process goes on until the test expression is false. When the test expression is false, the loop terminates.

To learn more about test expression (when the test expression is evaluated to true and false), check out relational and logical operators .

for loop Flowchart

Flowchart of for loop in C programming

Example 1: for loop

  • i is initialized to 1.
  • The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is executed. This will print the 1 (value of i ) on the screen.
  • The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is evaluated to true, and the body of for loop is executed. This will print 2 (value of i ) on the screen.
  • Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This process goes on until i becomes 11.
  • When i becomes 11, i < 11 will be false, and the for loop terminates.

Example 2: for loop

The value entered by the user is stored in the variable num . Suppose, the user entered 10.

The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.

Then, the update statement ++count is executed and count will equal to 2. Again, the test expression is evaluated. Since 2 is also less than 10, the test expression is evaluated to true and the body of the for loop is executed. Now, sum will equal 3.

This process goes on and the sum is calculated until the count reaches 11.

When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates.

Then, the value of sum is printed on the screen.

We will learn about while loop and do...while loop in the next tutorial.

Table of Contents

  • for Loop Examples

Video: C for Loop

Sorry about that.

Related Tutorials

C Ternary Operator

For Loops in C – Explained with Code Examples

Bala Priya C

In programming, you'll use loops when you need to repeat a block of code multiple times.

These repetitions of the same block of code a certain number of times are called iterations . And there's a looping condition that decides the number of iterations.

The for and the while loops are widely used in almost all programming languages.

In this tutorial, you'll learn about for loops in C. In particular, you'll learn:

  • the syntax to use for loops,
  • how for loops work in C, and
  • the possibility of an infinite for loop.

Let's get started.

C for Loop Syntax and How it Works

In this section, you'll learn the basic syntax of for loops in C.

The general syntax to use the for loop is shown below:

In the above syntax:

  • initialize is the initialization statement – the loop control variable is initialized here.
  • check_condition is the condition that determines if the looping should continue.
So long as check_condition is true, the body of the loop is executed.
  • The update statement updates the loop control variable after the statements in the loop body are executed.

Control Flow in C for Loops

The control flow is as follows:

  • Initialize the counter – the initialize statement is executed. This happens only once, at the beginning of the loop.
  • Check if the looping condition is true – the expression check_condition is evaluated. If the condition is true , go to step 3. If false , exit the loop.
  • Execute statements in the loop body.
  • Update the counter – the update statement is executed.
  • Go to step 2.

This is also illustrated below:

image-66

Now that you have an idea of how for loops work, let's take a simple example to see the for loop in action.

C for Loop Example

Let's write a simple for loop to count up to 10, and print the count value during each pass through the loop.

In the above code snippet,

  • count is the counter variable, and it's initialized to 0 .
  • The test condition here is count <= 10 . Therefore, count can be at most 10 for looping to continue.
  • In the body of the loop, the value of count is printed out.
  • And the value of count is increased by 1.
  • The control then reaches the condition count <= 10 and the looping continues if the condition evaluates to true.
  • In this example, the looping condition count < = 10 evaluates to false when the count value is 11 – and your loop terminates.

And here's the output:

When using loops, you should always make sure that your loop does terminate at some point.

You know that the looping continues so long as check_condition is true . And the looping stops once check_condition becomes false . But what happens when your looping condition is always true ?

Well, that's when you run into an infinite loop – your loop goes on forever, until your program crashes, or your system powers off.😢

You'll learn more about infinite loops in the next section.

Infinite for Loop

When your loop doesn't stop and keeps running forever, you'll have an infinite loop. Let's take a few examples to understand this.

▶ In the for loop construct, if you don't specify the test condition ( check_condition ), it's assumed to be true by default.

As a result, your condition never becomes false. And the loop will keep running forever until you force stop the program.

This is shown in the code snippet below:

▶ Here's another example.

You initialize the counter variable i to 10. And i increases by 1 after every iteration.

Notice how the test condition is i > 0 . Won't the value of i be always greater than 0?

So you have another infinite loop, as shown:

▶ In this example, your counter variable i is initialized to 0 . But it decreases by 1 with every iteration.

As a result, i always less than 10. So the condition i < 10 is always true , and you'll have an infinite loop.

To avoid running into infinite loops, you should define the looping condition correctly.

If you're a beginner, asking yourself the following questions may help.

What do I want this loop to do? How many times do I want the loop to run? When should my loop stop?

And then you can go ahead and define your loop construct accordingly. 🙂

I hope you found this tutorial helpful.

To sum up, you've learned the syntax of for loops and how they work. You also know how to anticipate the possibility of infinite for loops and how to avoid them by defining your looping condition carefully.

See you all soon in another tutorial. Until then, happy coding!

I am a developer and technical writer from India. I write tutorials on all things programming and machine learning.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • Understanding do...while loop in C
  • If...else statement in C Programming
  • If Statement in C
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Arithmetic Operators in C Programming
  • Relational Operators in C Programming
  • C Programming Assignment Operators
  • Logical Operators in C Programming
  • Understanding for loop in C
  • if else if statements in C Programming
  • Beginner's Guide to C Programming
  • First C program and Its Syntax
  • Escape Sequences and Comments in C
  • Keywords in C: List of Keywords
  • Identifiers in C: Types of Identifiers
  • Data Types in C Programming - A Beginner Guide with examples
  • Variables in C Programming - Types of Variables in C ( With Examples )
  • 10 Reasons Why You Should Learn C
  • Boolean and Static in C Programming With Examples ( Full Guide )
  • Operators in C: Types of Operators
  • Bitwise Operators in C: AND, OR, XOR, Shift & Complement
  • Expressions in C Programming - Types of Expressions in C ( With Examples )
  • Conditional Statements in C: if, if..else, Nested if
  • Switch Statement in C: Syntax and Examples
  • Ternary Operator in C: Ternary Operator vs. if...else Statement

Loop in C with Examples: For, While, Do..While Loops

  • Nested Loops in C - Types of Expressions in C ( With Examples )
  • Infinite Loops in C: Types of Infinite Loops
  • Jump Statements in C: break, continue, goto, return
  • Continue Statement in C: What is Break & Continue Statement in C with Example

03 Intermediate

  • Getting Started with Data Structures in C
  • Constants in C language
  • Functions in C Programming
  • Call by Value and Call by Reference in C
  • Recursion in C: Types, its Working and Examples
  • Storage Classes in C: Auto, Extern, Static, Register
  • Arrays in C Programming: Operations on Arrays
  • Strings in C with Examples: String Functions

04 Advanced

  • How to Dynamically Allocate Memory using calloc() in C?
  • How to Dynamically Allocate Memory using malloc() in C?
  • Pointers in C: Types of Pointers
  • Multidimensional Arrays in C: 2D and 3D Arrays
  • Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • C Programming Course
  • Data Structures and Algorithms Training
  • Loop In C With Examples: ..

Loop in C with Examples: For, While, Do..While Loops

C Programming For Beginners Free Course

Loop in c: an overview.

Are you interested in programming but don't know where to start? Have you ever heard the term loop ? Looping is one of the key concepts behind programming, and learning how to use  Loop  in C can open up a new world of code. Gain the foundational skills from this C tutorial and move to the advanced  C training thatincludes in-depth coverage of loop  and other essential programming concepts.

Read More - Top 50 C Interview Questions and Answers

What are Loop in C?

Loops are a block of code that executes itself until the specified condition becomes false. In this section, we will look in detail at the types of loops used in C programming .

What is the Need for Looping Statements in C?

Here are some uses of loops in C:

  • Loops allow the user to execute the same set of statements repeatedly without writing the same code multiple times.
  • It saves time and effort and increases the efficiency .
  • It reduces the chance of getting errors during compilation.
  • Loop makes the code readable and easier to understand, especially when dealing with complex logic or large data sets.
  • It promotes code reusability .
  • Loops help traverse data structures like arrays or linked lists

c problem solving for loop

Types of Loop in C

  • do while loop

for loop in C

A for loop is a control structure that enables a set of instructions to get executed for a specified number of iterations. It is an entry-controlled loop.

for loop Flowchart

for loop in C

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Java Programming Course

  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

C Functions

C structures, c reference.

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example explained

Expression 1 sets a variable before the loop starts (int i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Expression 3 increases a value (i++) each time the code block in the loop has been executed.

C Exercises

Test yourself with exercises.

Use a for loop to print "Yes" 5 times:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Programmingoneonone - Programs for Everyone

Programmingoneonone - Programs for Everyone

  • HackerRank Problems Solutions
  • _C solutions
  • _C++ Solutions
  • _Java Solutions
  • _Python Solutions
  • _Interview Preparation kit
  • _1 Week Solutions
  • _1 Month Solutions
  • _3 Month Solutions
  • _30 Days of Code
  • _10 Days of JS
  • CS Subjects
  • _IoT Tutorials
  • DSA Tutorials
  • Interview Questions

HackerRank For Loop in C programming problem solution

In this HackerRank For loop in c programming problem solution , In this challenge, you will learn the usage of the for loop, which is a programming language statement which allows code to be executed until a terminal condition is met. They can even repeat forever if the terminal condition is never met.

The syntax for the for loop is:

for ( <expression_1> ; <expression_2> ; <expression_3> )

    <statement>

expression_1 is used for intializing variables which are generally used for controlling the terminating flag for the loop.

expression_2 is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.

expression_3 is generally used to update the flags/variables.

The following loop initializes i to 0, tests that i is less than 10, and increments i at every iteration. It will execute 10 times.

for(int i = 0; i < 10; i++) {

    ...

For each integer [a,b] in the interval  (given as input) :

  • If 1 <= n <= 9, then print the English representation of it in lowercase. That is "one" for 1, "two" for 2, and so on.
  • Else if n > 9 and it is an even number, then print "even".
  • Else if n > 9 and it is an odd number, then print "odd".

HackerRank For Loop in C programming solution

HackerRank For loop in c programming problem solution.

Second solution

YASH PAL

Posted by: YASH PAL

You may like these posts, post a comment.

c problem solving for loop

anyone can explain this problem for me guys pls pls

what if the b value is smaller than value a ? the loop won't run isn't it?

In the second solution

  • 10 day of javascript
  • 10 days of statistics
  • 30 days of code
  • Codechef Solutions
  • coding problems
  • data structure
  • hackerrank solutions
  • interview prepration kit
  • linux shell

Popular Posts

HackerRank Trees: Is This a Binary Search Tree? solution

HackerRank Trees: Is This a Binary Search Tree? solution

HackerRank Lily's Homework problem solution

HackerRank Lily's Homework problem solution

HackerRank Minimum Distance problem solution

HackerRank Minimum Distance problem solution

c problem solving for loop

37 C Programs and Code Examples on Loops

  • Home > C Programs > C Loop programs
  • « Previous
  • Next »
  • C Loop Programs
  • Print 1 to 15 numbers
  • Print 10 to 1 numbers
  • Sum of first n even numbers
  • Print factorial of a number
  • Number perfectly dividing given number
  • Square roots of 1 to 9 numbers
  • Numbers not divisible by 2, 3, 5
  • Harmonic sequence & its sum
  • Arithmetic progression & its sum
  • Exponential series & its sum
  • Sum of Expanded Geometric Sequence
  • Print right angle triangle pattern
  • Print number pyramid pattern
  • Print mixed right angle triangle
  • Print inverted right angle triangle
  • Print alphabet right angle triangle
  • Print numbered inverted right angle triangle
  • Print alphabet triangle pattern
  • Print number triangle pattern
  • Print star pyramid pattern
  • Sum of first & last digit of number
  • Sum of all digits of number
  • Print reverse of a number
  • Armstrong number
  • Calculate sum of Fibonacci series
  • Calculate H.C.F using while loop
  • Check number is prime or not
  • Print series skipping given numbers
  • Add even & odd numbers
  • Print total marks of student
  • Sum of all +ve & -ve numbers
  • Print odd number right angle triangle
  • Print alphabetic right angle triangle
  • Check if number is palindrome
  • Display each digit in words
  • Print numeric inverted right angle triangle
  • Count zero, odd & even digits

C Programs and Code Examples on Loops

List of c programs and code examples on loops covered here, for whom are these c programs and code examples on loops useful, related topics.

  • C Formula based
  • C Decision and Loop
  • C Structure and Union
  • C Files I/O
  • C Linked List
  • C Binary Search

"Hello World!" in C Easy C (Basic) Max Score: 5 Success Rate: 85.72%

Playing with characters easy c (basic) max score: 5 success rate: 84.41%, sum and difference of two numbers easy c (basic) max score: 5 success rate: 94.63%, functions in c easy c (basic) max score: 10 success rate: 96.01%, pointers in c easy c (basic) max score: 10 success rate: 96.59%, conditional statements in c easy c (basic) max score: 10 success rate: 96.95%, for loop in c easy c (basic) max score: 10 success rate: 93.76%, sum of digits of a five digit number easy c (basic) max score: 15 success rate: 98.67%, bitwise operators easy c (basic) max score: 15 success rate: 94.98%, printing pattern using loops medium c (basic) max score: 30 success rate: 95.95%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

Guru99

Loops in C: For, While, Do While looping Statements [Examples]

Barbara Thompson

What is Loop in C?

Looping Statements in C execute the sequence of statements many times until the stated condition becomes false. A loop in C consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. The purpose of the C loop is to repeat the same code a number of times.

Types of Loops in C

Depending upon the position of a control statement in a program, looping statement in C is classified into two types:

1. Entry controlled loop

2. Exit controlled loop

In an entry control loop in C, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop.

In an exit controlled loop , a condition is checked after executing the body of a loop. It is also called as a post-checking loop.

Types of Loops in C

The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. The loop that does not stop executing and processes the statements number of times is called as an infinite loop . An infinite loop is also called as an “ Endless loop .” Following are some characteristics of an infinite loop:

1. No termination condition is specified.

2. The specified conditions never meet.

The specified condition determines whether to execute the loop body or not.

‘C’ programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop

Sr. No. Loop Type Description
1. While Loop In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed.
2. Do-While Loop In a do…while loop, the condition is always executed after the body of a loop. It is also called an exit-controlled loop.
3. For Loop In a for loop, the initial value is performed only once, then the condition tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.

While Loop in C

A while loop is the most straightforward looping structure. While loop syntax in C programming language is as follows:

Syntax of While Loop in C

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly braces even we have a single statement in the body.

In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do while loop which we will see shortly.

Following program illustrates while loop in C programming example:

The above program illustrates the use of while loop. In the above program, we have printed series of numbers from 1 to 10 using a while loop.

While Loop in C

  • We have initialized a variable called num with value 1. We are going to print from 1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign the value 0 during initialization.
  • In a while loop, we have provided a condition (num<=10), which means the loop will execute the body until the value of num becomes 10. After that, the loop will be terminated, and control will fall outside the loop.
  • In the body of a loop, we have a print function to print our number and an increment operation to increment the value per execution of a loop. An initial value of num is 1, after the execution, it will become 2, and during the next execution, it will become 3. This process will continue until the value becomes 10 and then it will print the series on console and terminate the loop.

Do-While loop in C

A do…while loop in C is similar to the while loop except that the condition is always executed after the body of a loop. It is also called an exit-controlled loop.

Syntax of do while loop in C programming language is as follows:

Syntax of Do-While Loop in C

As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)

The following loop program in C illustrates the working of a do-while loop:

Below is a do-while loop in C example to print a table of number 2:

In the above example, we have printed multiplication table of 2 using a do-while loop. Let’s see how the program was able to print the series.

Do-While loop in C

  • First, we have initialized a variable ‘num’ with value 1. Then we have written a do-while loop.
  • In a loop, we have a print function that will print the series by multiplying the value of num with 2.
  • After each increment, the value of num will increase by 1, and it will be printed on the screen.
  • Initially, the value of num is 1. In a body of a loop, the print function will be executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on until the value of num becomes 10. After that loop will be terminated and a statement which is immediately after the loop will be executed. In this case return 0.

For loop in C

A for loop is a more efficient loop structure in ‘C’ programming. The general structure of for loop syntax in C is as follows:

Syntax of For Loop in C

  • The initial value of the for loop is performed only once.
  • The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
  • The incrementation/decrementation increases (or decreases) the counter by a set value.

Following program illustrates the for loop in C programming example:

The above program prints the number series from 1-10 using for loop.

For loop in C

  • We have declared a variable of an int data type to store values.
  • In for loop, in the initialization part, we have assigned value 1 to the variable number. In the condition part, we have specified our condition and then the increment part.
  • In the body of a loop, we have a print function to print the numbers on a new line in the console. We have the value one stored in number, after the first iteration the value will be incremented, and it will become 2. Now the variable number has the value 2. The condition will be rechecked and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.

In C, the for loop can have multiple expressions separated by commas in each part.

For example:

Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.

Notice that loops can also be nested where there is an outer loop and an inner loop. For each iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example with multiple conditions in for loop, that uses nested for loop in C programming to output a multiplication table:

The nesting of for loops can be done up-to any level. The nested loops should be adequately indented to make code readable. In some versions of ‘C,’ the nesting is limited up to 15 loops, but some provide more.

The nested loops are mostly used in array applications which we will see in further tutorials.

Break Statement in C

The break statement is used mainly in the switch statement . It is also useful for immediately stopping a loop.

We consider the following program which introduces a break to exit a while loop:

Continue Statement in C

When you want to skip to the next iteration but remain in the loop, you should use the continue statement.

So, the value 5 is skipped.

Which loop to Select?

Selection of a loop is always a tough task for a programmer, to select a loop do the following steps:

  • Analyze the problem and check whether it requires a pre-test or a post-test loop.
  • If pre-test is required, use a while or for a loop.
  • If post-test is required, use a do-while loop.
  • Define loop in C: A Loop is one of the key concepts on any Programming language . Loops in C language are implemented using conditional statements.
  • A block of loop control statements in C are executed for number of times until the condition becomes false.
  • Loops in C programming are of 2 types: entry-controlled and exit-controlled.
  • List various loop control instructions in C: C programming provides us 1) while 2) do-while and 3) for loop control instructions.
  • For and while loop C programming are entry-controlled loops in C language.
  • Do-while is an exit control loop in C.
  • Dynamic Memory Allocation in C using malloc(), calloc() Functions
  • Type Casting in C: Type Conversion, Implicit, Explicit with Example
  • C Programming Tutorial PDF for Beginners
  • 13 BEST C Programming Books for Beginners (2024 Update)
  • Difference Between C and Java
  • Difference Between Structure and Union in C
  • Top 100 C Programming Interview Questions and Answers (PDF)
  • calloc() Function in C Library with Program EXAMPLE

Codersdaily-logo

  • Create Account

Codersdaily-logo

Book a FREE live class. NOW!

Fill your details and select a date for your live class

c problem solving for loop

HackerRank C Program Solutions Tutorial

  • "Hello World!" in C HackerRank Solution
  • Playing With Characters HackerRank Solution
  • Sum and Difference of Two Numbers HackerRank Solution
  • Functions in C HackerRank Solution
  • Pointers in C HackerRank Solution
  • Conditional Statements in C HackerRank Solution

For Loop in C Solution

  • Sum of Digits of a Five Digit Number HackerRank Solution
  • Bitwise Operators HackerRank Solution
  • Printing Pattern Using Loops HackerRank Solution
  • Variadic functions in C HackerRank Solution
  • HackerRank 1D Arrays in C Solutions
  • Array Reversal in C HackerRank Solution
  • Printing Tokens HackerRank Solution
  • Digit Frequency HackerRank Solution
  • Dynamic Array in C HackerRank Solution
  • Calculate the Nth term HackerRank Solution
  • Students Marks Sum HackerRank Solution
  • Sorting Array of Strings HackerRank Solution
  • Permutations of Strings HackerRank Solution
  • Querying the Document HackerRank Solution
  • Boxes through a Tunnel HackerRank Solution
  • Small Triangles, Large Triangles HackerRank Solution
  • Post Transition HackerRank Solution
  • Structuring the Document HackerRank Solution

HackerRank Solutions in C

In this challenge, you will learn the usage of the for loop, which is a programming language statement which allows code to be executed until a terminal condition is met. They can even repeat forever if the terminal condition is never met.

The syntax for the for loop is:

expression_1 is used for intializing variables which are generally used for controlling the terminating flag for the loop.

expression_2 is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.

expression_3 is generally used to update the flags/variables.

The following loop initializes i to 0, tests that i is less than 10, and increments i at every iteration. It will execute 10 times.

For each integer n in the interval [a,b] (given as input) :

If 1<=n<=9, then print the English representation of it in lowercase. That is “one” for 1, “two” for 2, and so on.

Else if n>9 and it is an even number, then print “even”.

Else if n>9 and it is an odd number, then print “odd”.

Input Format

The first line contains an integer, a.

The seond line contains an integer, b.

Constraints

1<=a<=b<=10^6

Output Format

Print the appropriate English representation,even, or odd, based on the conditions described in the ‘task’ section.

Note : [a,b] = {x ∈ Z | a <= x <= b} = {a, a+1,....,b}

Sample Input

Sample Output

Steps Used in solving the problem -

Step 1:  First, we imported the required libraries.

Step 2:  Then, we declared the main function. Inside our function, we declared two integer variables. We have also used the scanf function to take inputs for our declared variables.

Step 3 : Then, we created a For loop that iterates from the value of variable "a" to the value of variable "b" (inclusive)

Step 4 : Then, we used a switch statement to print the corresponding word for the input number. This will also check if the number is even or odd.

c problem solving for loop

Important Links

Trainings :

Free Courses and Resource :

Interview Questions :

Top Colleges in India :

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Basic trouble with for-loop in C

I'm incredibly new to C programming [last night my husband decided to make me turn an assignment in pseudo-code into a working C program...] so I apologize for how simple this might be. I'm also new to stackoverflow, so please let me know if I've made any basic mistakes.

I've written the following:

But I ran it with the numbers (2,4) and (2,8) and the result comes out 4 no matter what. Where is my mistake?

faerubin's user avatar

  • 5 Your mistake is that you didn't make any effort to go through a basic C language guide and you didn't debug your code. –  user529758 Commented Nov 13, 2013 at 7:47
  • 1 Why assign after if(m==0) ? you know the answer if m is 0, so just return it: if(m == 0) return 1; and if(m == 1) return n; –  Elias Van Ootegem Commented Nov 13, 2013 at 7:50
  • You may want to use ready C method called pow(). Please see tutorialspoint.com/c_standard_library/c_function_pow.htm –  Kamil Wozniak Commented Nov 13, 2013 at 7:51
  • @kamilw Naw, that's for floating-point values. You do not want to use it for integer operations. –  user529758 Commented Nov 13, 2013 at 10:26
  • @H2CO3 Good point, thank You. :) –  Kamil Wozniak Commented Nov 13, 2013 at 11:00

6 Answers 6

is equivalent to

You need to remove the ; from the end of your for statements.

You also need to use == for comparison. m=0 assigns 0 to m then returns 0 , causing your if condition to fail.

simonc's user avatar

Right, a couple of things, first those others have adressed in their answer, too:

  • you're using the assignment operator when you want the comparison operator: = assigns, == compares.
  • A semi-colon is the end of a statement, ; is an empty, yet valid statement so if(m ==0); is saying: "if m is 0, do nothing" . Your for loop suffers from the same issue.
  • As I said in my comment: why assign if you know the answer: if(m==0) result = 1; is a tad redundant, IMHO, I'd just write if (m == 0) return 1;

Now, something else: You're computing an int, to the power of another int. Technically, 2^33 should be "computable" , but an int simply isn't big enough. Here's an alternative suggestion:

I've also removed the if (exp == 1) , as the way the loop is written, it can now deal with that. Statements worth explaining:

I've changed the function's signature a bit: it now returns a long long value, to accomodate the larger values, which a power of -function may return. I've also declared the second argument to be an unsigned int , to avoid having to deal with negative powers. Your function wasn't ready for that, but you didn't check to see if m < 0 , you just assumed it was valid input.

Note: No semi-colon after the closing parentheses

This will promote the int to a long long value, and automatically assigns i^1 to result .

There's a lot going on here. For a start, the loop begins with --exp , which is the same as exp -= 1 , or exp = exp -1; . The condition for the loop to continue is simply exp . This evaluates to false if exp is 0. Suppose exp was 1, then beginning the loop automatically sets exp to 0, and the loop is never entered. If exp was > 1, then the loop continues, decrementing exp until it, too, reaches zero. On each iteration result *= i; , which is short for result = result * i is computed. After all this is done, return result returns a long long value...

As H2CO3 pointed out, this snippet can be simplified even more:

Instead of checking for an exp == 0 , just assigning 1 to result from the get-go, and taking things from there will do just fine... Note that for(;exp;--exp) isn't a typo. The first semicolon has to be present, but there's no expression that needs evaluating there. If you find for (exp;exp;--exp) , that works, too.

Note: By no means is this function "ready for production" , this is just a basic example of how one might calculate i1^i2 , for a more complete example of a pow function, have a look here , and see if you can work out how the code works. You'll probably need some more info, and perhaps a book on the C language, though

Elias Van Ootegem's user avatar

  • 1 you don't need to check the exponent for 0 explicitly. Just assign 1 to the result, then iterate from 0 to the exponent, multiplyijg the result with the base. –  user529758 Commented Nov 13, 2013 at 10:28
  • @H2CO3: Right indeed. I was too hung up on not assigning unless I was really going to use the var, I didn't think about that. Added a shortened version of the calc_power function without the if 's –  Elias Van Ootegem Commented Nov 13, 2013 at 10:41

Also for-loop

You're for-loop will run from i = 2 to m incrementing, but it cannot reflect what logic intended to perform under it.

Sunil Bojanapally's user avatar

Your problem is here:

You need to remove the ; from the end of this line; at the moment, it's just effectively this:

Leigh's user avatar

  • Semicolon ends the statement;

if ( / * Some condition * /);

basically mean if(/*whatever*/) do ; i.e. nothing instead of

= is assignment, == is equal to tester

This means assign 1 to m Assignment operator returns the RHS so it turns into

which means if(true)

Suvarna Pattayil's user avatar

if(m = 0); means you are assigning 0 to the variable m so it will never be true.also you are putting a ';' in your if statement so the statement after the if will not be affected by the condition.

R R's user avatar

  • No, assigning 0 means it will never be true. –  unwind Commented Nov 13, 2013 at 8:21
  • @unwind ah sorry that was a silly mistake.i updated my answer.you are right assigning 0 means the condition will always be false. –  R R Commented Nov 13, 2013 at 8:43

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c for-loop or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • if people are bred like dogs, what can be achieved?
  • Is there a category even more general than "thing"?
  • Voronoi mesh of a circular image
  • Where did the pronunciation of the word "kilometer/kilometre" as "kl OM iter" rather than "KILL o meeter" originate?
  • Clear jel to thicken the filling of a key lime pie?
  • How to create a flow that checks the overlaping dates on records?
  • When should a function be given an argument vs getting the data itself?
  • Can apophatic theology offer a coherent resolution to the "problem of the creator of God"?
  • What does it mean for observations to be uncorrelated and have constant variance?
  • Would a PhD from Europe, Canada, Australia, or New Zealand be accepted in the US?
  • Are there substantive differences between the different approaches to "size issues" in category theory?
  • Do I need to staple cable for new wire run through a preexisting wall?
  • What are some plausible means for increasing the atmospheric pressure on a post-apocalyptic earth?
  • What is a curate in English scone culture?
  • What is the purpose of the M1 pin on a Z80
  • What is the safest way to camp in a zombie apocalypse?
  • Binary Slashes Display
  • What is the meaning of "Wa’al"?
  • What kind of publications can i submit on my own without the need of supervisors approval?
  • Is this professor being unnecessarily harsh or did I actually make a mistake?
  • Comprehensive Guide to saying Mourners' Kaddish
  • A TCP server which uses one thread to read while writing data with another thread
  • TikZ - diagram of a 1D spin chain
  • Identifying the order of the output

c problem solving for loop

  • C Programming Home
  • ▼C Programming Exercises
  • Basic Declarations and Expressions
  • Basic Part-II
  • Basic Algorithm
  • Variable Type
  • Input - Output
  • Conditional Statements
  • Do-While Loop
  • Linked List
  • Callback function
  • Variadic function
  • Inline Function
  • File Handling
  • Searching and Sorting
  • C Programming Exercises, Practice, Solution

What is C Programming Language?

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs. It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C programming.

Hope, these exercises help you to improve your C programming coding skills. Currently, following sections are available, we are working hard to add more exercises. Please refer to this page for important C snippets, code, and examples before starting the exercises. Happy Coding!

List of C Programming Exercises :

  • Basic Declarations and Expressions [ 150 Exercises with Solution ]
  • Basic Part-II [ 7 Exercises with Solution ]
  • Basic Algorithm [ 75 Exercises with Solution ]
  • Variable Type [ 18 Exercises with Solution ]
  • Input, Output [ 10 Exercises with Solution ]
  • Conditional Statement [ 26 Exercises with Solution ]
  • While Loop [ 11 Exercises with Solution ]
  • Do-While Loop [ 12 Exercises with Solution ]
  • For Loop [ 61 Exercises with Solution ]
  • Array [ 107 Exercises with Solution ]
  • Structure [ 9 Exercises with Solution ]
  • Pointer [ 22 Exercises with Solution ]
  • Linked List [ 64 Exercises with Solution ]
  • Stack [ 17 Exercises with Solution ]
  • Binary Heap (Tree-Based Structure) [ 9 Exercises with Solution ]
  • Queue [ 13 Exercises with Solution ]
  • Hash [ 10 Exercises with Solution ]
  • Tree [ 10 Exercises with Solution ]
  • Graph [ 10 Exercises with Solution ]
  • Numbers [ 38 Exercises with Solution ]
  • Math [ 38 Exercises with Solution ]
  • String [ 41 Exercises with Solution ]
  • Date Time [ 10 Exercises with Solution ]
  • Function [ 12 Exercises with Solution ]
  • Callback Function [ 11 Exercises with Solution ]
  • Variadic Function [ 8 Exercises with Solution ]
  • Inline Function [ 11 Exercises with Solution ]
  • Recursion [ 21 Exercises with Solution ]
  • File Handling [ 19 Exercises with Solution ]
  • Search and Sorting [ 31 Exercises with Solution ]
  • Challenges [ 35 exercises with solution ]
  • C Snippets [29]
  • More to Come !

[ Want to contribute to C exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Popularity of Programming Language Worldwide, Nov 2023 compared to a year ago:

`
Rank Change Language Share Trend
1 Python 27.99 % +0.0 %
2 Java 15.91 % -0.8%
3 Javascript 9.18 % -0.3%
4 C/C++ 6.76 % +0.2%
5 C# 6.67 % -0.3 %
6 PHP 4.86 % -0.3 %
7 R 4.45% +0.4%
8 TypeScript 2.95 % +0.1%
9 Swift 2.7 % +0.6%
10 Objective-C 2.32% +0.2%
11 Rust1.98% +0.3%
12 Go 1.98% -0.0%
13 Kotlin 1.76 % -0.1%
14 Matlab 1.6 % +0.0%
15 Ada 1.02% +0.2%
16 Ruby 1.0 % -0.1 %
17 Dart 0.99 % +0.1 %
18 Powershell 0.93 % +0.0 %
19 VBA 0.93 % -0.1 %
20 Scala 0.62 % -0.1 %
21 Lua 0.62 % 0.0 %
22 Abap 0.58 % +0.1 %
23 Visual Basic 0.55 % -0.1 %
24 Julia 0.35 % -0.0 %
25 Groovy 0.31 % -0.1 %
26 Perl 0.31 % -0.1 %
27 Haskell 0.27 % -0.0 %
28 Cobol 0.25 % -0.1 %
29 Delphi/Pascal 0.18 % +0.2 %

Source : https://pypl.github.io/PYPL.html

TIOBE Index for November 2023

Nov 2023 Nov 2022 Change Programming Language Ratings Change
1 1 Python 14.16% -3.02%
2 2 C 11.77% -3.31%
3 4 C++ 10.36% -0.39%
4 3 Java 8.35% -3.63%
5 5 C# 7.65% +3.40%
6 7 JavaScript 3.21% +0.47%
7 10 PHP 2.30% +0.61%
8 6 Visual Basic 2.10% -2.01%
9 9 SQL 1.88% +0.07%
10 8 Assembly language 1.35% -0.83%
11 17 Scratch 1.31% +0.43%
12 24 Fortran 1.30% +0.74%
13 11 Go 1.19% +0.05%
14 15 MATLAB 1.15% +0.14%
15 28 Kotlin 1.15% +0.68%
16 14 Delphi/Object Pascal 1.14% +0.07%
17 18 Swift 1.04% +0.17%
18 19 Ruby 0.99% +0.14%
19 12 R 0.93% -0.20%
20 20 Rust 0.91% +0.16%

Source : https://www.tiobe.com/tiobe-index/

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Codeforwin

C programming examples, exercises and solutions for beginners

Fundamentals.

  • Hello world program in C
  • Basic input/output
  • Basic IO on all data types
  • Perform arithmetic operations
  • Find area and perimeter of rectangle
  • Find diameter and area of circle
  • Find area of triangle
  • Find angles of triangle
  • Temperature conversion
  • Length conversion
  • Days conversion
  • Find power of a number
  • Find square root
  • Calculate simple interest
  • Calculate compound interest
  • Find range of data types

Bitwise Operator

  • Check Least Significant Bit (LSB)
  • Check Most Significant Bit (MSB)
  • Get nth bit of a number
  • Set nth bit of a number
  • Clear nth bit of a number
  • Toggle nth bit of a number
  • Highest set bit of a number
  • Lowest set bit of a number
  • Count trailing zeros of binary number
  • Count leading zeros of binary number
  • Flip bits of a number
  • Rotate bits of a number
  • Decimal to binary
  • Swap two numbers
  • Check even or odd
  • View all Bitwise operator examples →

Ternary Operator

  • Maximum of two numbers
  • Maximum of three numbers
  • Check leap year
  • Check alphabet
  • View all ternary operator examples →
  • Find maximum of two numbers
  • Find maximum of three numbers
  • Check negative, positive or zero
  • Check divisibility
  • Check alphabet character
  • Check vowel or consonant
  • Check alphabet, digit or special character
  • Check uppercase or lowercase
  • Print day of week
  • Find number of days in month
  • Find roots of quadratic equation
  • Calculate profile/loss
  • View all if else examples →

Switch case

  • Find total days in month
  • Check positive, negative or zero
  • Simple calculator application
  • View all switch case examples →

Loop/Iteration

  • Print natural numbers from 1 to n
  • Print alphabets from a to z
  • Print even numbers from 1 to n
  • Print sum of all numbers from 1 to n
  • Print sum of all odd numbers from 1 to n
  • Print multiplication table of n
  • Find number of digits in a number
  • Find first and last digit
  • Find sum of first and last digit
  • Swap first and last digit
  • Find sum of digits of a number
  • Find reverse of a number
  • Find frequency of digits in a number
  • Find power of a number using loop
  • Find factorial of a number
  • Find HCF of two numbers
  • Find LCM of two numbers
  • View all loop examples →

Number system and conversion

  • Find one's complement
  • Find two's complement
  • Binary to octal conversion
  • Binary to decimal conversion
  • Binary to hexadecimal conversion
  • Octal to binary conversion
  • Octal to decimal conversion
  • Octal to hexadecimal conversion
  • Decimal to binary conversion
  • Decimal to octal conversion
  • Decimal to hexadecimal conversion
  • Hexadecimal to binary conversion
  • Hexadecimal to octal conversion
  • Hexadecimal to decimal conversion
  • View all conversion examples →

Star patterns

  • Pascal triangle generation
  • Square star pattern
  • Hollow square star pattern
  • Hollow square star pattern with diagonal
  • Rhombus star pattern
  • Hollow rhombus star pattern
  • Right triangle star pattern
  • Hollow right triangle star pattern
  • Inverted right triangle star pattern
  • Mirrored inverted right triangle star pattern
  • Pyramid star pattern
  • Inverted pyramid star pattern
  • Diamond star pattern
  • Plus starpattern
  • X star pattern
  • 8 star pattern
  • Heart star with name pattern
  • View all star pattern examples →

Number patterns

  • Square number pattern
  • Right triangle number pattern
  • Inverted right triangle
  • Triangle with zero filled
  • Half diamond pattern
  • Half diamond star bordered pattern
  • X number pattern
  • View all number pattern examples →
  • Find cube using functions
  • Diameter & area of circle using functions
  • Maximum and minimum using functions
  • Check even odd using functions
  • Check Prime number using functions
  • Find all prime numbers using functions
  • Find all strong numbers using functions
  • Find all armstrong numbers using functions
  • Find all perfect numbers using functions
  • View all function examples →
  • Find power using recursion
  • Print natural numbers using recursion
  • Print even numbers using recursion
  • Sum of natural numbers using recursion
  • Sum of even/odd numbers using recursion
  • Find reverse using recursion
  • Check palindrome using recursion
  • Find sum of digits using recursion
  • Find factorial using recursion
  • Generate nth Fibonacci term using recursion
  • Find HCF (GCD) using recursion
  • Find LCM using recursion
  • Sum of array elements using recursion
  • View all recursion examples →
  • Input and display array elements
  • Sum of all array elements
  • Find second largest element in array
  • Copy one array to another
  • Insert new element in array
  • Delete an element from array
  • Find frequency of array elements
  • Merge two array to third array
  • Delete duplicate elements from array
  • Reverse an array
  • Search an element in array
  • Sort an array
  • Left rotate an array
  • Right rotate an array
  • View all array examples →

Matrix (2D array)

  • Add two matrices
  • Scalar matrix multiplication
  • Multiply two matrices
  • Check if two matrices are equal
  • Sum of diagonal elements of matrix
  • Interchange diagonal of matrix
  • Find upper triangular matrix
  • Find sum of lower triangular matrix
  • Find transpose of triangular matrix
  • Find determinant of a matrix
  • Check identity matrix
  • Check sparse matrix
  • Check symmetric matrix
  • View all matrix examples →
  • Find length of string
  • Copy string to another string
  • Concatenate two strings
  • Compare two strings
  • Convert lowercase to uppercase
  • Find reverse of a string
  • Check palindrome
  • Reverse order of words
  • Search a character in string
  • Search a word in string
  • Find highest occurring character
  • Remove all duplicate characters
  • Replace a character in string
  • Trim whitespace from string
  • View all string examples →
  • Create, initialize and use pointer
  • Add two numbers using pointers
  • Swap two numbers using pointers
  • Access array using pointers
  • Copy array using pointers
  • Reverse array using pointers
  • Access 2D array using pointers
  • Multiply matrices using pointers
  • Copy strings using pointers
  • Concatenate strings using pointers
  • Compare strings using pointers
  • Reverse strings using pointers
  • Sort array strings using pointers
  • Return multiple values from function using pointers
  • View all pointers examples →
  • Create file and write contents
  • Read file contents and display
  • Append contents to file
  • Compare two files
  • Copy one file to another
  • Merge two files
  • Remove a word from file
  • Remove a line from file
  • Replace a word in file
  • Replace a line in file
  • Print source code
  • Convert uppercase to lowercase in file
  • Find properties of file
  • Check if file or directory exists
  • Rename a file or directory
  • List of files recursively
  • View all files handling examples →

Macros/Pre-processor directives

  • Create custom header file
  • Define, undefine and redefine a macro
  • Find sum using macro
  • Find square and cube using macro
  • Check even/odd using macro
  • Find maximum or minimum using macro
  • Check lowercase/uppercase using macro
  • Swap two numbers using macro
  • Multiline macros

C Solved programs, problems with solutions – C programming

C solved programs, problems with solutions.

C Solved programs —->  C is a powerful general-purpose programming language. It is fast, portable and available in all platforms. If you are new to programming, C is a good choice to start your programming journey.

This page contains the C solved programs/examples with solutions, here we are providing most important programs on each topic . These C examples cover a wide range of programming areas in Computer Science.

Every example program includes the description of the program, C code as well as output of the program. All examples are compiled and tested on a Windows system.

These examples can be as simple and basic as “Hello World” program to extremely tough and advanced C programs. Here is the List of C solved programs/examples with solutions (category wise) and detailed explanation.

C Solved Programs by categories…….

C Basic Solved Programs
C Number Solved Programs
C String Solved Programs
C Arrays Solved Programs
C Matrix Solved Programs
C Pattern Solved Programs
C Sorting Solved Programs
C Recursion Solved Programs
C Pointer Solved Programs
C File Handling Solved Programs
C Graphic Solved Programs
C Advance Solved Programs

If you found any error or any queries related to the above programs or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.

Thanks for reading the post….

No related posts.

guest

(using file handling) Enter Country Name (Inida): india 5 states() Enter Name of State : Rajasthan Enter Name of capital : jaipur show the menu of jaipur city: 1. check college in city : 2. check school Name: Enter choice : 1 show list of all college in jaipur city(10): college Name address contact no Enter choice : 2 show list of all school in jaipur city(10): school Name address contact no

Suresh Ahlay

Write a program that reads a list of integers until a stopping condition is met and then print each test score together with Pass, if the score is greater than or equal to 60, and Fail otherwise.

mahesh minho

worst website

Mahedi Hasan

Write a C program to find the sum of contiguous sub array within an array which has the smallest sum. Also print where in the array the smallest sum occurred. For example, given the array [4, -1, 2, -3, 1, -2, 7, -5, 4], the contiguous sub-array [1, -3, -2] has the smallest sum of -4 and it occurred in [0:6]. To understand contiguous sub array, given the array [1, 2, 3] the contiguous sub arrays are [1], [2], [3], [1, 2], [2, 3], [1, 2, 3], but [1, 3] is not a contiguous sub array. Sample Input Sample Output

Malu

Consider an Auto spares store which has different categories of items like. Under each category, the shop holds a maximum capacity of 1000 items. The arrangement of items in the racks vary from time to time. Based on the item type and availability, the supplier also varies. Each supplier can supply different items. The system in the shopping mall has the complete description of list of all items which includes item number, name, category, supplier name, price, total quantity and qty available. Based on the items purchased by the customer, billing is done. From the above description, initially the owner …  Read more »

pradip sapkale

#include <stdio.h>

int   main () {   int    i ;   float   avg = 0 ,  sum = 0  , a [ 10 ];  

  printf ( “Enter 10 numbers” );   for  ( i = 0 ;  i <= 9 ;  i ++)   scanf ( “ %d “ , & a [ i ]);

  for  ( i = 0 ;  i <= 9 ;  i ++); {   sum = sum + a [ i ];   avg =  sum / 10.0 ; }   printf ( “average is  %f “ ,  avg );

return   0 ; }

the output averge is 0.00000 please help i’m beginer in c programming using visual studio code

Sanskruti Jagdhane

Try with this code ..

#include<stdio.h>

int main() {  int a[20],i ,n ;  float avg=0 , sum=0 ;

 printf(“Enter no of elements in array :\n “);  scanf(“%d”, &n);  printf(“\n Enter the array of element : \n”);

 for (i=1; i<=n; i++)  {    scanf(“%d”,&a[i]);  }   for (i=1; i<=n; i++)   {     sum=sum+a[i];     avg= sum/n;   }

 printf(“\n sum of elements :%f”,sum);  printf(“\n average is %f”, avg);

return 0; }

Akash

#include <stdio.h> int main(){ /*Short and Sweet Code, Working code Please check inverted commas while running this code.*/

  int value[10];   float Sum, Average;   for(int i=0; i<=9; i++){   printf(“Enter %d number: \n”, i+1);   scanf(“%d”, &value[i]);   }

  for(int i=0; i<=9; i++){

    Sum += value[i];      } Average = Sum/10;

printf(“Average of these 10 numbers is %f”, Average);     return 0; }

#include<stdio.h> int main() { /*You have made 2 mistakes in this program.*/  int  i;  float avg=0, sum=0 ,a[10];    printf(“Enter 10 numbers”);  for (i=0; i<=9; i++)  scanf(“ %d “, &a[i]); /*ERROR 1: %d should be replaced with %f in your program because you declared a[10] as a float so you cannot use %d.*/

 for (i=0; i<=9; i++) ; /*ERROR 2: In this Loop Remove this semicolon after the brackets.*/ {  sum=sum+a[i];  avg= sum/10.0; }  printf(“average is %f“, avg);

/*After Doing this correction your program will run without giving error OR zero.*/

return 0; }

Md Forhad Ali

Plz Solve this Programe

256676832_4608769575897180_2595566630400619699_n.png

ভাই পেয়েছেন

Denn Martin Delizo

Interest is compounded annually at 10% by a certain bank. Make a program that would input an amount and a number of years (the program should test that both are positive) and output how much the original amount will be worth after that period.  

Abhishek

It’s really a wonderful website💥

ratta

The Business organization has a problem that they encounter. They received complains about the orders they have that are inaccurate mostly in selection of orders, prices, and quantity of the products. They want to have system update as soon as possible to fix this problem and asking for a refund. Every order must be confirmed to avoid any conflicts of transaction. Also the discounts are not applied when the order are wholesales which is needed to be fix when being total. Certain products are discounted either from a voucher or a wholesale that is minimum of five products. The deduction of …  Read more »

Srija

To check whether the candidate is eligible for vote or not

Krishna mistry

(A) Create a C structure, volume with fields: liter and mililiter. Read the value of two volumes and add them, if the value of mililiter is more than 1000 then add it to liter value.

John

Write a c program for There are 20 workers working in a field. the owner of Field gives them 20 rupees. In that 20 rupees each man get 4 rupees each woman get 50 paise and each child get 25 paise. Then how many are men, women, children in that 20 workers?

Revathi

A vending machine questions

LARANYA SUBUDHI

1. Write a C program to print all odd numbers between 2 values ‘n’ and ‘m’. Read the values ‘n’ and ‘m’ from the user and print all the odd numbers in this range (inclusive range, i.e if ‘n’ or ‘m’ is odd, print those as well).

Basavaraj Metri

write a programming using for loop to print all the numbers from them as even m to n there by case classifying them as even or odd

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

Home » C programming language

C Programs with Solutions

This section contains popular C programs with solution. Learn and practice these programs to test and enhance your C skills. Last updated : April 01, 2023

The best way to learn C programming is by practicing and solving the C programs (C problems). We have 1000+ C programs with solutions which are categorized below. Practice these C programs to learn and enhance your C problem-solving skills.

List of C programs

Practice the C programs based on the categories, library functions, advanced, top searched, and latest.

C programs by categories

  • C Basic and Conditional Programs 90
  • C switch case programs 06
  • C 'goto' programs 10
  • Bitwise related Programs 32
  • Looping (for, while, do while) Programs 18
  • C String Manipulation programs 10
  • C String programs 50
  • String User Define Functions Programs 11
  • Recursion Programs 13
  • Number (Digits Manipulation) Programs 10
  • Number System Conversion Programs 15
  • Star/Pyramid Programs 17
  • Sum of Series Programs (set 1) 05
  • Sum of Series Programs (set 2) 13
  • Pattern printing programs 01
  • User Define Function Programs (1) 05
  • User Define Function Programs (2) 13
  • One Dimensional Array Programs 58
  • Two Dimensional Array (Matrix) Programs 21
  • File Handling Programs 32
  • Structure & Union Programs 12
  • Pointer Programs 13
  • Dynamic Memory Allocation Programs 05
  • Command Line Arguments Programs 06
  • Common C program Errors 22
  • C scanf() programs 11
  • C preprocessor programs 24
  • C typedef programs 03
  • C SQLite programs 11
  • C MySQL programs 09
  • C Tricky Programs 07
  • Misc Problems & Solutions 05

C programs on standard library functions

  • ctype.h Library Functions (Set 1)
  • ctype.h Library Functions (Set 2)
  • string.h Library Functions
  • conio.h Library Functions
  • dos.h Library Functions
  • math.h Library Functions
  • graphics.h Library Functions
  • assert.h Library Functions
  • stdio.h Library Functions

Advance C programs

  • C program to create your own header file/ Create your your own header file in C
  • gotoxy(),clrscr(),getch(),getche() for GCC, Linux.
  • fork() function explanation and examples in Linux C
  • C program to print character without using format specifiers.
  • C program to find Binary Addition and Binary Subtraction.
  • C program to print weekday of given date.
  • C program to format/extract ip address octets
  • C program to check given string is a valid IPv4 address or not.
  • C program to extract bytes from an integer (Hexadecimal) value
  • C program to store date in an integer variable

Top searched C programs

Here is the list of most important/useful programs searched on the web .

Top visited programs on IncludeHelp

  • Pattern Programs in C
  • C program to design calculator with basic operations using switch
  • C program to find factorial of a number
  • C program to check whether number is Perfect Square or not
  • C program to find SUM and AVERAGE of two numbers
  • C program to convert temperature from Fahrenheit to Celsius and Celsius to Fahrenheit
  • C program to read and print an employee's detail using structure
  • Dynamic Memory Allocation programs
  • C program to convert number from Decimal to Binary
  • C program to check whether number is Palindrome or not

Top searched programs on the web

  • First C program to print "Hello World".
  • C program to find factorial of a number.
  • C program to swap two numbers without using third variable.
  • C program to check whether a number if Armstrong or not.
  • C program to check whether a number if Even or Odd.
  • C program to print all leap years from 1 to N.
  • C program to calculate employee gross salary.
  • C Program to print tables of numbers from 1 to 20.
  • C program to print star/pyramid series.
  • C program to convert temperature from Celsius to Fahrenheit and vice versa.
  • C program to convert number from Decimal to Binary.
  • C program to convert number from Binary to Decimal.
  • C program to print ASCII Table.
  • C program to get and set current system date and time.
  • C program to run dos command.

Latest C programs

  • C program to generate random numbers within a range
  • C program to compare strings using strcmp() function
  • Interchange the two adjacent nodes in a given circular linked list | C program
  • Find the largest element in a doubly linked list | C program
  • Convert a given singly linked list to a circular list | C program
  • Implement Circular Doubly Linked List | C program
  • Print the Alternate Nodes in a Linked List without using Recursion
  • Print the Alternate Nodes in a Linked List using Recursion
  • Find the length of a linked list without using recursion
  • Find the length of a linked list using recursion
  • Count the number of occurrences of an element in a linked list without using recursion
  • Count the number of occurrences of an element in a linked list using recursion
  • C program to convert a Binary Tree into a Singly Linked List by Traversing Level by Level
  • C program to Check if nth Bit in a 32-bit Integer is set or not
  • C program to swap two Integers using Bitwise Operators
  • C program to replace bit in an integer at a specified position from another integer
  • C program to find odd or even number using bitmasking
  • C program to check whether a given number is palindrome or not using Bitwise Operator
  • C program to count number of bits set to 1 in an Integer
  • C program to check if all the bits of a given integer is one (1)
  • C program to find the Highest Bit Set for any given Integer
  • C program to Count the Number of Trailing Zeroes in an Integer
  • C Program to find the Biggest Number in an Array of Numbers using Recursion
  • C program to accept Sorted Array and do Search using Binary Search
  • C Program to Cyclically Permute the Elements of an Array
  • C program to find two smallest elements in a one dimensional array
  • Write your own memset() function in C
  • memset() function in C with Example
  • Write your own memcpy() function in C
  • memcpy() function in C with Example

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions
  • C++ Program to Solve the 0-1 Knapsack Problem
  • Python Program for Fractional Knapsack Problem
  • C Program for Subset Sum Problem | DP-25
  • C Program For Stock Buy Sell To Maximize Profit
  • C/C++ Dynamic Programming Programs
  • Space Optimized DP Solution for 0-1 Knapsack Problem in Java
  • C / C++ Program for Subset Sum | Backtracking-4
  • Python Program for 0-1 Knapsack Problem
  • Java Program 0-1 Knapsack Problem
  • Program to solve the Alligation Problem
  • C++ Program for the Fractional Knapsack Problem
  • 0/1 Knapsack Problem to print all possible solutions
  • Crossword Puzzle Of The Week #20 (KnapSack Problem)
  • 0/1 Knapsack Problem
  • Introduction to Knapsack Problem, its Types and How to solve them
  • A Space Optimized DP solution for 0-1 Knapsack Problem
  • 0-1 knapsack queries
  • Fractional Knapsack Problem
  • Extended Knapsack Problem

C Program to Solve the 0-1 Knapsack Problem

Prerequisite:   Introduction to Knapsack Problem, its Types and How to solve them

The 0-1 Knapsack Problem is a classic dynamic programming problem where the goal is to maximize the total value of ( N ) items, each having a weight and a value, that can be included in a knapsack with a maximum weight capacity ( W ) without exceeding its capacity. It differs from the fractional knapsack problem, where we can take fractions of items. In the 0-1 knapsack problem, we can either take an item completely or leave it.

To learn more about the 0-1 Knapsack Problem refer:  0/1 Knapsack Problem

Methods For Solving 0/1 Knapsack Problem

Recursion Approach for 0/1 Knapsack Problem

Memoization approach for 0/1 knapsack problem, tabulation or bottom-up approach for 0/1 knapsack problem.

The recursive approach is based on a idea of exploring all the combinations of items possible by including and excluding each item at every step and then decide to pick the subset having maximum value among all these subsets. To solve the 0-1 Knapsack problem using recursion we can follow the below approach:

Define a function that takes knapsack capacity W, number of items N, array of item weights and array of values as it’s parameters. If there are no items left i.e if n==0 or it the knapsack capacity is 0 i.e if W==0 then return 0. This will be the base case for the recursive function. If the weight of the current item is greater than the knapsack capacity, skip it and recursively call the function with remaining n-1 items. If the weight of the current item is less than or equal to the knapsack capacity, make two recursive calls: In the first one include the value of n-1th item and recursively call the function with reduced capacity W-weight[n-1] and n-1 items. In the second one exclude the current item and recursively call the function with unchanged capacity W and n-1 items. Return the maximum value obtained from the above recursive calls.

C Program for 0-1 Knapsack Problem Using Recursion

The following program illustrates how we can solve the 0-1 knapsack problem in C using recursion.

Time Complexity: O(2 N ) , where N is the total number of items. Auxiliary Space: O(N), considering the recursive stack space.

The recursion + memorization is a dynamic programming problem solving technique which is also known as Top-Down DP in which we optimize the recursive version of our solutions using an array to store the result of repeated subproblems from our recursive solution. To solve the 0-1 Knapsack problem using recursion+ memoization we can follow the below approach:

Create a 2-D array named dp with number of rows= maximum number of items and number of columns = maximum capacity of knapsack. Initialize the dp array with -1. If the value for any subproblem(n,w) is already computed that is if dp[n][w]!=-1 return dp[n][w]. Otherwise solve the problem using the recursive solution and store the result in dp[n][w].

C Program for 0-1 Knapsack Problem Using Memoization

The following program illustrates how we can solve the 0-1 knapsack problem in C using recursion + memorization.

Time Complexity: O(N*W), where N is the total number of items and W is the maximum capacity of the knapsack. Auxiliary Space: O(N*W)

Note: The code for this approach almost remains same as the recursive approach, only a 2D array is added to optimize the code.

The tabulation method is also a dynamic programming technique which is also known as Bottom-Up DP where we store the results of smaller subproblems into a table and then use the result of the smaller subproblems iteratively to solve the larger subproblems and find the actual result. To solve the 0-1 Knapsack problem using tabulation we can follow the below approach:

Create a 2D array dp of size (n+1)x(w+1), where dp[i][j] will store the maximum result for i items and j capacity of the knapsack. Initialize the dp[0][j] and dp[i][0] with 0 as the maximum profit will be 0 when either there are no items or the capacity of the knapsack is zero. For each item i from 1 to n and for each capacity w from 1 to j. If the weight of the current item wt[i-1] is less than or equal to w, then: dp[i][w] = max(val[i-1] + dp[i-1][w – wt[i-1]], dp[i-1][j]) Otherwise, if the weight of the current item is more than w, then: dp[i][j] = dp[i-1][j] (same value as without considering the current item) Return the value of dp[n][w] that will contain the maximum value that can be achieved with the full capacity W using all n items.

C Program for 0-1 Knapsack Problem Using Tabulation

The following program illustrates how we can solve the 0-1 knapsack problem in C using tabulation.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

ACM Digital Library home

  • Advanced Search

Global trajectory tracking for quadrotors: : An MRP-based hybrid strategy with input saturation

New citation alert added.

This alert has been successfully added and will be sent to:

You will be notified whenever a record that you have chosen has been cited.

To manage your alert preferences, click on the button below.

New Citation Alert!

Please log in to your account

Information & Contributors

Bibliometrics & citations, view options, recommendations, motion control and trajectory tracking control for a mobile robot via disturbance observer.

This paper investigates the tracking control of a wheeled mobile robot in the unknown environment. A disturbance observer is developed with utilization the integral filter. The proposed control scheme employs the disturbance observer control approach to ...

Finite-Time Sliding Mode Trajectory Tracking Control of Uncertain Mechanical Systems

The problem of finite-time tracking control is studied for uncertain nonlinear mechanical systems. To achieve finite-time convergence of tracking errors, a simple linear sliding surface based on polynomial reference trajectory is proposed to enable the ...

Trajectory tracking control for a marine surface vessel with asymmetric saturation actuators

This paper investigates the problem of trajectory tracking control for an unmanned marine surface vessel (MSV) with external disturbances and asymmetric saturation actuators. An adaptive radial basis function neural network (RBFNN) is constructed to ...

Information

Published in.

Pergamon Press, Inc.

United States

Publication History

Author tags.

  • Autonomous vehicles
  • Nonlinear control systems
  • Global stability
  • Input saturation
  • Trajectory tracking
  • Research-article

Contributors

Other metrics, bibliometrics, article metrics.

  • 0 Total Citations
  • 0 Total Downloads
  • Downloads (Last 12 months) 0
  • Downloads (Last 6 weeks) 0

View options

Login options.

Check if you have access through your login credentials or your institution to get full access on this article.

Full Access

Share this publication link.

Copying failed.

Share on social media

Affiliations, export citations.

  • Please download or close your previous search result export first before starting a new bulk export. Preview is not available. By clicking download, a status dialog will open to start the export process. The process may take a few minutes but once it finishes a file will be downloadable from your browser. You may continue to browse the DL while the export process is in progress. Download
  • Download citation
  • Copy citation

We are preparing your search results for download ...

We will inform you here when the file is ready.

Your file of search results citations is now ready.

Your search export query has expired. Please try again.

IMAGES

  1. C/C++ For loop with Examples

    c problem solving for loop

  2. For Loop in C Programming

    c problem solving for loop

  3. C_37 || for loop || C Language || iteration and loops in c

    c problem solving for loop

  4. Problem Solving in c++:Loop 1

    c problem solving for loop

  5. Problem solving through C (Problem 5)

    c problem solving for loop

  6. For Loop in C++ with Syntax & Program EXAMPLES

    c problem solving for loop

VIDEO

  1. C programming: For loops

  2. C language problem solution

  3. c problem solving #shortsvideo #virulshorts #coding #codewithharry #coding #python #dqtact

  4. #12 c problem solving #coding #cse #programming #python #iitbombay #virulshorts #clanguage

  5. FUNCTIONS OF C

  6. USER DEFINED DATA TYPE IN C

COMMENTS

  1. C programming exercises: For Loop

    Write a C program to convert a binary number into a decimal number without using array, function and while loop. Test Data : Input a binary number :1010101 Expected Output: The Binary Number : 1010101 The equivalent Decimal Number : 85 Click me to see the solution. 43. Write a C program to find the HCF (Highest Common Factor) of two numbers ...

  2. C for Loop (With Examples)

    In programming, a loop is used to repeat a block of code until the specified condition is met. C programming has three types of loops: for loop; while loop; do...while loop; We will learn about for loop in this tutorial. In the next tutorial, we will learn about while and do...while loop.

  3. Loop programming exercises and solutions in C

    List of loop programming exercises. Write a C program to print all natural numbers from 1 to n. - using while loop. Write a C program to print all natural numbers in reverse (from n to 1). - using while loop. Write a C program to print all alphabets from a to z. - using while loop.

  4. C++: For-loop

    Write a C++ program that displays the sum of n odd natural numbers. Sample Output: Input number of terms: 5 The odd numbers are: 1 3 5 7 9 The Sum of odd Natural Numbers upto 5 terms: 25 Click me to see the sample solution. 21. Write a C++ program that displays the sum of the n terms of even natural numbers. Sample Output: Input number of terms: 5

  5. C Exercises

    This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more. So, Keep it Up! Solve topic-wise C exercise questions to strengthen your weak topics.

  6. For Loops in C

    C for Loop Example. Let's write a simple for loop to count up to 10, and print the count value during each pass through the loop. In the above code snippet, count is the counter variable, and it's initialized to 0. The test condition here is count <= 10. Therefore, count can be at most 10 for looping to continue.

  7. C for Loop

    Step 1: Initialization is the basic step of for loop this step occurs only once during the start of the loop. During Initialization, variables are declared, or already existing variables are assigned some value. Step 2: During the Second Step condition statements are checked and only if the condition is the satisfied loop we can further process ...

  8. Loop in C with Examples: For, While, Do..While Loops

    Loops in C have a broad range of applications, from loop-driven algorithms to iterative problem-solving. As demonstrated, the syntax for using these loops is relatively straightforward, although their logic must be carefully explored to determine advantage and ease of use.

  9. C For Loop

    Example explained. Expression 1 sets a variable before the loop starts (int i = 0). Expression 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Expression 3 increases a value (i++) each time the code block in the loop has been executed.

  10. For Loop in C

    The syntax for the for loop is: for ( <expression_1> ; <expression_2> ; <expression_3> ) <statement>. expression_1 is used for intializing variables which are generally used for controlling the terminating flag for the loop. expression_2 is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.

  11. HackerRank For Loop in C programming problem solution

    In this HackerRank For loop in c programming problem solution, In this challenge, you will learn the usage of the for loop, which is a programming language statement which allows code to be executed until a terminal condition is met.They can even repeat forever if the terminal condition is never met. The syntax for the for loop is: for ( <expression_1> ; <expression_2> ; <expression_3> )

  12. 37 C Programs and Code Examples on Loops

    37 Solved Loops based C Programming examples with output, explanation and source code for beginners and professionals. Covers simple and and difficult programs on loops like for, do, while, do while etc. Useful for all computer science freshers, BCA, BE, BTech, MCA students.

  13. Practice C

    Improve your C programming skills with over 200 coding practice problems. Solve these beginner friendly problems online to get better at C language. Courses. Learn Python 10 courses ... Practice problems related to While Loops, For Loops and the concept of Break / Continue. Problem Name: Status: Difficulty: MCQ: Easy: MCQ: Easy: MCQ: Easy: MCQ ...

  14. Solve C

    For Loop in C. Easy C (Basic) Max Score: 10 Success Rate: 93.76%. Solve Challenge. Sum of Digits of a Five Digit Number. Easy C (Basic) Max Score: 15 Success Rate: 98.67%. ... Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  15. Loops in C: For, While, Do While looping Statements [Examples]

    1. While Loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. 2. Do-While Loop. In a do…while loop, the condition is always executed after the body of a loop. It is also called an exit-controlled loop. 3.

  16. HackerRank C Program Solutions Tutorial

    Steps Used in solving the problem -. Step 1: First, we imported the required libraries. Step 2: Then, we declared the main function. Inside our function, we declared two integer variables. We have also used the scanf function to take inputs for our declared variables.

  17. Basic trouble with for-loop in C

    result = i; This will promote the int to a long long value, and automatically assigns i^1 to result. for(--exp;exp;--exp) result *= i; There's a lot going on here. For a start, the loop begins with --exp, which is the same as exp -= 1, or exp = exp -1;. The condition for the loop to continue is simply exp.

  18. C programming Exercises, Practice, Solution

    C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs.

  19. For loop in Programming

    For Loop is a control flow statement that allows you to repeatedly execute a block of code based on a condition. It typically consists of an initialization, a condition, and an iteration statement. Types of For loop in C:In C, there is only one type of for loop, It consists of three main parts initialization, condition, and update. Syntax: for (ini

  20. C programming examples, exercises and solutions for beginners

    Matrix (2D array) Add two matrices. Scalar matrix multiplication. Multiply two matrices. Check if two matrices are equal. Sum of diagonal elements of matrix. Interchange diagonal of matrix. Find upper triangular matrix. Find sum of lower triangular matrix.

  21. C Solved programs, problems with solutions

    C Basic Solved Programs. C Program to Print Hello World Program. C Program to calculate a simple interest. C program to convert Total days to year, month and days. C program to find Sum and Average of two numbers. C Program to check whether number is EVEN or ODD. C Program to find largest number among three numbers.

  22. 1000+ C Programs (C Programming Examples)

    C Basic and Conditional Programs 90. C switch case programs 06. C 'goto' programs 10. Bitwise related Programs 32. Looping (for, while, do while) Programs 18. C String Manipulation programs 10. C String programs 50. String User Define Functions Programs 11. Recursion Programs 13.

  23. C Program to Solve the 0-1 Knapsack Problem

    Time Complexity: O(2 N), where N is the total number of items. Auxiliary Space: O(N), considering the recursive stack space. Memoization Approach for 0/1 Knapsack Problem. The recursion + memorization is a dynamic programming problem solving technique which is also known as Top-Down DP in which we optimize the recursive version of our solutions using an array to store the result of repeated ...

  24. For loops in C language

    For loop in C. A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop syntax in C is as follows: Syntax of For Loop in C: for (initial value; condition; modification) { statements; } The initial value of the for loop is performed only once. Page 1 of 3. Programming for Problem Solving Using C

  25. Global trajectory tracking for quadrotors: : An MRP-based hybrid

    The control strategy comprises an inner-loop that relies on a hybrid controller with integral action, designed based on the modified Rodrigues parameters attitude description, to solve the attitude tracking problem. The hybrid formulation of the controller benefits from the unique properties of the mentioned attitude description.