C programming Tutorial |Beginners

Web C programming

C programming is a general-purpose, procedural computer programming language used for operating systems, system programming, and applications.

Here is a simple program that prints “Hello, World!” to the console:

#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
return 0;
}

To compile and run this program, you can use a C compiler such as GCC. For example, you can compile the program by running the following command:

gcc main.c -o main

This will create an executable file called “main” that you can run with the following command:

./main

The output of the program will be “Hello, World!”

Syntax

  • Variables: Variables are used to store values in C. They must be declared with a specific data type before they can be used. For example:
int x;
float y;
char z;

In this example, x is an integer variable, y is a floating-point variable, and z is a character variable.

  • Data types: C has a variety of built-in data types, including integers (int), floating-point numbers (float), and characters (char). Here are some examples of declaring variables with different data types:
int x = 10; // integer

float y = 3.14; // floating-point
char z = 'a'; // character
  • Operators: C supports a range of operators for performing operations such as assignment, arithmetic, and comparison. Here are some examples:
x = y + z; // assignment operator

i++; // increment operator

a == b; // comparison operator

In the first example, the assignment operator = is used to assign the value of y + z to x. In the second example, the increment operator ++ is used to increase the value of i by 1. In the third example, the comparison operator == is used to check if a is equal to b.

  • Control structures: C has several control structures for controlling the flow of a program, including if statements, for loops, and while loops. Here are some examples:
if (x > y)
{
printf("x is greater than y\n");
}
else
{
printf("x is not greater than y\n");
}
for (int i = 0; i < 10; i++)
{
printf("%d ", i);
}
while (x < 10)
{
x++;
printf("%d ", x);
}

In the first example, the if statement is used to check if x is greater than y. If it is, the program will print “x is greater than y”, otherwise it will print “x is not greater than y”.

In the second example, the for loop is used to iterate over a range of values. The loop will execute 10 times, starting at 0 and ending at 9.

In the third example, the while loop is used to execute a block of code while a certain condition is true. The loop will execute until x is no longer less than 10.

  • Functions: Functions are blocks of code that can be called from other parts of a program. They can take parameters and return a value. Here is an example of a function that takes two integers as parameters and returns their sum:
int sum(int a, int b)
{
return a + b;
}
int main(void)
{
int x = sum(1, 2);
printf("%d\n", x);
return 0;
}

In this example, the function sum takes two integers, a and b, and returns their sum. The function is called from the

Output (Print Text)

In C, you can use the printf function to print text to the console. Here’s an example:

#include <stdio.h>

int main()

{
printf("Hello, world!\n");
return 0;
}

This code will print the string “Hello, world!” followed by a newline to the console.

You can also use the puts function to print a string, but it will automatically add a newline at the end of the string. For example:

#include <stdio.h>
int main()
{
puts("Hello, world!");
return 0;
}

Both of these examples will produce the same output when run.

New Lines

In C, you can use the newline character '\n' to create a new line in a string. For example:

#include <stdio.h>

int main()

{
printf("Hello,\nworld!\n");
return 0;
}

This code will print “Hello,” on the first line, and “world!” on the second line.

You can also use the "\r" escape sequence to move the cursor to the beginning of the current line without creating a new line. For example:

#include <stdio.h>
int main()
{
printf("Hello,\rworld!\n");
return 0;
}

This will print “world!” on the same line as “Hello,” overwriting the text that was previously there.

Finally, you can use the "\r\n" escape sequence to create a new line on Windows systems. This is necessary because Windows uses a different line ending than other operating systems (e.g. Linux, macOS).

#include <stdio.h>

int main()

{
printf("Hello,\r\nworld!\n");
return 0;
}

This will print “Hello,” on the first line, and “world!” on the second line on a Windows system.

Comments

In C, you can add comments to your code to explain what the code is doing or to temporarily disable certain lines of code.

There are two types of comments in C: single-line comments and multi-line comments.

Single-line comments start with // and continue until the end of the line. For example:

#include <stdio.h>
int main()
{
// This is a single-line comment
printf("Hello, world!\n");
// This is also a single-line comment
return 0;
}

