Defination: A general purpose, procedural programming language developed by Dennis Ritchie in 1972 at Bell Labs. It is used for software, embedded systems and applictions.
Features of c
- It is simple and efficient.
- Supports structured programming.
- Low-leve access to memory.
- Rich set of library function
Basic Structure of C
- Preprocessor directives
- Main Function
- Variables and statements
- Return Statement
Additional Notes
- Each expression must end with semicolon (;).
- Next comes the opening brace ‘{” which indicates the beginning of the function.
- The closing brace ‘}’ indicates the end of the function.
- ‘//……………’ is used for single line remarks.
- ‘/*……………….*/’ is used for multiline remarks.
Preprocessor
The C preprocessor is a text processing tool that is used to modify the source code of a C program before it is compiled. It handle directives for the following in c program
- Source file inclusion (#include)
- Macro definition (#define)
- Conditional inclusion(#if, #ifdef, #elif, #endif)
- Miscellaneous directives (#,pragma, #undef, #error)
File Inclusion
#include<filename> ; in specific directory, if you use DevC++ then in C:/Dev-Cpp/include
#include “filename” ; in specific and current directory(cpp saved files location)
Header Files
A file that is defined to be included at the beginning of a program in C language that contains the definitions of data types and declarations of variables used by the functions in the program is called header file.
It is placed at top of the every program and it’s file extension is ‘.h’
| Header Files | Description | Main functions |
| stdio.h | Standard input and output | gets(), puts(), gstchar(), scanf(), printf(), rename (), etc |
| conio.h | Console input output (for DOS complier) | getch(), getche() |
| math.h | Mathematical calculation | sin(x), log(x), pow(x,2), srt(x), cbrt(x) |
Character Set = alphabet, number, spec
Keywords
The predefined reversed word of c program is called keyword which is directly recognized by compiler. The keywords are written in lowercase. There are 32 keyword in c programming.
| Keyword | Use | Keyword | Use |
|---|---|---|---|
auto | Automatic variable storage duration | break | Exit a loop or switch |
case | Label in a switch statement | char | Declares a character variable |
const | Constant value | continue | Skip the current iteration of a loop |
default | Default label in switch | do | Start a do-while loop |
double | Declares a double precision floating point | else | Defines the else condition in an if-else statement |
enum | Declares an enumerated type | extern | Declares a variable or function that is defined elsewhere |
float | Declares a floating point variable | for | Start a for loop |
goto | Jump to a specific label | if | Conditional statement |
inline | Suggests inlining of a function | int | Declares an integer variable |
long | Declares a long integer | register | Suggests storing a variable in a CPU register |
return | Return from a function | short | Declares a short integer |
signed | Declares a signed variable | sizeof | Returns the size of a data type or variable |
static | Statically allocated variable | struct | Defines a structure |
switch | Start a switch statement | typedef | Define a type alias |
union | Defines a union type | unsigned | Declares an unsigned variable |
void | Specifies an empty return type or function argument type | volatile | Declares a variable whose value can change at any time |
while | Start a while loop |
Identifier
The name given to various elements such as constants, variables, function name, etc rather than keywords called identifier. Identifiers are defined according to the following rules.
- It consists of letter, digit and underscore ‘_’ only.
- First character must be an alphabet or underscore.
- Keywords can not be used as identifier
- Only one special character ‘_’ can use.
- For Example add, sum, num, c12, _at, s_m, etc
Comments in C
- ‘//……………’ is used for single line remarks.
- ‘/*……………….*/’ is used for multiline remarks.
Using C Compilers
Using Browser
Use online OnlineGDB “https://www.onlinegdb.com/” or any other compiler and C as language
Installing Application
- Download and install Dev C++ through the Official Embarcadero Website: “https://www.embarcadero.com/free-tools/dev-cpp” For Windows
- Or use any complier you know for search in internet for help.
Basic Structure of C
//Structure of C
//You can use EITHER
#include<stdio.h> // Preprocessor directives (Header File)
int main() { // Entry point (Main Function)
//Code Statements
return 0; // Return Statement
}
// _________________________________________________________
// OR you can use following
#include<stdio.h> // Preprocessor directives (Header File)
void main() { // Entry point (Main Function)
//Code Statements
//No Return Statement
}
Input and Output in C
// Printing Hello World
#include<stdio.h>
int main() {
printf("Hello World");
return 0; // Return Statement
}
//Display the input prompt to enter input and display output
#include<stdio.h>
int main() {
int a;
printf("Enter the value of a");
scanf("%d", &a);
printf("The value of a is : %d", a);
return 0; // Return Statement
}
Data Types in C
- Primary (Basic) Datatype
- Derived Data Type
- Enumeration Data Type
- User-Defined Data Types
Primary Data Types
| Data Type | Type | Memory |
| void | nothing | 0 |
| char | character | 1 byte |
| int | Integer | 2 or 4 bytes |
| float | Floating point | 4 bytes |
| double | Decimal large | 8 bytes |
Derived Data Types
| Type | Description |
| Array | Collection of union of same data type |
| Pointer | Stores the address of a variable |
| Structure | Combines variables of different types into single unit |
| Union | Similar to structure but uses shared memory |
Enumeration Data Type
// It use keyword : enum
// Example
enum colors{RED, GREEN, BLUE};
enum colors c = RED; // c will have a value of 0
User Defined Data Type
// Created by user to suit specific requirements.
// "typedef" is used to give a new name to an existing data type.
//Example
typedef int age; // here "age" become new data type where age behave integer
age prson_age = 25;
//__________________________________________________
//"
Modifiers in Data Types
Modifiers alter the size and range of primary data types. They are:
signed, unsigned, short, long.
| Modifier | Data Type | Size (in bytes) | Range |
|---|---|---|---|
| short int | int | 2 | -32,768 to +32,767 |
| unsigned int | int | 2 or 4 | 0 to 65,535 (2 bytes) or 0 to 4,294,967,295 (4 bytes) |
| long int | int | 4 | -2,147,483,648 to +2,147,483,647 |
| unsigned long int | int | 4 | 0 to 4,294,967,295 |
| signed char | char | 1 | -128 to +127 |
| unsigned char | char | 1 | 0 to 255 |
Using data type in variable declaration
Constant Declaration → const int a= 5; //constant integer
Variable Declaration → int a= 5; //variable declartion
Local variable → Declared within the function
Global variable → Declared outside the function
//To assign integer value to variable and print it.
#include<stdio.h>
main()
{
int x= 5; //variable declaration
printf("value of x=%d",x);
return 0;
}
Types of specifier
It is used to format input and output in screen. It is of two types; escape sequence(format nonprintable character) and format specifier(format printable character)
Escape Sequence
| Escape Sequence | Meaning /normally used by printf() function |
| \’ | Pint ‘ in output |
| \” | Print ” in output |
| \0 | Terminate string |
| \n | New line in output display |
| \t | Create tab or 8 space in print output |
Format Specifier
| Format Sequence | Meaning /normally used by scanf() and printf() function |
| %d, %i | signed integer with + or – sign |
| %u | unsigned integer without + or – sign |
| %f | float number |
| %e | exponent number |
| %o | octal integer |
| %c | single character |
| %s | string |
Uses of Format Specifier in C
| Example | Output |
| printf(“%d”, a); | 12345678 |
| printf(“%10d”, a); | 12345678 |
| printf(“%-10d”, a); | 12345678 |
| printf(“%f”, a); | 1.2345678 |
| printf(“%5.3f”, a); | 1.234 |
| printf(“%x”, a); | BC614E |
| printf(“%s”, c); | COMPUTER |
Operators
| Operator | Function |
| + | Add |
| – | Substract |
| * | Multiply |
| / | Divide |
| % | Reminder of Division |
| Operator | Function |
| == | Return true if both are equal |
| != | Return true if both are unequal |
| < | Return true if first value is less |
| > | Return true if first value is greater |
| <= | Return true if first value is less or equal to second value |
| >= | Return true if first value is greater or equal to second value |
| Operator | Function |
| && | AND Logic |
| || | OR Logic |
| ! | NOT Logic |
Increment Operator
++ is used as increment operator, it increase the value of variable by 1. Example; i++, a++ (post increment), ++i, ++a (pre increment).
Decrement Operator
— is used as decrement operator, it decrease the value of variable by 1. Example; i–, a– (post decrement), –i, –a (pre decrement).
Input Output Function
| Function | Uses | Type |
| printf() | To print | Formatted Output |
| scanf() | To assign input value | Formatted Input |
| getch() | Get Character; hold output screen for next line until user press any key. It doesn’t echo(display) character during entry. Can be used instead of scanf() for single character | Unformatted Input |
| getche() | Get Character; hold output screen for next line until user press any key. It echo(display) character during entry. Can be used instead of scanf() for single character | Unformatted Input |
| putch() | Put Character; Print Single Character | Unformatted Output |
| getchar() | To read character from keyboard | Unformatted Input |
| putchar() | To print character on monitor | Unformatted Output |
| gets() | To read single or multiple word from keyboard | Unformatted Input |
| puts() | To print single or multiple word on monitor | Unformatted Output |
Example 1
//Ask two integer and find it's sum
#include<stdio.h>
int main()
{
int a, b, sum;
printf("Enter first integer=");
scanf("%d",&a);
printf("Enter first integer=");
scanf("%d",&b);
sum = a+ b;
printf("%d+%d = %d",a,b,sum);
return 0;
}
Conditional Statements
1. if Statement
if (condition) {
// code to execute if condition is true
}
#include<stdio.h>
int main()
{
int n;
printf("Enter marks= ");
scanf("%d",&n);
if(n>=35){
printf("You are passed");
}
if(n<35){
printf("You are failed");
}
return 0;
}
2. if -else Statement
if (condition) {
// code if true
} else {
// code if false
}
#include<stdio.h>
int main()
{
int n;
printf("Enter marks= ");
scanf("%d",&n);
if(n>=35){
printf("You are passed");
}
else{
printf("You are failed");
}
return 0;
}
3. if – else if -else Statement
if (condition) {
// code if true
} else if {
// code if true
}
else if {
// code if true
}
else if {
// code if true
}
else if {
// code if true
}
else {
// code if false
}
#include<stdio.h>
int main()
{
int n;
come_back:
printf("\nEnter marks= ");
scanf("%d",&n);
if(n>=90 && n<=100){
printf("Your grade is: A+");
}
else if(n>=80 && n<90){
printf("Your grade is: A");
}
else if(n>=70 && n<80){
printf("Your grade is: B+");
}
else if(n>=60 && n<70){
printf("Your grade is: B");
}
else if(n>=50 && n<60){
printf("Your grade is: C+");
}
else if(n>=40 && n<50){
printf("Your grade is: C");
}
else if(n>=35 && n<40){
printf("Your gradr is: D");
}
else if(n>=1 && n<35){
printf("Non Graded");
}
else{
printf("Invalid Entry; Please Enter number between 1-100");
}
goto come_back;
return 0;
}
4. switch Statement
#include <stdio.h>
int main() {
int date;
printf("Enter date number 1-7: ");
scanf("%d",&date);
switch (date) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid Entry. Please enter date code 1-7 only\n");
break;
}
return 0;
}
Looping Statement
1. for Loop
for (initialization; condition; increment) {
// code
}
#include <stdio.h>
int i;
int main() {
for (i=1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
2. while Loop
while (condition) {
// code
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
3. do while Loop
do {
// code
} while (condition);
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Array
1. One Dimensional Array
data_type array_name[size];
#include <stdio.h>
int main() {
// Declare an array of integers with 5 elements
int num[5] = {65, 14, 22, 49, 51};
printf("The third(3) number is: %d",num[2]);
// Loop through the array and print each element
for (int i = 0; i < 5; i++) {
printf("\nElement at index %d: %d", i, num[i]);
}
return 0;
}
2. Two Dimensional Array (Matrix)
data_type array_name[rows][columns];
#include <stdio.h>
int main() {
// Declare a 2D array with 3 rows and 4 columns
int matrixA[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("MatrixA(2,3) is: %d",matrixA[1][2]);
// Loop through the array and print each element
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("\nElement at [%d][%d]: %d", i, j, matrixA[i][j]);
}
}
// Display the matrix in standard matrix form
printf("\nMatrix A:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrixA[i][j]);
}
printf("\n");
}
return 0;
}
3. Multi Dimensional Array
a. 3D Array
int cube[2][3][4]; // A 3D array with 2 layers, 3 rows, and 4 columns per layer.
#include <stdio.h>
int main() {
// Declare a 3D array with 2 pages, 3 rows, and 4 columns
int matrix[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
// Loop through the array and print each element
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
printf("Element at [%d][%d][%d]: %d\n", i, j, k, matrix[i][j][k]);
}
}
}
return 0;
}
Addition of Matrix
#include <stdio.h>
int main() {
// Declare and initialize two 2x2 matrices
int matrixA[2][2] = {{1, 2}, {3, 4}};
int matrixB[2][2] = {{5, 6}, {7, 8}};
int result[2][2]; // Matrix to store the result
// Add the two matrices
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
// Display the first matrix
printf("Matrix A:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrixA[i][j]);
}
printf("\n");
}
// Display the second matrix
printf("Matrix B:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrixB[i][j]);
}
printf("\n");
}
// Display the result matrix
printf("Result Matrix (Matrix A + Matrix B):\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Functions in C
A function in C is a block of code designed to perform a specific task. It enhances code reusability, modularity, and readability. Functions divide a large program into smaller, manageable pieces.
Key Features of Functions
- Modularity: Breaks down the program into smaller, reusable blocks.
- Reusability: Functions can be called multiple times in a program, reducing code repetition.
- Easier Debugging: Errors are easier to isolate and fix in modular code.
Types of Functions in C
- Library Functions: Predefined functions provided by C (e.g.,
printf(),scanf(),strlen()). - User-Defined Functions: Functions created by the programmer for specific tasks.
Structure of a Function
A function consists of three parts:
Function Declaration (Prototype): Describes the function’s name, return type, and parameters.
int add(int a, int b);
Function Definition: Contains the actual code to perform the task.
int add(int a, int b){
return a + b;
}
Function Call: Invokes the function to execute its code.
int result = add(5, 3);
printf("Result: %d", result);
Syntax of a Function
return_type function_name(parameters) { //return type: void, int, char etc
// Body of the function
return value; // Optional
}
Passing Arguments to Functions
Pass by Value: Copies the value of the argument into the function. Changes made inside the function do not affect the original variable.
void display(int x) {
x = x + 10; // Changes only the local copy
printf("%d", x); }
Pass by Reference: Passes the address of the variable. Changes made inside the function affect the original variable.
void increment(int *x) {
(*x)++; }
Function Example
#include <stdio.h>
// Function declaration
int multiply(int a, int b);
int main() {
int x = 5, y = 10;
int result = multiply(x, y); // Function call
printf("Result: %d\n", result);
return 0;
}
// Function definition
int multiply(int a, int b) {
return a * b;
}
