C Notes - Odt

You might also like

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 22

C is general purpose programming language, originally developed by dennis ritche in 1972 at bell

labs to develop unix operating system.

Compilers are used by C.

C featers:
c is eazy to learn, structured language, it can be run on different computer platform, human
understandable language, to low level language etc

C applications:
c is used to write software, text editors, database, language interpreter, operating system, assemblers
etc

C programs consists of concepts:


preprocessor comments
functions
variables
statements and expressions
comments

Tokens in c:
a c programs contain several tokens like keywords, identifiers, string literals, constants etc.

Semicol in c:
a semicol is a statment terminators in c program.
‘;’

Comments in c:
a comment line help to expresss some comment and which is ignored by compilers.
/* */

identifiers in c:
an identifiers are variables in c and can be named with _, alphabet a to z, digits (0 to 9).

Keywords in c:
auto, static, register, else, union, if, do, switch, goto, while, const, for, long, double, int, float,
unsigned, signed, char, string, static, extern, sizeof, case, switch, break,

Datatypes in c:
1 Basic datatypes: They are airthmetic datatypes. ex: integer, float etc.
2 Enumerated datatypes: they are again airthmetic types and they are used to define certain
airthmetic variables that can only assign certain discreate integer values through the program.
3 Type Void: they indicates that no value is available.
4 Derived Type: They include Array, Pointer, Structure, Union, Function type.

Airthmetic Data type:


char-->1 byte--> -128 to 127 or 0 to 255
int --> 2 or 4 bytes --> -32,768 to 32,767
signed char --> 1 bytes --> -128 to +127
unsigned char --> 1 bytes --> 0 to 255
unsigned int --> 2 or 4 bytes --> 0 to 65,535
short --> 2 bytes --> -32,768 to 32,767
unsigned short --> 2 bytes --> 0 to 65,535
long --> 8 bytes(4 bytes for 32 bit os)
unsigned long --> 8 bytes

Float data type:


float-->4 bytes--> -1.2E-38 to 3.4E+38
double --> 8 bytes--> 2.3E-308 to 1.7E+308
long double --> 10 bytes--> 3.4E-4932 to 1.1E+4932

Void data type:


Void data type return no value.
Pointer to void (void * ) returns the address of the variables not the data type.

Variables in C:
char, int, float, string, void etc

extern keyword : is used to declare variable globally that can be called from another program or
within the program.

Storage classes in c:
auto
static
register
extern

auto storage class: these are the variables that are declared inside the function or with in the
function.
Ex:
int sum(int j1, int j2)
{
s=j1+j2;
return s;
}
int main()
{
int j=1, k=2;
printf(“Sum of two number is :%d\n”, sum(j, k));
}

Extern storage class:


the extern keyword used to tell the compiler that these variable are declared somewhere else in the
program. Or these variables are global variable that can be called from other program.

