Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views59 pages

Stractured Programming

The document discusses structured programming concepts and provides practical topics to explore related to Java OOP, data structures and algorithms, SQL, and C programming. It emphasizes clear organization, modular design, and logical flow in writing code.

Uploaded by

bigdealcalebu77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views59 pages

Stractured Programming

The document discusses structured programming concepts and provides practical topics to explore related to Java OOP, data structures and algorithms, SQL, and C programming. It emphasizes clear organization, modular design, and logical flow in writing code.

Uploaded by

bigdealcalebu77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Certainly! Let’s explore some practical work related to structured programming.

Structured
programming emphasizes clear organization, modular design, and logical flow in writing
code. Here are some practical topics you can explore:

1. Java OOP (Object-Oriented Programming):


o Learn about classes, objects, inheritance, encapsulation, and polymorphism.
o Understand how to create reusable and well-organized Java applications.
o Explore the advantages of object-oriented programming (OOP) over
procedural programming.
o Java OOP Tutorial on W3Schools provides detailed explanations and
examples1.
2. Data Structures and Algorithms (DSA):
o DSA is essential for efficient problem-solving and software development.
o Study different data structures (arrays, linked lists, trees, graphs, etc.) and
algorithms (sorting, searching, dynamic programming, etc.).
o Implement DSA concepts in your preferred programming language.
o W3Schools offers an Introduction to Data Structures and Algorithms to
get you started2.
3. SQL (Structured Query Language):
o SQL is used for managing and querying databases.
o Learn SQL syntax, database design, and common operations (SELECT,
INSERT, UPDATE, DELETE).
o Practice writing SQL queries on sample databases.
3
o Explore the SQL Introduction on W3Schools .

Remember to practice hands-on coding, work on small projects, and gradually build your
skills. Structured programming principles apply not only to specific languages but also to
good coding practices in general. Happy coding! �����

C programming

Certainly! Let’s explore some structured programming concepts in C programming.


Structured programming emphasizes clear organization, modular design, and logical flow in
writing code. Here are some key points and practical topics you can explore:

1. Introduction to C:
o C is a general-purpose programming language created by Dennis Ritchie at
Bell Laboratories in 1972.
o Despite its age, C remains popular due to its fundamental role in computer
science and strong association with UNIX.
o Start by understanding the basics of C, including syntax, data types, and
control structures.
1
o Explore the C Introduction on W3Schools for a solid foundation .
2. C Tutorial:
o Learn C step by step with W3Schools’ comprehensive C Tutorial.
o Topics covered include variables, operators, loops, functions, arrays, pointers,
and more.
o Practice writing C code using the “Try it Yourself” editor provided in each
chapter.
3. Structures (structs):
o Structures (also called structs) allow you to group related variables into one
place.
o Unlike arrays, a structure can contain different data types (int, float, char, etc.).
o Explore how to create and use structures in C with the C Structures
Tutorial2.
4. Object-Oriented Programming (OOP) in C:
o Although C is not a pure OOP language, you can apply OOP principles using
structs and functions.
o Learn about encapsulation, abstraction, and modular design.
o Practice creating reusable code using OOP concepts.
5. Practice and Projects:
o Apply what you’ve learned by working on small projects.
o Write programs that solve real-world problems or simulate specific scenarios.
o Explore algorithms, data structures, and practical applications.

Remember to practice coding regularly, experiment with different concepts, and gradually
build your skills. Structured programming principles apply not only to C but also to good
coding practices in general. Happy coding! �����.

C pogramming(w3schools)

Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable with the reference operator &:

Example
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge
(0x7ffe5367e044)

Try it Yourself »

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
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that
stores the address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)


printf("%p\n", ptr);

Try it Yourself »

Example explained
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.

Now, ptr holds the value of myAge's memory address.

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
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer
(0x7ffe5367e044)
printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)


printf("%d\n", *ptr);

Try it Yourself »
Note that the * sign can be confusing here, as it does two different things in
our code:

 When used in declaration (int* ptr), it creates a pointer variable.


 When not used in declaration, it act as a dereference operator.