Multi-line comments start with /* and end with */. Everything in between these two symbols is considered a comment. For example:

#include <stdio.h>

int main()

{
/*
This is a multi-line
comment.
It can span
multiple lines.
*/

printf("Hello, world!\n");
return 0;
}

Comments are ignored by the compiler and are not included in the compiled program. They are only there to help human readers understand the code.

Variables

In C, a variable is a named storage location that holds a value of a particular type. The type of a variable determines the size and layout of the memory allocated to hold the value, as well as the set of operations that can be performed on the value.

There are several different types of variables in C, including:

  • char: A single byte that can hold a character value, such as ‘A’ or ‘B’.
  • int: A integer value, such as 123 or -456. The size of an int varies depending on the system, but it is usually at least 16 bits.
  • float: A floating-point value, such as 3.14 or -2.718. The size of a float is usually 32 bits.
  • double: A double-precision floating-point value, which is a more precise representation of a float. The size of a double is usually 64 bits.

To declare a variable in C, you use the following syntax:

type variable_name;

For example:

int age;
float temperature;
double income;

You can also initialize a variable when you declare it by assigning it a value:

int age = 30;
float temperature = 98.6;
double income = 50000.00;

Once you have declared a variable, you can use it to store and manipulate data in your C program

Data Types

C has a variety of data types that can be used to store different kinds of values. The most common data types in C are:

  • char: A single byte that can hold a character value, such as ‘A’ or ‘B’.
  • int: An integer value, such as 123 or -456. The size of an int varies depending on the system, but it is usually at least 16 bits.
  • float: A floating-point value, such as 3.14 or -2.718. The size of a float is usually 32 bits.
  • double: A double-precision floating-point value, which is a more precise representation of a float. The size of a double is usually 64 bits.

C also has several other data types, including short, long, and long long, which are variations of int with different sizes; unsigned, which allows you to store only non-negative integers; and _Bool, which can hold the values 0 (false) and 1 (true).

In addition to these basic data types, C also has several derived data types, which are created by combining other data types in different ways. These include:

  • array: An ordered sequence of values of the same type, such as an array of integers or an array of characters.
  • struct: A composite data type that groups together different values, possibly of different types, into a single entity.
  • union: A composite data type that allows you to store different values in the same memory location, with the caveat that only one of the values can be used at a time.
  • pointer: A value that stores the memory address of another value, allowing you to indirectly access and modify the value.

C also has a few special data types, such as void, which indicates the absence of a value, and enum, which allows you to define a set of named integer constants

Type Conversion

In C, type conversion refers to the process of converting a value from one data type to another. This can be necessary when you are working with values of different types and need to ensure that they are compatible before performing an operation on them.

C has a set of built-in type conversion functions that allow you to explicitly convert values from one type to another. The most common type conversion functions are:

  • (int): Converts a value to an integer.
  • (float): Converts a value to a floating-point value.
  • (double): Converts a value to a double-precision floating-point value.
  • (char): Converts a value to a character.

For example, the following code converts a float value to an int:

float x = 3.14;
int y = (int)x; // y is now 3

C also supports implicit type conversion, which occurs when a value is automatically converted to the appropriate type as needed. This can happen when you assign a value to a variable, pass an argument to a function, or perform an operation on values of different types.

For example, the following code uses implicit type conversion to add an int and a float:

int x = 3;
float y = 2.718;
float z = x + y; // z is now 5.718

It’s important to be aware of type conversion in C, as it can affect the behavior of your code and lead to unintended results if not used correctly.

Constants

In most programming languages, a constant is a value that cannot be changed once it is set. Constants are usually used to represent values that are used multiple times within a program, but whose values should not be changed.

Here is an example of how to define and use a constant in C:

#define PI 3.14159265
int main()
{
float radius = 10.0;
float circumference = 2 * PI * radius;
printf("Circumference of circle with radius %f is %f\n", radius, circumference);
return 0;
}