Ex:
#include<stdio.h>
extern int x;
void main()
{
int x=10;
Static storage class:
variable declared as static once initialized, and it will be reamin till the end of the program. If the
variable declared as static, the variable will remain in existance till the end of the program even
after the function ends. If the variable declared outside all the functions, it cannot be called outside
the program.
Ex:
#include<stdio.h>
int fun1()
{
static int a=10;
a--;
return a;
}
void main()
{
int b;
for(int j=0;j<5;j++)
{
b=fun1();
printf(“value of b is :%d\n”, b);
}
}

register storage class:


it tells the compiler that the variable stored in register instead of ram. So we can access very faster
than normal register.
Ex:
#include<stdio.h>
int main()
{
register int n=20;
int *ptr;
ptr=&n;
printf(“address of n: %u\n”, ptr);
return 0;
}

Lvalue and Rvalue:


Lvalue is the expression that reffers to memory location are called Lvalue.
Rvalue is the data value stored in some memory location.

Character Literals:
Are stored in single quotes. Ex: ‘A’

String Literals:
Are stored in double quotes. Ex: “AB”

defining Constants:
#define is a preposser for define some variable
const key word
ex:
#include<stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE ‘\n’

int main()
{
int area;
area=LENGTH*WIDTH;
printf(“area is :%d\n”, area);
printf(“%c”, NEWLINE);
}

Operators in c:
Airthmetic, Relational, logical, Bitwise, Assignment, Misc

Airthmetic Operator:
+, -, /, %, --, ++, *

Relational Operator:
==, !=, <, >, >=, <=

Logical Operator:
And(&&), OR(||), NOT(!)

Bit Wise Operator:


&, |, !, ^
ex: assume A=60, b=13 in binary format is
A=0011 1100, B=00001101

A&B=00001101
A|B=00111101
A^B=00110001
~A=11000011

Binary Left Shift and Binary Right Shift:


<< ---> binary left operands moved by number of times the right specified.
>> ---> Binary right operands moved by number of times specified by right operand.

Left shift and right shift operators cannot be defined fot negative number.

Ex: x<<y is equivalent to multiplying x by 2^y


x>>y is equivalent to division of x by 2^y

Misc Operators:
sizeof, &, *, :?
:?-->if condition is true the result will be x otherwise y.

Sizeof:
#include<stdio.h>
void main()
{
int a=10;
printf(“value of a is :%d\n”, a);
printf(“sizeof a is :%lu\n”, sizeof(a));
}

Ternary Operator:
:?
Ex:
#include<stdio.h>
void main()
{
int a=10, b=20, c;
c=(a>b)?a:b;
printf(“big value is:%d\n”, c);
}

Decision Making:
if, nested if, if else, switch statement, nested switch statement

switch statement: switch statemnet is used to compare perticular data with every other data through
case by case.

#include<stdio.h>
#include<math.h>
void main()
{
char abc=’B’;

switch(abc){
case ‘A’:
printf(“Excellent\n”);
break;
case ‘B’:
printf(“Welldone\n”);
break;
case ‘C’:
printf(“Good\n”);
break;
case ‘D’:
printf(“betterluck next time\n”);
break;
default:
printf(“invalid input\n”);
}
printf(“entered input is:%c\n”, abc);
}

Nested Switch statement:


#include<stdio.h>
#include<math.h>
void main()
{
int a=100, b=200;
switch(a){
case ‘100’:
printf(“value is :%d\n”, a);
break;
switch(b){
case ‘200’:
printf(“value is :%d\n”, b);
break;
}
}
printf(“exact value of a is:%d\n”, a);
printf(“exact value of b is:%d\n”, b);
}

Loops in C:
for, while, do while, nested for

while:
#include<stdio.h>
void main()
{
int a=10;
while(a>1)
{
printf(“value of a is:%d\n”, a);
}
}

Do-while loop:
the condition will execute at the end of the program, but the loop will executes once wheather the
condition true or false.
#include<stdio.h>
void main()
{
int a=10;
do{
printf(“value of a is:%d\n”, a);
a--;
}while(a>1);
}

For loops:
#include<stdio.h>
void main()
{
int a=10;
for(int j=0; j>10;j++)
{
printf(“value of a is:%d\n”, a);
}
}

Nested Loops:
for{
for{
Expressions;
}
}

while{
while{
expressions;
}}

do{
do{
expressions;
}while(conditions);
}while(conditions);

Loop Control Statements:


Break statement, Continue statement, Goto statement

Continue statement: it is same like break statement, instead of terminating the loop, it forces the
next iteration to takeplace.

#include<stdio.h>
void main()
{
int a=10;
do
{
if(a==15)
{
a=a+1;
continue;
}
printf(“value of a is:%d\n”, a);
}while(a>20);
}

output:
10
11
12
13
14
16
17
18
19

Goto Statement:
it is like unconditional jump statements in c.

#include<stdio.h>
void main()
{
int a=10;
LOOP1:
printf(“am prajwal\n”);
do
{
if(a==15)
{
goto LOOP1;
a=a+1;
}
printf(“value of a is :%d\n”, a);
}while(a<20);
}

Function in C:
it contains return type, function declaration, parameters, function body etc.
EX:
#include<stdio.h>
int big(int a, int b);
void main()
{
int a=10, b=20, c;
c=big(a, b);
printf(“big value is :%d\n”, c);
}
int big(int a, int b)
{
int res;
if(a>b)
{
res=a;
}
else
{
res=b;
}
return res;
}

output: 20.

Data passing to functions:


it has two methods
1.call by value
2.call by reference.

Call By Value: here only data will be passed to the formal parameters, it will affect to the original
data of the actual arguments.

Call By Refrence:
here address of the actual arguments to the formal parameters.

#include<stdio.h>
void swap(int *a, int *b);

void main()
{
int a=10, b=20;
printf(“value of a and b before swaping is :%d and %d \n”, a, b);
swap(&a, &b);
printf(“value of a and b after swapping is:%d and %d\n”, a, b);
}
void swap(int *a, int *b)
{
int res;
res=*a;
* a=* b;
* b=res;
}

Array in C:
array are used to store similar data type.
Ex:
#include<stdio.h>
void main()
{
int a[10];
printf(“enterd the value for array:\n”);
scanf(“%d”, &a[i]);
printf(“entred values are :%d\n”, a);
}

Arrays passing to function:


Type Function Name(array, array_size)
EX:
#include<stdio.h>
double getAverage(int arr[], int size);
void main()
{
int balance[5]={1000, 100, 55, 13, 7};
double avg;
avg=getAverage(balance, 5);
printf(“average value of array is:%d\n”, avg);
}
double getAverage(int arr[], int size)
{
double res;
int sum=0;
for(int i=0;i<size;i++)
{
sum=sum+arr[i];
}
res=sum/size;
return res;
}

Return array from function(not studied)

Pointer to Array in C:
#include<stdio.h>
void main()
{
int arr[5]={1,2,3,4,5};
int *ptr=arr; -------------------------> here no need to ‘&’ symbol because it is array
for(int j=0; j<5;j++)
{
printf(“%d\n”, *ptr);
*ptr++;
}
}

output:
1,2,3,4,5

POINTERS IN C :

Study the ponier in c


https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/pointer-array-array-pointer/
POINTERS are very import in c, and it can be used in memory allocation programs in c.

Pointer ia variable, whose value is address of another variable.

Declaring of pointer
ex: int *p;
float *x;
char *z;

#include<stdio.h>
void main()
{
int a=10, b=20;
int *p, *c;
p=&a;
c=&b;
printf(“value stored inside poniter variable p is:%d\n”, *p);
printf(“value stored inside poniter variable c is:%d\n”, *c);
printf(“value of pointer that is address is :%u\n”, p);
printf(“value of pointer that is address is :%u\n”, c);

NULL Pointer:
it is always good practice to fill the pointer with NULL value.

#include<stdio.h>
void main()
{
int *p=NULL;
printf(“value stored in pointer is:%d\n”, p);
}

Airthmetic Pointer:
decerement pointer
#include<stdio.h>
void main()
{
int arr[5]={1,2,3,4,5}
int *p=NULL;
p=&arr[4]; -------> here we are using address operand because we are using 4 inside bracket
for(int j=0; j<5;j++)
{
printf(“values of array are:%d\n”, *p);
* p=* p+1;
}
}

Pointer to array (please study in website)

Pointer to Pointer:
pointer to pointer stores the address of pointer variable.

#include<stdio.h>
void main()
{
int var;
int *ptr=NULL;
int **pptr=NULL;
var=3000;
ptr=&var;
pptr=&ptr;
printf(“value of var is:%d\n”, var);
printf(“value of ptr is :%d\n”, *ptr);
printf(“Value of pptr is :%d\n”, *pptr);
}
output:
3000
3000
3000

pointer used in character array:


#include<stdio.h>
void main()
{
char *greeting[10]={‘P’,’R’,’A’,’J’,’W’,’A’,’L’,’\0’};
char *ptr;
ptr=greeting;
for(int j=0; j< 10;j++)
{
printf(“%c\n”, ptr[j]);
}
}

Strings in C:
format specifier is “%s”
strcpy(s1, s2), strcat(s1, s2), strlen(s1), strcmp(s1, s2), strchr(s1, ch), strstr(s1, s2)

strcpy(s1, s2)-----> copy string s2 into string s1


strcat(s1, s2)----> string concat s2 at the end of the s1
strlen(s)-----> string length of s
strcmp(s1, s2)-----> comparing os string s1 and s2. Return 0 if s1 and s2 are same.
Return -1 if s1 less than s2. Return 1 if s1 is more than s2.
strchr(s1, ch)------> returns pointer to the first occurence of character of string s1
strstr(s1, s2)-----> return a pointer to the first occurence of string s2 in string s1.

Struct in C:
it is user defined data types which will stores different data types.
We can access any data using ‘.’ operator.

Format:
Struct (keyword) struct_name
{
variables declaration;
variables declaration;
};

in program:
Struct Struct_name object;

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}
structure used in functions:
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printBook( Book1 );

/* Print Book2 info */


printBook( Book2 );
return 0;
}