Good To Know: There are two ways to declare pointer variables in C:

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
Test Yourself With Exercises
Exercise:
Create a pointer variable called ptr, that points to the int variable myAge:

int myAge = 43;


= &myAge;

Submit Answer »

Start the Exercise

❮ PreviousNext ❮

C Pointers and Arrays


❮ PreviousNext ❮

Pointers & Arrays


You can also use pointers to access arrays.

Consider the following array of integers:

Example
int myNumbers[4] = {25, 50, 75, 100};

You learned from the arrays chapter that you can loop through the array
elements with a for loop:

Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}

Result:

25
50
75
100
Try it Yourself »

Instead of printing the value of each array element, let's print the memory
address of each array element:

Example
int myNumbers[4] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%p\n", &myNumbers[i]);
}

Result:

0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
Try it Yourself »

Note that the last number of each of the elements' memory address is
different, with an addition of 4.

It is because the size of an int type is typically 4 bytes, remember:

Example
// Create an int variable
int myInt;

// Get the memory size of an int


printf("%lu", sizeof(myInt));

Result:
4
Try it Yourself »

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
int myNumbers[4] = {25, 50, 75, 100};

// Get the size of the myNumbers array


printf("%lu", sizeof(myNumbers));

Result:

16
Try it Yourself »

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
int myNumbers[4] = {25, 50, 75, 100};

// Get the memory address of the myNumbers array


printf("%p\n", myNumbers);

// Get the memory address of the first array element


printf("%p\n", &myNumbers[0]);

Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f0
Try it Yourself »

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
int myNumbers[4] = {25, 50, 75, 100};

// Get the value of the first element in myNumbers


printf("%d", *myNumbers);

Result:

25
Try it Yourself »

To access the rest of the elements in myNumbers, you can increment the
pointer/array (+1, +2, etc):

Example
int myNumbers[4] = {25, 50, 75, 100};

// Get the value of the second element in myNumbers


printf("%d\n", *(myNumbers + 1));

// Get the value of the third element in myNumbers


printf("%d", *(myNumbers + 2));

// and so on..

Result:

50
75
Try it Yourself »

Or loop through it:

Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", *(ptr + i));
}

Result:

25
50
75
100
Try it Yourself »

It is also possible to change the value of array elements with pointers:

Example
int myNumbers[4] = {25, 50, 75, 100};

// Change the value of the first element to 13


*myNumbers = 13;

// Change the value of the second element to 17


*(myNumbers +1) = 17;

// Get the value of the first element


printf("%d\n", *myNumbers);

// Get the value of the second element


printf("%d\n", *(myNumbers + 1));

Result:

13
17
Try it Yourself »
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.

❮ PreviousNext ❮

W3schools Pathfinder
Track your progress - it's free!
Log inSign Up

C Functions
❮ PreviousNext ❮

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

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;
}

// Outputs "I just got executed!"

Try it Yourself »

A function can be called multiple times:

Example
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Try it Yourself »

C Exercises
Test Yourself With Exercises
Exercise:
Create a method named myFunction and call it inside main().

void {
printf("I just got executed!");
}

int main() {
return 0;
}

Submit Answer »

Start the Exercise

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

C Function Parameters
❮ PreviousNext ❮

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as variables inside the
function.

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
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

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
void myFunction(char name[]) {
printf("Hello %s\n", name);
}

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
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Hello Liam. You are 3 years old.
// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.

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.

Pass Arrays as Function Parameters


You can also pass arrays to a function:

Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}

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 »

This example returns the sum of a function with two parameters:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}

// Outputs 8 (5 + 3)

Try it Yourself »

You can also store the result in a variable:

Example
int myFunction(int x, int y) {
return x + y;
}

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
// Function to convert Fahrenheit to Celsius
float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}

int main() {
// Set a fahrenheit value
float f_value = 98.8;

// Call the function with the fahrenheit value


float result = toCelsius(f_value);

// Print the fahrenheit value


printf("Fahrenheit: %.2f\n", f_value);

// Print the result


printf("Convert Fahrenheit to Celsius: %.2f\n", result);

return 0;
}

