w3c
w3c
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Tutorial
❮ Home Next ❯
Learn C
C is a general-purpose programming language, developed in 1972, and still quite popular.
C is very powerful; it has been used to develop operating systems, databases, applications, etc.
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
We recommend reading this tutorial, in the sequence listed in the left menu.
C Exercises
int () {
("Hello World!");
return 0;
}
Submit Answer »
C Quiz
Learn by taking a quiz! The quiz will give you a signal of how much you know about C.
Start C Quiz
My Learning
Track your progress with the free "My Learning" program here at W3Schools.
This is an optional feature. You can study at W3Schools without using My Learning.
Learn by Examples
Learn by examples! This tutorial supplements all explanations with clarifying examples.
❮ Home Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Syntax
❮ Previous Next ❯
Syntax
You have already seen the following code a couple of times in the first chapters. Let's break it down to
understand it better:
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
Example explained
Line 1: #include <stdio.h> is a header file library that lets us work with input and output functions, such
as printf() (used in line 4). Header files add functionality to C programs.
Don't worry if you don't understand how #include <stdio.h> works. Just think of it as something that
(almost) always appears in your program.
Line 2: A blank line. C ignores white space. But we use it to make the code more readable.
Line 3: Another thing that always appear in a C program, is main() . This is called a function. Any code inside
its curly brackets {} will be executed.
Line 4: printf() is a function used to output/print text to the screen. In our example it will output "Hello
World!".
Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}
Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
C Exercises
Exercise:
Insert the missing part of the code below to output "Hello World!":
int () {
("Hello World!");
return 0;
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
C Statements
❮ Previous Next ❯
Statements
A computer program is a list of "instructions" to be "executed" by a computer.
The following statement "instructs" the compiler to print the text "Hello World" to the screen:
Example
printf("Hello World!");
Try it Yourself »
If you forget the semicolon ( ; ), an error will occur and the program will not run:
Example
printf("Hello World!")
Try it Yourself »
Many Statements
Most C programs contain many statements.
The statements are executed, one by one, in the same order as they are written:
Example
printf("Hello World!");
printf("Have a good day!");
return 0;
Try it Yourself »
Example explained
1. printf("Hello World!");
2. printf("Have a good day!");
3. return 0;
The first statement is executed first (print "Hello World!" to the screen).
Then the second statement is executed (print "Have a good day!" to the screen).
And at last, the third statement is executed (end the C program successfully).
You will learn more about statements while reading this tutorial. For now, just remember to always end them
with a semicolon to avoid any errors.
Coming up: The next chapter will teach you how to control the output and how to insert new lines to make it
more readable.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "" .
Example
Try it Yourself »
#include <stdio.h>
int main() {
printf("Hello World!");
printf("I am learning C.");
printf("And it is awesome!");
return 0;
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C New Lines
❮ Previous Next ❯
New Lines
To insert a new line, you can use the \n character:
Example
#include <stdio.h>
int main() {
printf("Hello World!\n");
printf("I am learning C.");
return 0;
}
Try it Yourself »
You can also output multiple lines with a single printf() function. However, this could make the code harder to
read:
Example
#include <stdio.h>
int main() {
printf("Hello World!\nI am learning C.\nAnd it is awesome!");
return 0;
}
Try it Yourself »
Tip: Two \n characters after each other will create a blank line:
Example
#include <stdio.h>
int main() {
printf("Hello World!\n\n");
printf("I am learning C.");
return 0;
}
Try it Yourself »
What is \n exactly?
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in a new line.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Comments
❮ Previous Next ❯
Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to prevent execution
when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes ( // ).
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
// This is a comment
printf("Hello World!");
Try it Yourself »
Example
Try it Yourself »
C Multi-line Comments
Multi-line comments start with /* and ends with */ .
Try it Yourself »
It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.
Good to know: Before version C99 (released in 1999), you could only use multi-line comments in C.
C Exercises
Exercise:
Comments in C are written with special characters. Insert the missing parts:
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Variables
❮ Previous Next ❯
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B' . Char values are surrounded by single quotes
Syntax
Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName). The
equal sign is used to assign a value to the variable.
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
You can also declare a variable without assigning the value, and assign the value later:
Example
// Declare a variable
int myNum;
Output Variables
You learned from the output chapter that you can output values/print text with the printf() function:
Example
printf("Hello World!");
Try it Yourself »
In many other programming languages (like Python, Java, and C++), you would normally use a print function to display the
value of a variable. However, this is not possible in C:
Example
Try it Yourself »
To output variables in C, you must get familiar with something called "format specifiers", which you will learn about in the next
chapter.
C Exercises
Exercise:
Create a variable named myNum and assign the value 50 to it.
= ;
Submit Answer »
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Format Specifiers
❮ Previous Next ❯
Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler what type of data the
variable is storing. It is basically a placeholder for the variable value.
For example, to output the value of an int variable, use the format specifier %d surrounded by double quotes
( "" ), inside the printf() function:
Example
Try it Yourself »
Example
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
Try it Yourself »
To combine both text and a variable, separate them with a comma inside the printf() function:
Example
Try it Yourself »
To print different types in a single printf() function, you can use the following:
Example
Try it Yourself »
C Exercises
Exercise:
Use the correct format specifier to output the value of myNum :
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Variable Values
❮ Previous Next ❯
Example
Try it Yourself »
Example
Try it Yourself »
Example
Try it Yourself »
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
Try it Yourself »
C Exercises
Exercise:
Display the sum of 5 + 10 , using two variables: x and y .
= ;
int y = 10;
printf("%d", x + y);
Submit Answer »
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
Try it Yourself »
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
Try it Yourself »
C Exercises
Exercise:
Fill in the missing parts to create three variables of the same type, using a comma-separated list:
myNum1 = 10 myNum2 = 15 myNum3 = 25;
printf("%d", myNum1 + myNum2 + myNum3);
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Variable Names
All C variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable code:
Example
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Variables - Examples
❮ Previous Next ❯
Real-Life Example
Often in our examples, we simplify variable names to match their data type (myInt or myNum for int types,
myChar for char types, and so on). This is done to avoid confusion.
However, if you want a real-life example on how variables can be used, take a look at the following, where we
have made a program that stores different data of a college student:
Example
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
Try it Yourself »
Example
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
C Data Types
❮ Previous Next ❯
Data Types
As explained in the Variables chapter, a variable in C must be a specified data type, and you must use a format specifier
inside the printf() function to display it:
Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
Try it Yourself »
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15
decimal digits
%d or %i int Try it »
%f or %F float Try it »
%c char Try it »
%s Used for strings (text), which you will learn more about in a later Try it »
chapter
C Exercises
Exercise:
Add the correct data type for the following variables:
myNum = 5;
myFloatNum = 5.99;
myLetter = 'D';
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Character Types
The char data type is used to store a single character.
The character must be surrounded by single quotes, like 'A' or 'c', and we use the %c format specifier to print it:
Example
Try it Yourself »
Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain characters:
Example
Try it Yourself »
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double
when you need a floating point number (with decimals), like 9.99 or 3.14515.
int
Try it Yourself »
float
Try it Yourself »
double
Try it Yourself »
The precision of a floating point value indicates how many digits the value can have after the decimal point. The
precision of float is six or seven decimal digits, while double variables have a precision of about 15 digits.
Therefore, it is often safer to use double for most calculations - but note that it takes up twice as much memory
as float (8 bytes vs. 4 bytes).
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
printf("%f\n", f1);
printf("%lf", d1);
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Decimal Precision
❮ Previous Next ❯
Example
Try it Yourself »
If you want to remove the extra zeros (set decimal precision), you can use a dot ( . ) followed by a number that specifies how
many digits that should be shown after the decimal point:
Example
printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
Try it Yourself »
C Exercises
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
int 2 or 4 bytes
float 4 bytes
double 8 bytes
char 1 byte
The memory size refers to how much space a type occupies in the computer's memory.
To actually get the size (in bytes) of a data type or a variable, we can use the sizeof operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
Try it Yourself »
Note that we use the %lu format specifer to print the result, instead of %d . It is because the compiler expects
the sizeof operator to return a long unsigned int ( %lu ), instead of int ( %d ). On some computers it might
work with %d , but it is safer to use %lu .
You will learn more about the sizeof operator later in this tutorial, and how to use it in different scenarios.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Real-Life Example
Here's a real-life example of using different data types, to calculate and output the total cost of a number of
items:
Example
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Type Conversion
❮ Previous Next ❯
Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is known as type conversion.
For example, if you try to divide two integers, 5 by 2 , you would expect the result to be 2.5 . But since we are working with
integers (and not floating-point values), the following example will just output 2 :
Example
int x = 5;
int y = 2;
int sum = 5 / 2;
Try it Yourself »
To get the right result, you need to know how type conversion works.
Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to another.
Example
As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000 .
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the float value 9.99 to an int value of
9:
Example
printf("%d", myInt); // 9
Try it Yourself »
What happened to .99 ? We might want that data in our program! So be careful. It is important that you know how the compiler
work in these situations, to avoid unexpected results.
As another example, if you divide two integers: 5 by 2 , you know that the sum is 2.5 . And as you know from the beginning of
this page, if you store the sum as an integer, the result will only display the number 2 . Therefore, it would be better to store the
sum as a float or a double , right?
Example
float sum = 5 / 2;
Try it Yourself »
Why is the result 2.00000 and not 2.5 ? Well, it is because 5 and 2 are still integers in the division. In this case, you need to
manually convert the integer values to floating-point values. (see below).
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Considering our problem from the example above, we can now get the right result:
Example
Try it Yourself »
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
Try it Yourself »
And since you learned about "decimal precision" in the previous chapter, you could make the output even cleaner by removing the
extra zeros (if you like):
Example
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
Try it Yourself »
Real-Life Example
Here's a real-life example of data types and type conversion where we create a program to calculate the percentage of a user's
score in relation to the maximum score in a game:
Example
/* Calculate the percantage of the user's score in relation to the maximum available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;
Try it Yourself »
C Exercises
Exercise:
Use type conversion to make sure that the result of the following example is 1.5 , and not just 1 .
float sum = 3 / 2;
printf("%.1f", sum);
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Constants
❮ Previous Next ❯
Constants
If you don't want others (or yourself) to change existing variable values, you can use the const keyword.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
Try it Yourself »
You should always declare the variable as constant when you have values that are unlikely to change:
Example
Try it Yourself »
Notes On Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
Try it Yourself »
Good Practice
Another thing about constant variables, is that it is considered good practice to declare them with uppercase.
It is not required, but useful for code readability and common for C programmers:
Example
Try it Yourself »
C Exercises
Exercise:
Make sure that the value of the following variable is not possible to change:
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Operators
❮ Previous Next ❯
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
Try it Yourself »
Although the + operator is often used to add together two values, like in the example above, it can also be used
to add together a variable and a value, or a variable and another variable:
Example
Try it Yourself »
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example Try it
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x:
Example
int x = 10;
Try it Yourself »
Example
int x = 10;
x += 5;
Try it Yourself »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because
it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0 , which means true ( 1 ) or false ( 0 ). These values are
known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
Try it Yourself »
> Greater than x>y Returns 1 if the first value is greater Try it »
than the second value
< Less than x<y Returns 1 if the first value is less than Try it »
the second value
>= Greater than or equal x >= y Returns 1 if the first value is greater Try it »
to than, or equal to, the second value
<= Less than or equal to x <= y Returns 1 if the first value is less than, Try it »
or equal to, the second value
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and x < 5 && x < 10 Returns 1 if both statements are true Try it »
! Logical not !(x < 5 && x < 10) Reverse the result, returns 0 if the result is Try it »
1
C Exercises
Exercise:
Fill in the blanks to multiply 10 with 5 , and print the result:
int x = 10;
int y = 5;
printf(" ", x y);
Submit Answer »
Start the Exercise
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Booleans
❮ Previous Next ❯
Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
Boolean Variables
In C, the bool type is not a built-in data type, like int or char .
It was introduced in C99, and you must import the following header file to use it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can only take the values true or false :
Before trying to print the boolean variables, you should know that boolean values are returned as integers:
Therefore, you must use the %d format specifier to print a boolean value:
Example
Try it Yourself »
However, it is more common to return a boolean value by comparing values and variables.
For example, you can use a comparison operator, such as the greater than ( > ) operator, to compare two
values:
Example
Try it Yourself »
From the example above, you can see that the return value is a boolean value (1 ).
Example
int x = 10;
int y = 9;
printf("%d", x > y);
Try it Yourself »
In the example below, we use the equal to ( == ) operator to compare different values:
Example
You are not limited to only compare numbers. You can also compare boolean variables, or even special
structures, like arrays (which you will learn more about in a later chapter):
Example
Try it Yourself »
Remember to include the <stdbool.h> header file when working with bool variables.
C Exercises
Exercise:
What is the result of the following example?
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Boolean Examples
❮ Previous Next ❯
In the example below, we use the >= comparison operator to find out if the age (25 ) is greater than OR equal
to the voting age limit, which is set to 18 :
Example
printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year olds are allowed to
vote!
Try it Yourself »
Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above in an
if...else statement, so we can perform different actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18 . Otherwise output "Not old enough to
vote.":
Try it Yourself »
Booleans are the basis for all comparisons and conditions.
You will learn more about conditions ( if...else ) in the next chapter.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
C If ... Else
❮ ❯
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of code to be executed if a condition is true .
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true , print some text:
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y
is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".
C Exercises
Exercise:
Print "Hello World" if x is greater than y .
int x = 50;
int y = 10;
(x y) {
printf("Hello World");
}
COLOR PICKER
‐
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Else
❮ Previous Next ❯
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
Try it Yourself »
Example explained
In the example above, time (20) is greater than 18, so the condition is false . Because of this, we move on to
the else condition and print to the screen "Good evening". If the time was less than 18, the program would
print "Good day".
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Else If
❮ Previous Next ❯
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
Try it Yourself »
Example explained
In the example above, time (22) is greater than 10, so the first condition is false . The next condition, in the
else if statement, is also false , so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Real-Life Examples
This example shows how you can use if..else to "open a door" if the user enters the correct code:
Example
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
Try it Yourself »
This example shows how you can use if..else to find out if a number is positive or negative:
Example
if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Try it Yourself »
Example
int myAge = 25;
int votingAge = 18;
Try it Yourself »
Example
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
P T S Q
C Switch
❮ Previous Next ❯
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
Syntax
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
Try it Yourself »
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
Example
int day = 4;
switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}
Try it Yourself »
Note: The default keyword must be used as the last statement in the switch, and it does not need a break.
C Exercises
Exercise:
Insert the missing parts to complete the following switch statement:
int day = 2;
switch ( ) {
1:
printf("Monday");
;
2:
printf("Sunday");
;
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C While Loop
❮ Previous Next ❯
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
While Loop
The while loop loops through a block of code as long as a specified condition is true :
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable ( i ) is less than 5:
Example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Try it Yourself »
Note: Do not forget to increase the variable used in the condition ( i++ ), otherwise the loop will never end!
C Exercises
Test Yourself With Exercises
Exercise:
Print i as long as i is less than 6:
int i = 1;
(i < 6) {
printf("%d\n", i);
;
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Do/While Loop
❮ Previous Next ❯
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition
is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
Try it Yourself »
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
Real-Life Examples
To demonstrate a practical example of the while loop, we have created a simple "countdown" program:
Example
int countdown = 3;
Try it Yourself »
To demonstrate a practical example of the while loop combined with an if else statement, let's say we play a
game of Yatzy:
Example
Print "Yatzy!" If the dice number is 6:
int dice = 1;
Try it Yourself »
If the loop passes the values ranging from 1 to 5, it prints "No Yatzy". Whenever it passes the value 6, it prints
"Yatzy!".
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C For Loop
❮ Previous Next ❯
For Loop
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:
Syntax
Expression 1 is executed (one time) before the execution of the code block.
Expression 3 is executed (every time) after the code block has been executed.
Example
int i;
Try it Yourself »
Example explained
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
Exercise:
Use a for loop to print "Yes" 5 times:
(int i = 0; i < 5; ) {
printf("Yes\n");
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Nested Loops
❮ Previous Next ❯
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
int i, j;
// Outer loop
for (i = 1; i <= 2; ++i) {
printf("Outer: %d\n", i); // Executes 2 times
// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Real-Life Examples
To demonstrate a practical example of the for loop, let's create a program that counts to 100 by tens:
Example
In this examlpe, we create a program that only print even values between 0 and 10:
Example
And in this example, we create a program that prints the multiplication table for a specified number:
Example
int number = 2;
int i;
return 0;
❮ ❯
COLOR PICKER
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out"
of a switch statement.
Example
int i;
Try it Yourself »
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with
the next iteration in the loop.
Example
int i;
Try it Yourself »
Break Example
int i = 0;
Try it Yourself »
Continue Example
int i = 0;
Try it Yourself »
C Exercises
Exercise:
Stop the loop if i is 5.
for (int i = 0; i < 10; i++) {
if (i == 5) {
;
}
printf("%d\n", i);
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Arrays
❮ ❯
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.
To create an array, define the data type (like int ) and specify the name of the array followed by square
brackets [].
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers :
Example
// Outputs 25
myNumbers[0] = 33;
Example
printf("%d", myNumbers[0]);
Example
Example
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the number of array elements in advance, in order for the program to
store enough memory.
You are not able to change the size of the array after creation.
C Exercises
Exercise:
Create an array of type int called myNumbers .
❮ ❯
COLOR PICKER
‐
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Array Size
❮ Previous Next ❯
Example
Try it Yourself »
Why did the result show 20 instead of 5 , when the array contains 5 elements?
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5
(4 bytes x 5 elements) = 20 bytes.
Knowing the memory size of an array is great when you are working with larger programs that require good
memory management.
But when you just want to find out how many elements an array has, you can use the following formula (which
divides the size of the array by the size of one array element):
Example
Try it Yourself »
Making Better Loops
In the array loops section in the previous chapter, we wrote the size of the array in the loop condition (i < 4 ).
This is not ideal, since it will only work for arrays of a specified size.
However, by using the sizeof formula from the example above, we can now make loops that work for arrays of
any size, which is more sustainable.
Instead of writing:
Example
Try it Yourself »
It is better to write:
Example
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Real-Life Example
To demonstrate a practical example of using arrays, let's create a program that calculates the average of
different ages:
Example
Try it Yourself »
And in this example, we create a program that finds the lowest age among different ages:
Example
// Loop through the elements of the ages array to find the lowest age
for (int i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Multidimensional Arrays
❮ Previous Next ❯
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single dimension arrays. These are
great, and something you will use a lot while programming in C. However, if you want to store data as a tabular
form, like a table with rows and columns, you need to get familiar with multidimensional arrays.
Arrays can have any number of dimensions. In this chapter, we will introduce the most common; two-
dimensional arrays (2D).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
The first dimension represents the number of rows [2], while the second dimension represents the number of
columns [3]. The values are placed in row-order, and can be visualized like this:
This statement accesses the value of the element in the first row (0) and third column (2) of the matrix
array.
Example
Try it Yourself »
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
The following example will change the value of the element in the first row (0) and first column (0):
Example
Try it Yourself »
Example
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Strings
❮ Previous Next ❯
Strings
Strings are used for storing text/characters.
Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must
use the char type and create an array of characters to make a string in C:
To output the string, you can use the printf() function together with the format specifier %s to tell C that we are now working
with strings:
Example
Try it Yourself »
Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [] .
Example
Note that we have to use the %c format specifier to print a single character.
Modify Strings
To change the value of a specific character in a string, refer to the index number, and use single quotes:
Example
Try it Yourself »
Example
Try it Yourself »
And like we specified in the arrays chapter, you can also use the sizeof formula (instead of manually write the size of the array in
the loop condition (i < 5) ) to make the loop more sustainable:
Example
Try it Yourself »
You should also note that you can create a string with a set of characters. This example will produce the same result as the
example in the beginning of this page:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);
Try it Yourself »
Why do we include the \0 character at the end? This is known as the "null terminating character", and must be
included when creating strings using this method. It tells C that this is the end of the string.
Differences
The difference between the two ways of creating strings, is that the first method is easier to write, and you do not have to include
the \0 character, as C will do it for you.
You should note that the size of both arrays is the same: They both have 13 characters (space also counts as a character by
the way), including the \0 character:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";
Try it Yourself »
Real-Life Example
Use strings to create a simple welcome message:
Example
Try it Yourself »
C Exercises
Exercise:
Fill in the missing part to create a "string" named greetings, and assign it the value "Hello".
= ;
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Special Characters
❮ Previous Next ❯
char txt[] = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash ( \ ) escape character turns special characters into string characters:
\\ \ Backslash
Example
char txt[] = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Example
Try it Yourself »
The sequence \\ inserts a single backslash in a string:
Example
Try it Yourself »
\t Tab Try it »
\0 Null Try it »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C User Input
❮ Previous Next ❯
User Input
You have already learned that printf() is used to output values in C.
Example
Output a number entered by the user:
// Create an integer variable that will store the number we get from the user
int myNum;
Run example »
The scanf() function takes two arguments: the format specifier of the variable ( %d in the example above) and
the reference operator ( &myNum ), which stores the memory address of the variable.
Tip: You will learn more about memory addresses and functions in the next chapter.
Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character in the following example):
Example
// Create an int and a char variable
int myNum;
char myChar;
// Get and save the number AND character the user types
scanf("%d %c", &myNum, &myChar);
Run example »
Example
Output the name of a user:
// Create a string
char firstName[30];
Run example »
Note: When working with strings in scanf() , you must specify the size of the string/array (we used a very high
number, 30 in our example, but atleast then we are certain it will store enough characters for the first name),
and you don't have to use the reference operator ( & ).
However, the scanf() function has some limitations: it considers space (whitespace, tabs, etc) as a terminating
character, which means that it can only display a single word (even if you type many words). For example:
Example
char fullName[30];
From the example above, you would expect the program to print "John Doe", but it only prints "John".
That's why, when working with strings, we often use the fgets() function to read a line of text. Note that you
must include the following arguments: the name of the string variable, sizeof (string_name), and stdin :
Example
char fullName[30];
Run example »
Use the scanf() function to get a single word as input, and use fgets() for multiple words.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Memory Address
❮ Previous Next ❯
Memory Address
When a variable is created in C, a memory address is assigned to the variable.
The memory address is the location of where the variable is stored on the computer.
To access it, use the reference operator ( & ), and the result represents where the variable is stored:
Example
Try it Yourself »
Note: The memory address is in hexadecimal form (0x..). You will probably not get the same result in your
program, as this depends on where the variable is stored on your computer.
You should also note that &myAge is often called a "pointer". A pointer basically stores the memory address of a
variable as its value. To print pointer values, we use the %p format specifier.
You will learn much more about pointers in the next chapter.
Pointers are important in C, because they allow us to manipulate the data in the computer's memory -this can
reduce the code and improve the performance.
Pointers are one of the things that make C stand out from other programming languages, like Python and Java.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Pointers
❮ ❯
Creating Pointers
You learned from the previous chapter, that we can get thememory address of a variable with the reference
operator & :
Example
A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.
The address of the variable you are working with is assigned to the pointer:
Example
Create a pointer variable with the name ptr , that points to an int variable ( myAge ). Note that the type of
the pointer has to match the type of the variable you're working with ( int in our example).
Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.
Dereference
In the example above, we used the pointer variable to get the memory address of a variable (used together with
the & reference operator).
You can also get the value of the variable the pointer points to, by using the * operator (the dereference
operator):
Example
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
Note that the * sign can be confusing here, as it does two different things in our code:
int* myNum;
int *myNum;
Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages, like Python and Java.
They are important in C, because they allow us to manipulate the data in the computer's memory. This can
reduce the code and improve the performance. If you are familiar with data structures like lists, trees and
graphs, you should know that pointers are especially useful for implementing those. And sometimes you even
have to use pointers, for example when working with files.
But be careful; pointers must be handled with care, since it is possible to damage data stored in other memory
addresses.
C Exercises
Exercise:
Create a pointer variable called ptr, that points to the int variable myAge:
❮ ❯
COLOR PICKER
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Example
You learned from the arrays chapter that you can loop through the array elements with a for loop:
Example
Result:
25
50
75
100
Instead of printing the value of each array element, let's print the memory address of each array element:
Example
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
Note that the last number of each of the elements' memory address is different, with an addition of 4.
Example
Result:
So from the "memory address example" above, you can see that the compiler reserves 4 bytes of memory for
each array element, which means that the entire array takes up 16 bytes (4 * 4) of memory storage:
Example
Result:
16
How Are Pointers Related to Arrays
Ok, so what's the relationship between pointers and arrays? Well, in C, the name of an array, is actually a
pointer to the first element of the array.
Confused? Let's try to understand this better, and use our "memory address example" above again.
The memory address of the first element is the same as the name of the array:
Example
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
This basically means that we can work with arrays through pointers!
How? Since myNumbers is a pointer to the first element in myNumbers, you can use the * operator to access it:
Example
Result:
25
To access the rest of the elements in myNumbers, you can increment the pointer/array (+1, +2, etc):
Example
// and so on..
Result:
50
75
Example
Result:
25
50
75
100
Example
Result:
13
17
This way of working with arrays might seem a bit excessive. Especially with simple arrays like in the examples
above. However, for large arrays, it can be much more efficient to access and manipulate arrays with pointers.
It is also considered faster and easier to access two-dimensional arrays with pointers.
And since strings are actually arrays, you can also use pointers to access strings.
For now, it's great that you know how this works. But like we specified in the previous chapter; pointers must
be handled with care, since it is possible to overwrite other data stored in memory.
❮ ❯
COLOR PICKER
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Functions
❮ Previous Next ❯
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.
Predefined Functions
So it turns out you already know what a function is. You have been using it the whole time while studying this tutorial!
For example, main() is a function, which is used to execute code, and printf() is a function; used to output/print text to the
screen:
Example
int main() {
printf("Hello World!");
return 0;
}
Try it Yourself »
Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by parentheses () and
curly brackets {} :
Syntax
void myFunction() {
// code to be executed
}
Example Explained
myFunction() is the name of the function
void means that the function does not have a return value. You will learn more about return values later in the next
chapter
Inside the function (the body), add code that defines what the function should do
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main , call myFunction() :
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Try it Yourself »
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Try it Yourself »
C Exercises
Exercise:
Create a method named myFunction and call it inside main() .
void {
printf("I just got executed!");
}
int main() {
return 0;
}
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Function Parameters
❮ Previous Next ❯
Parameters are specified after the function name, inside the parentheses. You can add as many parameters as
you want, just separate them with a comma:
Syntax
The following function that takes a string of characters with name as parameter. When the function is called, we
pass along a name, which is used inside the function to print "Hello" and the name of each person.
Example
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Hello Liam
// Hello Jenny
// Hello Anja
Try it Yourself »
When a parameter is passed to the function, it is called an argument. So, from the example above: name is a
parameter, while Liam , Jenny and Anja are arguments.
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Try it Yourself »
Note that when you are working with multiple parameters, the function call must have the same number of
arguments as there are parameters, and the arguments must be passed in the same order.
Example
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Try it Yourself »
Example Explained
The function ( myFunction ) takes an array as its parameter ( int myNumbers[5] ), and loops through the
array elements with the for loop.
When the function is called inside main() , we pass along the myNumbers array, which outputs the array
elements.
Note that when you call the function, you only need to use the name of the array when passing it as an
argument myFunction(myNumbers) . However, the full declaration of the array is needed in the function
parameter ( int myNumbers[5] ).
Return Values
The void keyword, used in the previous examples, indicates that the function should not return a value. If you
want the function to return a value, you can use a data type (such as int or float , etc.) instead of void ,
and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Example
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Try it Yourself »
Real-Life Example
To demonstrate a practical example of using functions, let's create a program that converts a value from
fahrenheit to celsius:
Example
int main() {
// Set a fahrenheit value
float f_value = 98.8;
return 0;
}
Try it Yourself »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
For code optimization, it is recommended to separate the declaration and the definition of the function.
You will often see C programs that have function declaration above main() , and function definition below
main() . This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
printf("I just got executed!");
}
Another Example
If we use the example from the previous chapter regarding function parameters and return values:
Example
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Example
// Function declaration
int myFunction(int, int);
// Function definition
int myFunction(int x, int y) {
return x + y;
}
❮ ❯
COLOR PICKER
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Recursion
❮ Previous Next ❯
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break complicated
problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following
example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding
two numbers:
Example
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Try it Yourself »
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns
the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there and returns the result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which
never terminates, or one that uses excess amounts of memory or processor power. However, when written
correctly, recursion can be a very efficient and mathematically-elegant approach to programming.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Math Functions
❮ Previous Next ❯
Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on numbers.
To use them, you must include the math.h header file in your program:
#include <math.h>
Square Root
To find the square root of a number, use the sqrt() function:
Example
printf("%f", sqrt(16));
Try it Yourself »
Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a
number downwards to its nearest integer, and returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Try it Yourself »
Power
The pow() function returns the value of x to the power of y (xy):
Example
Try it Yourself »
Function Description
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
C Files
❮ ❯
File Handling
In C, you can create, open, read, and write to files by declaring a pointer of type FILE , and use the fopen()
function:
FILE *fptr
fptr = fopen(filename, mode);
FILE is basically a data type, and we need to create a pointer variable to work with it ( fptr ). For now, this line
is not important. It's just something you need when working with files.
To actually open a file, use the fopen() function, which takes two parameters:
Parameter Description
filename The name of the actual file you want to open (or create), like filename.txt
mode A single character, which represents what you want to do with the file (read,
write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will create one for you:
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
// Close the file
fclose(fptr);
Note: The file is created in the same directory as your other C files, if nothing else is specified.
Tip: If you want to create the file in a specific folder, just provide an absolute path:
This will close the file when we are done with it.
In the next chapters, you will learn how to write content to a file and read from it.
❮ ❯
COLOR PICKER
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Write To Files
❮ Previous Next ❯
Write To a File
Let's use the w mode from the previous chapter again, and write something to the file we just created.
The w mode means that the file is opened for writing. To insert content to it, you can use the fprintf()
function and add the pointer variable ( fptr in our example) and some text:
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this:
Run example »
Note: If you write to a file that already exists, the old content is deleted, and the new content is inserted. This is
important to know, as you might accidentally erase existing content.
For example:
Example
As a result, when we open the file on our computer, it says "Hello World!" instead of "Some text":
Run example »
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this:
Run example »
Note: Just like with the w mode; if the file does not exist, the a mode will create a new file with the
"appended" content.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
C Read Files
❮ Previous Next ❯
Read a File
In the previous chapter, we wrote to a file using w and a modes inside the fopen() function.
Example
FILE *fptr;
It requires a little bit of work to read a file in C. Hang in there! We will guide you step-by-step.
Next, we need to create a string that should be big enough to store the content of the file.
For example, let's create a string that can store up to 100 characters:
Example
FILE *fptr;
In order to read the content of filename.txt , we can use the fgets() function.
1. The first parameter specifies where to store the file content, which will be in the myString array we just
created.
2. The second parameter specifies the maximum size of data to read, which should match the size of
myString ( 100 ).
3. The third parameter requires a file pointer that is used to read the file ( fptr in our example).
Now, we can print the string, which will output the content of the file:
Example
FILE *fptr;
Hello World!
Run example »
Note: The fgets function only reads the first line of the file. If you remember, there were two lines of text in
filename.txt .
To read every line of the file, you can use a while loop:
Example
FILE *fptr;
Hello World!
Hi everybody!
Run example »
Good Practice
If you try to open a file for reading that does not exist, the fopen() function will return NULL .
Tip: As a good practice, we can use an if statement to test for NULL , and print some text instead (when the
file does not exist):
Example
FILE *fptr;
Run example »
With this in mind, we can create a more sustainable code if we use our "read a file" example above again:
Example
If the file exist, read the content and print it. If the file does not exist, print a message:
FILE *fptr;
Hello World!
Hi everybody!
Run example »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Structures (structs)
❮ Previous Next ❯
Structures
Structures (also called structs) are a way to group several related variables into one place. Each variable in the
structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside curly braces:
Use the struct keyword inside the main() method, followed by the name of the structure and then the name
of the structure variable:
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Try it Yourself »
Now you can easily create multiple structure variables with different values, using just one structure:
Example
s2.myNum = 20;
s2.myLetter = 'C';
Try it Yourself »
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
return 0;
}
Try it Yourself »
However, there is a solution for this! You can use the strcpy() function and assign the value to s1.myString ,
like this:
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};
int main() {
struct myStructure s1;
return 0;
}
Result:
Try it Yourself »
Simpler Syntax
You can also assign values to members of a structure variable at declaration time, in a single line.
Just insert the values in a comma-separated list inside curly braces {} . Note that you don't have to use the
strcpy() function for string values with this technique:
Example
// Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Try it Yourself »
Note: The order of the inserted values must match the order of the variable types declared in the structure (13
for int, 'B' for char, etc).
Copy Structures
You can also assign one structure to another.
Example
s2 = s1;
Try it Yourself »
Modify Values
If you want to change/modify a value, you can use the dot syntax (. ).
Example
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};
int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};
// Modify values
s1.myNum = 30;
s1.myLetter = 'C';
strcpy(s1.myString, "Something else");
// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);
return 0;
}
Try it Yourself »
Modifying values are especially useful when you copy structure values:
Example
// Copy s1 values to s2
s2 = s1;
// Change s2 values
s2.myNum = 30;
s2.myLetter = 'C';
strcpy(s2.myString, "Something else");
// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);
Try it Yourself »
Imagine you have to write a program to store different information about Cars, such as brand, model, and year.
What's great about structures is that you can create a single "Car template" and use it for every cars you make.
See below for a real life example.
Real-Life Example
Use a structure to store different information about Cars:
Example
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
return 0;
}
Try it Yourself »
C Exercises
Exercise:
Fill in the missing part to create a Car structure:
Car {
char brand[50];
char model[50];
int year;
};
Submit Answer »
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.
Menu
ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
C Enumeration (enum)
❮ Previous Next ❯
C Enums
An enum is a special type that represents a group of constants (unchangeable values).
To create an enum, use the enum keyword, followed by the name of the enum, and separate the enum items
with a comma:
enum Level {
LOW,
MEDIUM,
HIGH
};
Inside the main() method, specify the enum keyword, followed by the name of the enum ( Level ) and then
the name of the enum variable ( myVar in this example):
Now that you have created an enum variable ( myVar ), you can assign a value to it.
The assigned value must be one of the items inside the enum (LOW , MEDIUM or HIGH ):
By default, the first item ( LOW ) has the value 0 , the second ( MEDIUM ) has the value 1 , etc.
If you now try to print myVar, it will output 1 , which represents MEDIUM :
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
return 0;
}
Try it Yourself »
Change Values
As you know, the first item of an enum has the value 0. The second has the value 1, and so on.
To make more sense of the values, you can easily change them:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
Try it Yourself »
Note that if you assign a value to one specific item, the next items will update their numbers accordingly:
enum Level {
LOW = 5,
MEDIUM, // Now 6
HIGH // Now 7
};
Try it Yourself »
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}
Try it Yourself »
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of
cards, etc.
❮ Previous Next ❯
COLOR PICKER
SPACES
UPGRADE
AD-FREE
NEWSLETTER
GET CERTIFIED
REPORT ERROR
Top Tutorials
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
How To Tutorial
SQL Tutorial
Python Tutorial
W3.CSS Tutorial
Bootstrap Tutorial
PHP Tutorial
Java Tutorial
C++ Tutorial
jQuery Tutorial
Top References
HTML Reference
CSS Reference
JavaScript Reference
SQL Reference
Python Reference
W3.CSS Reference
Bootstrap Reference
PHP Reference
HTML Colors
Java Reference
Angular Reference
jQuery Reference
Top Examples
HTML Examples
CSS Examples
JavaScript Examples
How To Examples
SQL Examples
Python Examples
W3.CSS Examples
Bootstrap Examples
PHP Examples
Java Examples
XML Examples
jQuery Examples
Get Certified
HTML Certificate
CSS Certificate
JavaScript Certificate
Front End Certificate
SQL Certificate
Python Certificate
PHP Certificate
jQuery Certificate
Java Certificate
C++ Certificate
C# Certificate
XML Certificate
FORUM ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all
content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.