In this example, the constant PI is defined using the #define preprocessor directive. It is then used to calculate the circumference of a circle with a radius of 10.0. The value of PI cannot be changed within the program.

Operators

In C, operators are special symbols that perform specific operations on one, two, or three operands, and produce a result.

Here are some examples of common operators in C:

  • Arithmetic operators: +, -, *, /, % (modulus)
  • Comparison operators: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
  • Logical operators: && (and), || (or), ! (not)
  • Assignment operator: =

Here is an example of how to use some of these operators in C:

#include <stdio.h>

int main()

{
int x = 10;
int y = 5;
int z = 2;
// Arithmetic operators
int sum = x + y; // sum is 15
int difference = x - y; // difference is 5
int product = x * y; // product is 50
int quotient = x / y; // quotient is 2

int remainder = x % z; // remainder is 0
// Comparison operators
int a = 5;
int b = 10;
int c = 5;
printf("a == b is %d\n", a == b); // a == b is 0 (false)
printf("a != b is %d\n", a != b); // a != b is 1 (true)
printf("a > b is %d\n", a > b); // a > b is 0 (false)
printf("a < b is %d\n", a < b); // a < b is 1 (true)
printf("a >= b is %d\n", a >= b); // a >= b is 0 (false)
printf("a <= b is %d\n", a <= b); // a <= b is 1 (true)
printf("a == c is %d\n", a == c); // a == c is 1 (true)
// Logical operators
int d = 1;
int e = 0;
printf("d && e is %d\n", d && e); // d && e is 0 (false)
printf("d || e is %d\n", d || e); // d || e is 1 (true)
printf("!d is %d\n", !d); // !d is 0 (false)
printf("!e is %d\n", !e); // !e is 1 (true)
// Assignment operator
int f = 10;
f = 5; // f is now 5
return 0;
}

Booleans

In C, there is no built-in boolean data type. Instead, boolean values are represented using the int data type, with a value of 0 representing false and a value of 1 representing true.

Here is an example of how you can use boolean values in C:

#include <stdio.h>

int main()

{
int is_even = 0;
int num = 10;
if (num % 2 == 0)
{
is_even = 1;
}
if (is_even)
{
printf("%d is even.\n", num);
}
else
{
printf("%d is odd.\n", num);
}
return 0;
}

In this example, the is_even variable is used to store a boolean value indicating whether the number num is even or odd. The value of is_even is set to 1 (true) if num is even, and 0 (false) otherwise. The if statement is then used to test the value of is_even and print the appropriate message.

If … Else

The if...else statement in C is used to execute a block of code conditionally. It allows you to specify a condition, and then two blocks of code: one that will be executed if the condition is true, and another that will be executed if the condition is false.

Here is the syntax for an if...else statement in C:

if (condition)
{
// code to be executed if condition is true
}
else

{
// code to be executed if condition is false

}

Here is an example of how to use an if...else statement in C:

#include <stdio.h>

int main()


{
int num = 10;
if (num > 0)
{
printf("%d is positive.\n", num);
}
else

{
printf("%d is not positive.\n", num);
}
return 0;
}

In this example, the if statement checks if the value of num is greater than 0. If it is, the message “10 is positive.” is printed. If it is not, the message “10 is not positive.” is printed instead.

Short Hand If Else

In C, you can use a shorthand version of the if...else statement, known as the ternary operator or conditional operator. This operator allows you to write an if...else statement in a single line of code.

Here is the syntax for the ternary operator in C:

variable = (condition) ? value_if_true : value_if_false;

The condition is evaluated first. If it is true, the value_if_true is assigned to variable. If it is false, the value_if_false is assigned to variable instead.

Here is an example of how to use the ternary operator in C:

#include <stdio.h>
int main()
{
int num = 10;
char *sign = (num > 0) ? "positive" : "negative";

printf("%d is %s.\n", num, sign);

return 0;

}

In this example, the ternary operator is used to assign the string “positive” to the sign variable if num is greater than 0, or “negative” if it is not. The resulting message “10 is positive.” is then printed to the console.

Switch