Try it Yourself »

❮ PreviousNext ❮

W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT
C Function Declaration and
Definition
❮ PreviousNext ❮

Function Declaration and Definition


You just learned from the previous chapters that you can create and call a function in the
following way:

Example
// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}
Try it Yourself »

A function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

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!");
}

Try it Yourself »

Another Example
If we use the example from the previous chapter regarding function parameters and return values:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)

Try it Yourself »

It is considered good practice to write it like this instead:

Example
// Function declaration
int myFunction(int, int);

// The main method


int main() {
int result = myFunction(5, 3); // call the function
printf("Result is = %d", result);
return 0;
}

// Function definition
int myFunction(int x, int y) {
return x + y;
}

Try it Yourself »

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Recursion
❮ PreviousNext ❮

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 sum(int k);

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.
❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Math Functions
❮ PreviousNext ❮

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
printf("%f", pow(4, 3));

Try it Yourself »

Other Math Functions


A list of other popular math functions (from the <math.h> library) can be found in the table
below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x


cbrt(x) Returns the cube root of x

cos(x) Returns the cosine of x

exp(x) Returns the value of Ex

sin(x) Returns the sine of x (x is in radians)

tan(x) Returns the tangent of an angle

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Files
❮ PreviousNext ❮

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.

On our computer, it looks like this:


Run example »

Tip: If you want to create the file in a specific folder, just provide an absolute path:

fptr = fopen("C:\directoryname\filename.txt", "w");

Closing the file


Did you notice the fclose() function in our example above?

This will close the file when we are done with it.

It is considered as good practice, because it makes sure that:

 Changes are saved properly


 Other programs can use the file (if you want)
 Clean up unnecessary memory space

In the next chapters, you will learn how to write content to a file and read from it.

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!


Log inSign Up

ADVERTISEMENT

C Write To Files
❮ PreviousNext ❮

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;

// Open a file in writing mode


fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, "Some text");

// Close the file


fclose(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
fprintf(fptr, "Hello World!");

As a result, when we open the file on our computer, it says "Hello World!" instead of "Some
text":

Run example »

Append Content To a File


If you want to add content to a file without deleting the old content, you can use the a mode.

The a mode appends content at the end of the file:


Example
FILE *fptr;

// Open a file in append mode


fptr = fopen("filename.txt", "a");

// Append some text to the file


fprintf(fptr, "\nHi everybody!");

// Close the file


fclose(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.

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up
ADVERTISEMENT

C Read Files
❮ PreviousNext ❮

Read a File
In the previous chapter, we wrote to a file using w and a modes inside
the fopen() function.

To read from a file, you can use the r mode:

Example
FILE *fptr;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

This will make the filename.txt opened for reading.

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;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

In order to read the content of filename.txt, we can use


the fgets() function.
The fgets() function takes three parameters:

Example
fgets(myString, 100, fptr);

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;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print the file content


printf("%s", myString);

// Close the file


fclose(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;

// Open a file in read mode


fptr = fopen("filename.txt", "r");
// Store the content of the file
char myString[100];

// Read the content and print it


while(fgets(myString, 100, fptr)) {
printf("%s", myString);
}

// Close the file


fclose(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;

// Open a file in read mode


fptr = fopen("loremipsum.txt", "r");

// Print some text if the file does not exist


if(fptr == NULL) {
printf("Not able to open the file.");
}

// Close the file


fclose(fptr);

If the file does not exist, the following text is printed:

Not able to open the file.

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;

// Open a file in read mode


fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// If the file exist


if(fptr != NULL) {

// Read the content and print it


while(fgets(myString, 100, fptr)) {
printf("%s", myString);
}

// If the file does not exist


} else {
printf("Not able to open the file.");
}

// Close the file


fclose(fptr);

Hello World!
Hi everybody!

Run example »

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!


Log inSign Up

C Structures (structs)
❮ PreviousNext ❮

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:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and
then the name of the structure variable:

Create a struct variable with the name "s1":

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}
Access Structure Members
To access members of a structure, use the dot syntax (.):

Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// 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
// Create different struct variables
struct myStructure s1;
struct myStructure s2;

// Assign values to different struct variables


s1.myNum = 13;
s1.myLetter = 'B';

s2.myNum = 20;
s2.myLetter = 'C';

Try it Yourself »
What About Strings in Structures?
Remember that strings in C are actually an array of characters, and unfortunately, you can't assign
a value to an array like this:

Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};

int main() {
struct myStructure s1;

// Trying to assign a value to the string


s1.myString = "Some text";

// Trying to print the value


printf("My string: %s", s1.myString);

return 0;
}

An error will occur:

prog.c:12:15: error: assignment to expression with array type


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;

// Assign a value to the string using the strcpy function


strcpy(s1.myString, "Some text");

// Print the value


printf("My string: %s", s1.myString);
return 0;
}

Result:

My string: Some text


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.

In the following example, the values of s1 are copied to s2:


Example
struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2;

s2 = s1;
Try it Yourself »

Modify Values
If you want to change/modify a value, you can use the dot syntax (.).

And to modify a string value, the strcpy() function is useful again:

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
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};