void printBook( struct Books book ) {

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}

structure used in pointers:


Live Demo
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

/* function declaration */
void printBook( struct Books *book );
int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );

/* print Book2 info by passing address of Book2 */


printBook( &Book2 );

return 0;
}

void printBook( struct Books *book ) {

printf( "Book title : %s\n", book->title);


printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}

Union in C:
union is a special data type available in c, that allows multiple data types to store in a single
memory location.
We can access different data type by using dot operator ‘.’

Typedef in C:
the c programmin language provides a keyword called typedef, which u can use to give a type for
new name.

Typdef unsigned char BYTE;

#include<stdio.h>
#include<string.h>
typedef struct Books
{
char name[100];
char subject[100];
char author[100];
int subject_id[10];
}book;
void main()
{
book b1;
strcpy(b1.name, “c programming”);
strcpy(b1.subject, “C programming tutorial”);
strcpy(b1.author, “Nuha Ali”);
b1.subject_id=123;
printf(“name is %s\n”, b1.name);
printf(“subject is %s\n”, b1.subject);
printf(“author is %s\n”, b1.author);
printf(“subject_id is %d\n”, b1.subject_id);
}

typedef is used by compiler. Typedef is limited to giving symbolic names to types only where as
#define is used to define alias for values as well.
Typdef interpretation is permformed by compiler, where as #define statements are processed by pre-
processor.
#define is used for preposser.