The switch statement in C is used to execute a block of code based on the value of an expression. It allows you to specify multiple cases, and the code associated with each case will be executed if the value of the expression matches the case.

Here is the syntax for a switch statement in C:

switch (expression)
{
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
...
default:
// code to be executed if expression does not match any of the cases
break;
}

The break statement is used to exit the switch statement once a match has been found. If it is omitted, the code for all subsequent cases will be executed as well.

Here is an example of how to use a switch statement in C:

#include <stdio.h>
int main()
{
int num = 10;
switch (num)
{
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 10:
printf("Ten\n");
break;
default:
printf("Other\n");
break;
}
return 0;
}

In this example, the switch statement checks the value of num. If it is 1, the message “One” is printed. If it is 2, the message “Two” is printed. If it is 10, the message “Ten” is printed. If it is none of these values, the message “Other” is printed.

While Loop

Here is an example of a while loop in C:

#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i++;
}
return 0;
}

This program will print the numbers 1 through 5, each on a separate line. The while loop continues to execute as long as the condition i <= 5 is true. The variable i is incremented by 1 each time the loop executes using the i++ statement. When i becomes greater than 5, the loop will exit and the program will continue with the next statement after the loop.

Output:

1
2
3
4
5

For Loop

Here is an example of a for loop in C:

#include <stdio.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
return 0;
}

This program will print the numbers 1 through 5, each on a separate line. The for loop uses a compact syntax that includes all the loop control information in a single line. The loop control variables are initialized to 1, the loop continues as long as i is less than or equal to 5, and i is incremented by 1 each time the loop executes.

The loop control variables are defined as follows:

  • int i = 1;: Initializes the loop control variable i to 1. This statement is executed before the loop begins.
  • i <= 5;: The loop continues as long as this condition is true.
  • i++: Increments the loop control variable by 1. This statement is executed after the loop body.

Output:

1
2
3
4
5

Break and Continue

The break and continue statements are used to control the flow of a loop in C.

Here is an example using the break statement:

#include <stdio.h>

int main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break;
}
printf(“%d\n”, i);
}

return 0;
}

This program will print the numbers 1 and 2, and then exit the loop when i becomes 3. The break statement terminates the loop and causes the program to continue with the next statement after the loop.

Output:

1
2

Here is an example using the continue statement:

#include <stdio.h>
int main()

{
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
{
continue;
}
printf("%d\n", i);
}
return 0;
}

This program will print the odd numbers from 1 to 5. The continue statement skips the remaining statements in the loop body and goes to the next iteration of the loop.

Output:

1
3
5

Arrays

An array in C is a collection of data items that are stored at contiguous memory locations and all of which are of the same data type. In C, an array is a collection of variables of the same type that are stored at contiguous memory locations and that can be accessed individually or as a whole.

The elements of an array are accessed by their index, which is a non-negative integer. The first element of an array is at index 0, the second element is at index 1, and so on.

Here is an example of declaring an array in C:

int arr[5]; // Declares an array of size 5

This declares an array of 5 integers and assigns them default values of 0. You can also initialize the array with specific values when you declare it, like this:

int arr[5] = {1, 2, 3, 4, 5}; // Initializes the array with values 1, 2, 3, 4, and 5

You can also specify the size of the array by using a variable instead of a constant value:

int size = 5;
int arr[size]; // Declares an array of size 5

To access an element of the array, you use the array name and the index of the element in square brackets:

arr[0] = 10; // Assigns the value 10 to the first element of the array

int x = arr[3]; // x is assigned the value of the fourth element of the array (4)

You can also use a loop to access all the elements of the array:

for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]); // Prints all the elements of the array
}

Multidimensional Arrays

A multidimensional array in C is an array of arrays. It is an array with more than one dimension.

The elements of a multidimensional array are accessed using multiple indices. For example, in a two-dimensional array, the elements are accessed by using two indices: one for the row and one for the column.

Here is an example of declaring a two-dimensional array in C:

int arr[3][3]; // Declares a 2D array of size 3x3

This declares a 2D array with 3 rows and 3 columns and assigns them default values of 0. You can also initialize the array with specific values when you declare it, like this:

int arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Initializes the array with values 1, 2, 3, 4, 5, 6, 7, 8, and 9

You can access the elements of a multidimensional array using multiple indices in square brackets:

arr[0][0] = 10; // Assigns the value 10 to the element at row 0 and column 0
int x = arr[1][2]; // x is assigned the value of the element at row 1 and column 2 (6)

You can use nested loops to access all the elements of a multidimensional array:

for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
{
printf("%d ", arr[i][j]); // Prints all the elements of the array

}
}

Strings

n C, a string is a null-terminated array of characters. It is a sequence of characters that is treated as a single data type.

To declare a string in C, you can use an array of characters, like this:

char str[6] = "hello"; // Declares a string with the characters 'h', 'e', 'l', 'l', 'o', and a null character

In this example, the string has a size of 6 because it includes the null character at the end.

You can also use a string literal to declare a string, like this:

char *str = "hello"; // Declares a string with the characters 'h', 'e', 'l', 'l', 'o', and a null character

In this case, the string is stored in read-only memory and cannot be modified.

To access the characters of a string, you can use an index in square brackets:

char c = str[0]; // c is assigned the value 'h'
str[1] = 'a';// Changes the second character of the string to ‘a’

You can also use the %s format specifier to print a string with the printf() function:

printf("%s", str); // Prints the string "hello"

You can use the strlen() function to get the length of a string (excluding the null character):

int length = strlen(str); // length is assigned the value 5

Special Characters

In C, special characters are characters that have a special meaning in the language, such as newline, tab, and null.

Here are some examples of special characters in C:

  • \n: Newline character. It is used to move the cursor to the beginning of the next line.
  • \t: Tab character. It is used to move the cursor to the next tab stop.
  • \0: Null character. It is used to mark the end of a string.
  • \\: Backslash character. It is used to escape other special characters.
  • \': Single quote character. It is used to represent a single character inside single quotes.
  • \": Double quote character. It is used to represent a string inside double quotes.

Here is an example of using special characters in a string in C:

printf("Hello\nWorld\n"); // Prints "Hello" on one line and "World" on the next

In this example, the \n character is used to move the cursor to the next line after printing “Hello”.

I hope this helps! Let me know if you have any more questions about special characters in C.

String Functions

In C, there are several functions that you can use to manipulate strings. Here are some examples:

  • strlen(): This function returns the length of a string (excluding the null character). For example:
#include <string.h>
int main()
{
char str[6] = "hello";
int length = strlen(str); // length is assigned the value 5
return 0;
}
  • strcpy(): This function copies one string to another. For example:
#include <string.h>
int main()
{
char str1[6] = "hello";
char str2[6];
strcpy(str2, str1); // Copies str1 to str2
return 0;
}
  • strcat(): This function concatenates (joins) two strings. For example:
#include <string.h>
int main()
{
char str1[6] = "hello";
char str2[6] = ", world";
strcat(str1, str2); // Concatenates str2 to str1
return 0;
}
  • strcmp(): This function compares two strings. It returns 0 if the strings are equal, a negative value if the first string is lexicographically (alphabetically) less than the second, and a positive value if the first string is lexicographically greater than the second. For example:
#include <string.h>
int main()
{
char str1[6] = "hello";
char str2[6] = "hello";
int cmp = strcmp(str1, str2); // cmp is assigned the value 0
return 0;
}

I hope this helps! Let me know if you have any more questions about string functions in C.

User Input

There are several ways to get user input in C. Here are some examples:

  • scanf(): This function reads input from the standard input (usually the keyboard) and stores it in a variable. For example:
#include <stdio.h>

int main()

{
int x;
printf("Enter a number: ");
scanf("%d", &x); // Reads an integer from the standard input and stores it in x
printf("You entered: %d\n", x);
return 0;
}
  • fgets(): This function reads a line of input from the standard input (up to a specified number of characters) and stores it in a string. For example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin); // Reads a line of input (up to 100 characters) and stores it in str