// Create another structure variable


struct myStructure s2;

// 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 »

Ok, so, how are structures useful?


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};

printf("%s %s %d\n", car1.brand, car1.model, car1.year);


printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);

return 0;
}

Try it Yourself »
C Exercises
Test Yourself With Exercises
Exercise:
Fill in the missing part to create a Car structure:

Car {
char brand[50];
char model[50];
int year;
};

Submit Answer »

Start the Exercise

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Enumeration (enum)
❮ PreviousNext ❮
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
};

Note that the last item does not need a comma.

It is not required to use uppercase, but often considered as good practice.

Enum is short for "enumerations", which means "specifically listed".

To access the enum, you must create a variable of it.

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):

enum Level myVar;

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):

enum Level myVar = MEDIUM;

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;

// Print the enum variable


printf("%d", myVar);

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
};
printf("%d", myVar); // Now outputs 50
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 »

Enum in a Switch Statement


Enums are often used in switch statements to check for corresponding values:

enum Level {
LOW = 1,
MEDIUM,
HIGH
};

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 »

Why And When To Use Enums?


Enums are used to give names to constants, which makes the code easier to read and maintain.

Use enums when you have values that you know aren't going to change, like month days, days,
colors, deck of cards, etc.

❮ PreviousNext ❮

W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT

C Examples
❮ PreviousNext ❮

Syntax
Create a simple "Hello World" program
Syntax Explained

Output/Print
Use printf to print textUsing many printf functionsInsert a new line with \n
Output Explained
Comments
Single-line comment before a line of codeSingle-line comment at the end of a line of
codeMulti-line comment
Comments Explained

Variables
Create an integer variable and print itCombine both text and a variableChange/overwrite
variable valuesAdd a variable to another variableDeclare many variables of the same type
with a comma-separated listAssign the same value to multiple variables of the same
typeReal-life variables example
Variables Explained

Data Types and Format Specifiers


A demonstration of different data types and format specifiersSet decimal precision for
floating point valuesImplicit/automatically conversion - convert an int to a
floatExplicit/manually conversion - convert an int to a float
Data Types and Format Specifiers Explained

Constants
Create a constant variableGood practice - use uppercase letters when declaring constants
Constants Explained

Operators
Addition operatorSubtraction operatorDivision operatorModulus operatorIncrement
operatorDecrement operatorAssignment operatorAddition assignment operatorComparison
operatorLogical operatorsUsing the "sizeof" operator to get the memory size of different
variables
Operators Explained
Booleans
Create boolean variablesCompare two valuesCompare two variablesCompare two boolean
variablesReal-life example
Variables Explained

If...Else (Conditions)
The if statementThe else statementThe else if statementShort hand if...else
If...Else Explained

Switch
The switch statementThe switch statement with a default keyword
Switch Explained