INPUT and OUTPUT IN C:


getchar, putchar,
gets, puts,
printf, scanf

#include<stdio.h>
#include<string.h>
void main()
{
char c[];
printf(“enter the value:\n”);
c=getch();
putch(c);
}

#include<stdio.h>
#include<string.h>
void main()
{
char c[];
printf(“enter the string:\n”);
gets(c);
puts(c);
}

FILE I/O IN C:
fopen---> to open a new file or existing file.
Format is
FILE *fopen(const char * filename, const char * mode)
file name-----> name of your file
mode-----> is the access mode

r---> opens a file for reading


w---->opens a text file for writing. If it does not exist, then a new file is created. Here your program
will start writing at the beginning of the file.

a--->here opens a file for writing in appending mode. If it does not exist, it will create new file.
r+---> both read and write operation will performed.
w+-----> opens a file for both reading and writing. It first truncates the file into zero length if it
does not exist.
a+----> opens a file for reading and writing. If it does not exist it will create.

FCLOSE A FILE:
int fclose(FILE * fp)
fclose------> return 0 if it success in closing the file or EOF there is an error while closing the file.

WRITING A FILE:
int fputc(int c, FILE * fp)
fputc function will put the character vaue stored by c to the output stream referenced by fp.
It returns the written charater if it is success or EOF if it failed.

Int fputs(const char *s, FILE *fp)


fputs writes the string to the output stream referenced by Fp

Memory Management in C:

malloc: it is used to allocates single large block of memory with specified size. It returns a void
type of pointer and it can be cast into various types. It initializes memory with a default garbage
value.
P
format:
ptr=(cast type *)malloc(byte-size)

#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr;
ptr=(int *)malloc(5*sizeof(int));
if(ptr==NULL)
{
printf(“memory not allocated :\n”);
}
else
{
printf(“enter the array values:\n”);
for(int i=0;i<5;i++)
{
scanf(“%d”, (ptr+i)); }
}
}
printf(“array values are:”);
for(int j=0;j<5;j++)
{
printf(“%d\n”, *(ptr+j));
}
}

Calloc memory allocation:


Calloc is used to dynamically allocate a specified number of blocks of memory(not single block)
of specified size.it initializes memory with default 0 values.

ptr=(cast type *)calloc(n, element-size);

#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i;
  
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
  
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
  
    // Check if the memory has been successfully
    // allocated by calloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
  
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
  
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
  
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
  
    return 0;
}

C free method in C:
it is used to deallocate the memory allocated by malloc and calloc.because dynamically allocated
memory will not release automatically. So we need to release it by manually.
By using the keyword Free.
It helps to reduce the wastage of memory.

#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // This pointer will hold the
    // base address of the block created
    int *ptr, *ptr1;
    int n, i;
  
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
  
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
  
    // Dynamically allocate memory using calloc()
    ptr1 = (int*)calloc(n, sizeof(int));
  
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL || ptr1 == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
  
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
  
        // Free the memory
        free(ptr);
        printf("Malloc Memory successfully freed.\n");
  
        // Memory has been successfully allocated
        printf("\nMemory successfully allocated using calloc.\n");
  
        // Free the memory
        free(ptr1);
        printf("Calloc Memory successfully freed.\n");
    }
  
    return 0;
}

Realloc function in C:
is used to change the previously allocated memory with new size. If the memory prvioulsy
dynamically allocated with the help of malloc or calloc is insufficient, realloc is used to
dynamically reallocate memory. Realloc function maintains the already presented value and the new
block will be allocated with the default garbage value.

ptr=realloc(ptr, new size);

#include <stdio.h>
#include <stdlib.h>
  
int main()
{
  
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i;
  
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
  
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
  
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
  
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
  
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
  
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
  
        // Get the new size for the array
        n = 10;
        printf("\n\nEnter the new size of the array: %d\n", n);
  
        // Dynamically re-allocate memory using realloc()
        ptr = realloc(ptr, n * sizeof(int));
  
        // Memory has been successfully allocated
        printf("Memory successfully re-allocated using realloc.\n");
  
        // Get the new elements of the array
        for (i = 5; i < n; ++i) {
            ptr[i] = i + 1;
        }
  
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
  
        free(ptr);
    }
  
    return 0;
}

You might also like