printf("You entered: %s", str);
return 0;
}
  • getchar(): This function reads a single character from the standard input and returns it as an integer. For example:
#include <stdio.h>
int main()
{
int c;
printf("Enter a character: ");
c = getchar(); // Reads a single character from the standard input and stores it in c
printf("You entered: %c\n", c);
return 0;
}

Memory Address

n C, a memory address is a numerical value that represents the location of a memory location in the computer’s memory.

You can use the & operator to get the memory address of a variable. For example:

int x = 10;
int *ptr = &x; // ptr is assigned the memory address of x

In this example, ptr is a pointer to an integer, and it is assigned the memory address of x.

You can use the * operator to dereference a pointer and access the value stored at the memory address it points to. For example:

int y = *ptr; // y is assigned the value of x (10)

You can also use the %p format specifier to print the memory address of a variable with the printf() function. For example:

printf("The memory address of x is: %p\n", &x); // Prints the memory address of x

I hope this helps! Let me know if you have any more questions about memory addresses in C.

Pointers

n C, a pointer is a variable that stores the memory address of another variable. Pointers are used to store the addresses of memory locations in order to access the values stored there.

To declare a pointer in C, you use the * operator. For example:

int x = 10;
int *ptr; // Declares a pointer to an integer

To assign the memory address of a variable to a pointer, you use the & operator. For example:

ptr = &x; // Assigns the memory address of x to ptr

You can use the * operator to dereference a pointer and access the value stored at the memory address it points to. For example:

int y = *ptr; // y is assigned the value of x (10)

You can also use the * operator to modify the value stored at the memory address pointed to by a pointer. For example:

*ptr = 20; // Changes the value of x to 20

Functions

In C, a function is a block of code that performs a specific task. Functions are used to modularize the code and make it easier to read, write, and maintain.

To define a function in C, you use the following syntax:

return_type function_name(parameter_list)
{
// function body
// ...
return value;
}

Here is an example of a function that adds two integers and returns the result:

int add(int x, int y)
{
// The function has two parameters, x and y, of type int
int result = x + y; // The function performs the task of adding x and y
return result; // The function returns the result
}

To call a function in C, you use its name followed by a list of arguments in parentheses. For example:

int a = 3;
int b = 5;
int c = add(a, b); // Calls the add function with arguments a and b, and assigns the result to c

You can also define a function with no parameters or a function with no return value. For example:

void print_hello()
{
// A function with no parameters
printf("Hello, world!\n");
}
int add(int x, int y)
{
// A function with no return value
printf("The sum of %d and %d is %d\n", x, y, x + y);
}

Parameters and Arguments

In C, function parameters are variables that are declared in the function definition and that receive the values of the arguments passed to the function when it is called.

For example, consider the following function definition:

int add(int x, int y)
{
int result = x + y;
return result;
}

In this example, the function add() has two parameters, x and y, both of type int.

When you call the function, you pass it arguments, which are the values that are passed to the function. For example:

int a = 3;
int b = 5;
int c = add(a, b); // Calls the add function with arguments a and b

In this example, the arguments passed to the add() function are a and b. The values of the arguments (3 and 5) are assigned to the parameters x and y, respectively.

The number and types of the arguments must match the number and types of the parameters in the function definition. If there is a mismatch, the compiler will generate an error.

Function Declaration and Definition

In C, a function declaration (also called a function prototype) is a statement that provides the compiler with the information it needs to check the syntax of function calls. It specifies the function’s name, return type, and parameters.

A function definition, on the other hand, is the actual implementation of the function, where the function’s code is written.

Here is an example of a function declaration and a function definition in C:

// Function declaration
int add(int x, int y);
// Function definition
int add(int x, int y)
{
int result = x + y;
return result;
}

In this example, the function add() is declared with the int add(int x, int y); statement, which specifies that it takes two int arguments and returns an int value. The function is defined with the int add(int x, int y) statement, which specifies the function’s code.

You can also define a function and declare it at the same time by including the function’s code in the declaration. For example:

int add(int x, int y)
{
// Function declaration and definition
int result = x + y;
return result;
}