Loops
While loopDo while loopFor loopNested loopBreak a loopContinue a loop
Loops Explained

Arrays
Create and access an arrayChange an array elementLoop through an arrayTwo-dimensional
arrayChange elements in a two-dimensional arrayLoop through a two-dimensional array
Arrays Explained

Strings
Create a stringAnother way to create a stringAccess string charactersChange string
charactersLoop through a stringSpecial characters in a stringGet the length of a
stringConcatenate stringsCopy stringsCompare strings
Strings Explained

User Input
Input a number and print the resultInput a string and print the result
User Input Explained

Memory Address/References
Get the memory address of a variable
Memory Address Explained

Pointers
Create a pointer variableGet the value of a variable with the dereference operator *Access an
array with pointersLoop through an array using pointers
Pointers Explained

Functions
Create and call a functionCall a function multiple timesFunction declaration and
definitionParameters and argumentsMultiple parametersPass arrays as function
parametersReturn valueReturn the sum of two parametersRecursion (make a function call
itself)Use a math function to get the square root of a number
Functions Explained

Files
Create a fileWrite to a fileAppend/add content to a fileRead the first line of a fileRead all
lines of a fileGood practice when reading files
Files Explained
Structures
Access a structureCreate multiple structure variables with different valuesString in
structureSimpler Syntax (shorthand)Copy structure valuesModify valuesReal Life Example
Structures Explained

Enums
Create an enum variable and assign a value to itChange the value of enum itemsChange the
value of a specific enum itemEnum in a switch statement
Enums Explained

❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Real-Life Examples
❮ PreviousNext ❮

Practical Examples
This page contains a list of practical examples used in real world projects.

Variables and Data Types


Example
Use variables to store different data of a college student:

// 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
Calculate the area of a rectangle (by multiplying the length and width)

// Create integer variables


int length = 4;
int width = 6;
int area;

// Calculate the area of a rectangle


area = length * width;

// Print the variables


printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d", area);
Try it Yourself »

Example
Use different data types to calculate and output the total cost of a number of items:

// Create variables of different data types


int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';

// 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 »

Example
Calculate the percentage of a user's score in relation to the maximum score in a game:

// Set the maximum possible score in the game to 500


int maxScore = 500;

// The actual score of the user


int userScore = 420;

// Calculate the percantage of the user's score in relation to the


maximum available score
float percentage = (float) userScore / maxScore * 100.0;

// Print the percentage


printf("User's percentage is %.2f", percentage);
Try it Yourself »

For a tutorial about variables and data types in C, visit our Variables Chapter and Data Types
Chapter.

Booleans
Example
Find out if a person is old enough to vote:

int myAge = 25;


int votingAge = 18;

printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year


olds are allowed to vote!
Try it Yourself »

You could also wrap the code above in an if...else to 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.":

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
Try it Yourself »

For a tutorial about booleans in C, visit our Booleans Chapter.

Conditions (If..Else)
Example
Use if..else statements to output some text depending on what time it is:

int time = 20;


if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Try it Yourself »

Example
Check whether the user enters the correct code:

int doorCode = 1337;

if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
Try it Yourself »

Example
Find out if a number is positive or negative:
int myNum = 10;

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
Find out if a person is old enough to vote:

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
Try it Yourself »

Example
Find out if a number is even or odd:

int myNum = 5;

if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
Try it Yourself »

For a tutorial about conditions in C, visit our If..Else Chapter.

Switch
Example
Use the weekday number to calculate and output the weekday name:
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 »

For a tutorial about switch in C, visit our Switch Chapter.

While Loops
Example
Use a while loop to create a simple "countdown" program:

int countdown = 3;

while (countdown > 0) {


printf("%d\n", countdown);
countdown--;
}

printf("Happy New Year!!\n");


Try it Yourself »

Example
Use a while loop to play a game of Yatzy:

int dice = 1;

while (dice <= 6) {


if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yatzy!\n");
}
dice = dice + 1;
}
Try it Yourself »

