Introduction to C Programming Language

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 FilesDescriptionMain functions
stdio.hStandard input and outputgets(), puts(), gstchar(), scanf(), printf(), rename (), etc
conio.hConsole input output (for DOS complier)getch(), getche()
math.hMathematical calculationsin(x), log(x), pow(x,2), srt(x), cbrt(x)
Some header files

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.

KeywordUseKeywordUse
autoAutomatic variable storage durationbreakExit a loop or switch
caseLabel in a switch statementcharDeclares a character variable
constConstant valuecontinueSkip the current iteration of a loop
defaultDefault label in switchdoStart a do-while loop
doubleDeclares a double precision floating pointelseDefines the else condition in an if-else statement
enumDeclares an enumerated typeexternDeclares a variable or function that is defined elsewhere
floatDeclares a floating point variableforStart a for loop
gotoJump to a specific labelifConditional statement
inlineSuggests inlining of a functionintDeclares an integer variable
longDeclares a long integerregisterSuggests storing a variable in a CPU register
returnReturn from a functionshortDeclares a short integer
signedDeclares a signed variablesizeofReturns the size of a data type or variable
staticStatically allocated variablestructDefines a structure
switchStart a switch statementtypedefDefine a type alias
unionDefines a union typeunsignedDeclares an unsigned variable
voidSpecifies an empty return type or function argument typevolatileDeclares a variable whose value can change at any time
whileStart 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

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 TypeTypeMemory
voidnothing0
charcharacter1 byte
intInteger2 or 4 bytes
floatFloating point4 bytes
doubleDecimal large8 bytes
Basic Data type in c

Derived Data Types

TypeDescription
ArrayCollection of union of same data type
PointerStores the address of a variable
StructureCombines variables of different types into single unit
UnionSimilar 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.

ModifierData TypeSize (in bytes)Range
short intint2-32,768 to +32,767
unsigned intint2 or 40 to 65,535 (2 bytes) or 0 to 4,294,967,295 (4 bytes)
long intint4-2,147,483,648 to +2,147,483,647
unsigned long intint40 to 4,294,967,295
signed charchar1-128 to +127
unsigned charchar10 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
\0Terminate string
\nNew line in output display
\tCreate tab or 8 space in print output
Escape sequence

Format Specifier

Format Sequence Meaning /normally used by scanf() and printf() function
%d, %isigned integer with + or – sign
%uunsigned integer without + or – sign
%ffloat number
%eexponent number
%ooctal integer
%csingle character
%sstring

Uses of Format Specifier in C

ExampleOutput
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

OperatorFunction
+Add
Substract
*Multiply
/Divide
%Reminder of Division
Arithmetic Operator
OperatorFunction
==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
Relational Operator
OperatorFunction
&&AND Logic
||OR Logic
!NOT Logic
Logical Operator

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

FunctionUsesType
printf()To printFormatted Output
scanf()To assign input valueFormatted 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 characterUnformatted 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 characterUnformatted Input
putch()Put Character; Print Single CharacterUnformatted Output
getchar()To read character from keyboard Unformatted Input
putchar()To print character on monitorUnformatted Output
gets()To read single or multiple word from keyboardUnformatted Input
puts()To print single or multiple word on monitorUnformatted 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

  1. Modularity: Breaks down the program into smaller, reusable blocks.
  2. Reusability: Functions can be called multiple times in a program, reducing code repetition.
  3. Easier Debugging: Errors are easier to isolate and fix in modular code.

Types of Functions in C

  1. Library Functions: Predefined functions provided by C (e.g., printf(), scanf(), strlen()).
  2. 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;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top