It is a good practice to declare functions before you use them, so that the compiler knows the function’s prototype and can check the syntax of the function calls.

I hope this helps! Let me know if you have any more questions about function declarations and definitions in C.

Recursion

Recursion is a programming technique in which a function calls itself with a different set of arguments in order to solve a problem.

In C, you can use recursion to solve problems that can be divided into smaller subproblems that can be solved in a similar way.

Here is an example of a recursive function in C that calculates the factorial of a number:

int factorial(int n) {
if (n == 0)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}

In this example, the function factorial() calls itself with the argument n - 1 until the base case n == 0 is reached, at which point it returns 1. The result of each recursive call is then multiplied by the value of n and returned.

To call the factorial() function, you can use the following code:

int x = 5;
int result = factorial(x); // result is assigned the value 120 (5! = 5 x 4 x 3 x 2 x 1)

Recursion can be a powerful tool, but it can also be inefficient if not used correctly. It is important to make sure that the base case is reached and to use an appropriate data type for the function’s return value.

Math Functions

n C, you can use the math library (math.h) to perform various mathematical operations, such as trigonometric functions, logarithms, and square roots.

To use the math library in your C program, you need to include the math.h header file at the beginning of your code. For example:

#include <math.h>

Here are some examples of math functions that you can use in C:

  • sin(): Calculates the sine of an angle.
  • cos(): Calculates the cosine of an angle.
  • tan(): Calculates the tangent of an angle.
  • exp(): Calculates the exponent of a number.
  • log(): Calculates the natural logarithm of a number.
  • log10(): Calculates the base-10 logarithm of a number.
  • sqrt(): Calculates the square root of a number.

Here is an example of using math functions in C:

#include <stdio.h>

#include <math.h>
int main()
{
double x = 1.5;
double y = sin(x); // y is assigned the sine of x
double z = cos(x); // z is assigned the cosine of x

printf("The sine of %f is %f\n", x, y);
printf("The cosine of %f is %f\n", x, z);
return 0;
}

In this example, the program calculates the sine and cosine of the angle x and prints the results.

Structures (structs)

n C, a structure (or struct) is a user-defined data type that can store a collection of related data items of different types. Structures are used to represent complex data structures, such as records, in a program.

To define a structure in C, you use the struct keyword followed by the name of the structure and a list of fields inside curly braces. Each field represents a member of the structure and has a name and a type. For example:

struct point {
int x;
int y;
};

In this example, the structure point has two members, x and y, both of type int.

To create a variable of a structure type, you use the name of the structure followed by a variable name. For example:

struct point p; // Declares a variable p of type struct point

To access the members of a structure, you use the dot operator (.). For example:

p.x = 10; // Assigns the value 10 to the member x of the structure p
p.y = 20; // Assigns the value 20 to the member y of the structure p

You can also define a structure and create a variable of that type in a single statement:

struct point {
int x;
int y;
} p; // Declares a variable p of type struct point

Enumeration (enum)

In C, an enumeration (or enum) is a user-defined data type that consists of a set of named constants. Enumerations are used to define a set of values that a variable can take and to make the code more readable.

To define an enumeration in C, you use the enum keyword followed by the name of the enumeration and a list of constants inside curly braces. Each constant is called an enumerator and has a name and an optional value. If no value is specified, the constants are assigned values starting from 0. For example:

enum color {
RED, // 0
GREEN, // 1
BLUE // 2
};

In this example, the enumeration color has three constants: RED, GREEN, and BLUE.

To create a variable of an enumeration type, you use the name of the enumeration followed by a variable name. For example:

enum color c; // Declares a variable c of type enum color

To assign a value to an enumeration variable, you use one of the constants defined in the enumeration. For example:

c = RED; // Assigns the value RED (0) to the variable c

You can also define an enumeration and create a variable of that type in a single statement:

enum color
{
RED, // 0
GREEN, // 1
BLUE // 2
}
c; // Declares a variable c of type enum color

I hope this helps! Let me know if you have any more questions about enumerations in C.

for more detail: click here

Home

Scroll to Top