Example
Use a while loop to reverse some numbers:

// A variable with some specific numbers


int numbers = 12345;

// A variable to store the reversed number


int revNumbers = 0;

// Reverse and reorder the numbers


while (numbers) {
// Get the last number of 'numbers' and add it to 'revNumber'
revNumbers = revNumbers * 10 + numbers % 10;
// Remove the last number of 'numbers'
numbers /= 10;
}
Try it Yourself »

For a tutorial about while loops in C, visit our While Loop Chapter.

For Loops
Example
Use a for loop to create a program that only print even values between 0 and 10:

int i;

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


printf("%d\n", i);
}
Try it Yourself »

Example
Use a for loop to create a program that counts to 100 by tens:

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


printf("%d\n", i);
}

Try it Yourself »

Example
Use a for loop to create a program that prints the multiplication table of a specified number (2 in
this example):

int number = 2;
int i;

// Print the multiplication table for the number 2


for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", number, i, number * i);
}

return 0;
Try it Yourself »

For a tutorial about for loops in C, visit our For Loop Chapter.

Arrays
Example
Create a program that calculates the average of different ages:

// An array storing different ages


int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;


int i;

// Get the length of the array


int length = sizeof(ages) / sizeof(ages[0]);

// Loop through the elements of the array


for (int i = 0; i < length; i++) {
sum += ages[i];
}

// Calculate the average by dividing the sum by the length


4avg = sum / length;

// Print the average


printf("The average age is: %.2f", avg);

Try it Yourself »

Example
Create a program that finds the lowest age among different ages:

// An array storing different ages


int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

// Get the length of the array


int length = sizeof(ages) / sizeof(ages[0]);

// Create a variable and assign the first array element of ages to it


int lowestAge = ages[0];

// 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 »

For a tutorial about arrays in C, visit our Arrays Chapter.

Strings
Example
Use strings to create a simple welcome message:

char message[] = "Good to see you,";


char fname[] = "John";

printf("%s %s!", message, fname);

Try it Yourself »
Example
Create a program that counts the number of characters found in a specific word:

char word[] = "Computer";


printf("The word '%s' has %d characters in it.", word, strlen(word));

Try it Yourself »

For a tutorial about strings in C, visit our Strings Chapter.

User Input
Example
Get the name of a user and print it:

char fullName[30];

printf("Type your full name: \n");


fgets(fullName, sizeof(fullName), stdin);

printf("Hello %s", fullName);

Run example »

For a tutorial about user input in C, visit our User Input Chapter.

Functions
Example
Use a function to create a program that converts a value from fahrenheit to celsius:

// Function to convert Fahrenheit to Celsius


float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}

int main() {
// Set a fahrenheit value
float f_value = 98.8;
// Call the function with the fahrenheit value
float result = toCelsius(f_value);

// Print the fahrenheit value


printf("Fahrenheit: %.2f\n", f_value);

// Print the result


printf("Convert Fahrenheit to Celsius: %.2f\n", result);

return 0;
}

Try it Yourself »

For a tutorial about functions in C, visit our Functions Chapter.

Structures
Example
Use a structure to store and output different information about Cars:

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};

printf("%s %s %d\n", car1.brand, car1.model, car1.year);


printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);

return 0;
}

Try it Yourself »

For a tutorial about structures in C, visit our Structures Chapter.


❮ PreviousNext ❮

W3schools Pathfinder

Track your progress - it's free!

Log inSign Up

ADVERTISEMENT

C Exercises
❮ PreviousNext ❮

You can test your C skills with W3Schools' Exercises.

Exercises
We have gathered a variety of C exercises (with answers) for each C Chapter.

Try to solve an exercise by editing some code, or show the answer to see what you've done
wrong.

Count Your Score


You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start C Exercises
Good luck!
Start C Exercises ❮

If you don't know C, we suggest that you read our C Tutorial from scratch.

❮ PreviousNext ❮

W3schools Pathfinder
Track your progress - it's free!
Log inSign Up
ADVERTISEMENT

You might also like