Quick Reference Study Notes for C Programming (Advanced)

C Language

C developed by Dennis Ritchie between 1969 and 1973 at Bell Labs, is a general-purpose programming language used for wide range of applications from Operating systems like Windows and iOS to software that is used for creating 3D movies. Standard C programs are portable. The source code written in one system works in another operating system without any change.

 

  1. Features:

Structured language

Code can be partitioned in C using functions or code block.

General purpose language

Ideal language for system programming, business and scientific applications.

Portability

Ability to port or use the programs written in c on different platforms.

Code Reusability & Ability to customize and extend

Function can be added to 'c' library and can be used repeatedly in different application.

Limited Number of Key-Word

There are only 32 keywords in 'C' and strength of 'C' is lies in its in-built function.


 

  1. Header Files:

Header file contain C function declarations and macro definitions to be shared between several source files. These files has ‘.h’ extension. You can create your own header files with .h extension to reuse code in different files/programs. Header files are included using the preprocessing directive #include in two ways:

 

#include <file>

used for system header files.

#include "file"

used for header files of your own program.

 

Some of header files and their use:

 

Header Files

Use

<float.h>

Defines macro constants specifying the implementation-specific properties of the floating-point library.

<math.h>

Defines common mathematical functions.

<stdio.h>

Defines core input and output functions

<stdlib.h>

Defines numeric conversion functions, pseudo-random numbers generation functions, memory allocation, process control functions

<string.h>

Defines string handling functions.

 

Eg-:  #include<stdio.h>


C Program Structure:

pre-processor directives
global declarations
main()
{
    local variable declaration
    statement sequences
    function invoking
}

  1. Keywords:

Keywords are the words whose meaning has already been explained to the C compiler. There are only 32 keywords available in C. The keywords are also called ‘Reserved words’.

 

auto

double

Int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

signed

continue

for

unsigned

void

default

sizeof

goto

volatile

do

if

static

while

       


 

  1. Data types:

It is a particular kind of data item that tells which type of value it can take.

 

Keyword

Variable type

Range

char

Character/string

-128 to 127

int

Integer

-32768 to 32767

short/short int

Short Integer

-32768 to 32767

long

Long Integer

-2147483648 to 2147483647

unsigned char

Unsigned Character

0 to 255

unsigned int

Unsigned Integer

0 to 65535

unsigned short

Unsigned Short Integer

0 to 65535

unsigned long

Unsigned Long Integer

0 to 4294967295

float

Single precision floating point(accurate to 7 digits)

 

double

Double precision floating point(accurate to 15 digits)

 

 

Used as- int x=10;

This means x will contain integer value range between -32768 to 32767.

 

  1. Variables:

Variables are simply names used to refer to some location in memory.

Declaring-

 

int x;

A variable.

char x = ‘A’;

A variable & initializing it.

float a,b,c;

Multiple variables of the same type.

const int n = 18;

A constant variable: can’t assign to after declaration.

 

  1. Conversion Characters/Placeholders

Conversion Characters are the combinations of percent sign and a letter as placeholders for variables you want to display.

 

Placeholders

Display arguments as-

%c

Single character

%d

Signed decimal integer (int)

%e

Signed floating-point value in E notation

%f

Signed floating-point value (float)

%g

Signed value in %e or %f format, whichever is shorter

%i

Signed decimal integer (int)

%o

Unsigned octal (base 8) integer (int)

%s

String of text

%u

Unsigned decimal integer (int)

%x

Unsigned hexadecimal (base 16) integer (int)

%%

(percent character)print a ‘%’

 

Eg-

int a=10;

printf(“Value of a is %d”,a);

This will replace placeholder ‘%d’ with the value of variable ‘a’. Output will be- Value of a is 10.


 

  1. Control Characters(Escape Sequences)

Certain non printing characters as well as the backslash () and the apostrophe('), can be expressed in terms of escape sequence.

 

\a

Bell

\n

New Line

\r

Carriage return

\b

Backspace

\f

Formfeed

\t

Horizontal tab

\”

Quotation Mark

\v

Vertical Tab

\’

Apostrophe

\\

Backslash

\?

Question mark

\0

Null

 

  1. Operators:

For our examples X=20 and Y=10.

Expression

Operators

Description

Example

   

      Arithmetic

 

Addition

+

Adds two operands.

X + Y = 30

Subtraction

-

Subtracts second operand from the first.

X – Y = 10

Multiplication

*

Multiplies both operands.

X*Y = 200

Division

/

Divides numerator by de-numerator.

X / Y= 2

Modulus

%

Modulus Operator and remainder of after an integer division.

X % Y= 0

Increment

++

Increment operator increases the integer value by one.

X++ = 21

Decrement

--

Decrement operator decreases the integer value by one.

X-- = 19

   

      Relational

 

Equal to

==

Checks if the values of two operands are equal or not. If yes, then the condition becomes true.

(X == Y) is not true.

Not equal to

!=

Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.

(X != Y) is true.

Greater than

>

Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.

(X > Y) is true.

Less than

<

Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.

(X < Y) is not true.

Greater than or equal to

>=

Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.

(X >= Y) is true.

Less than or equal to

<=

Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.

(X <= Y) is not true.

   

       Logical

 

Logical AND

&&

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(X && Y) is true.

Logical OR

||

Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

(X || Y) is true.

Negation

!

Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

!(X && Y) is false.

   

        Bit-wise

 

Bitwise AND

&

Binary AND Operator copies a bit to the result if it exists in both operands.

 

Bitwise inclusive OR

|

Binary OR Operator copies a bit if it exists in either operand.

 

Bitwise exclusive OR

^

Binary XOR Operator copies the bit if it is set in one operand but not both.

 

One’s compliment

~

Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.

 

Left shift

<<

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

 

Right shift

>>

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

 
   

     Assignment

 

Simple assignment operator

=

Simple assignment operator. Assigns values from right side operands to left side operand

Z = X + Y will assign the value of X + Y to Z

AND assignment

+=

Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

Z += X is equivalent to Z = Z + X

Subtract AND assignment

-=

Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.

Z -= X is equivalent to Z = Z – X

Multiply AND assignment

*=

Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.

Z *= X is equivalent to Z = Z * X

Divide AND assignment

/=

Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.

Z /= X is equivalent to Z = Z/ X

Modulus AND assignment

%=

Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.

Z %= X is equivalent to Z = Z % X

Left shift AND assignment

<<=

Left shift AND assignment operator.

Z <<= 2 is same as Z = Z << 2

Right shift AND assignment

>>=

Right shift AND assignment operator.

Z >>= 2 is same as Z = Z >> 2

Right shift AND assignment

&=

Right shift AND assignment operator.

Z &= 2 is same as Z = Z & 2

Bitwise exclusive OR and assignment

^=

Bitwise exclusive OR and assignment operator.

Z ^= 2 is same as Z = Z ^ 2

Bitwise inclusive OR and assignment

|=

Bitwise inclusive OR and assignment operator.

Z |= 2 is same as Z = Z | 2

   

         Misc

 

Size in bytes

sizeof()

Returns the size of a variable.

sizeof(x), where a is integer, will return 4.

Address of

&

Returns the address of a variable.

&X; returns the actual address of the variable.

Value of address

*

Pointer to a variable.

*X;

Conditional

? :

Conditional Expression.

If Condition is true ? then value X : otherwise value Y

Type cast

(type)

Convert the variable into given data type.

(float)X, where x=4 is int, will return 4.00 as float.


 

  1. Precedence in ascending order and associativity of Expressions and Operators:

 

Unary & +, -, and * have higher precedence than the binary forms.

Operator/Expression

Associativity

()(Function Expression)

Left to Right

[](Array Expression)

Left to Right

->(Structure Operator)

Left to Right

.(Structure Operator)

Left to Right

-(Unary minus)

Right to Left

++/--(Increment/decrement)

Right to Left

~(One’s compliment)

Right to Left

!(Negation)

Right to Left

&(Address of )

Right to Left

*(Value of address)

Right to Left

(type)

Right to Left

sizeof

Right to Left

*(Multiplication)

Left to Right

/(Division)

Left to Right

%(Modulus)

Left to Right

+(Addition)

Left to Right

-(Subtraction)

Left to Right

<<(Left Shift)

Left to Right

>>(Right Shift)

Left to Right

<(Less than)

Left to Right

<=(Less than or equal to)

Left to Right

>(Greater than)

Left to Right

>=(Greater than or equal to )

Left to Right

==(Equal to)

Left to Right

!=(Not equal to)

Left to Right

&(Bitwise AND)

Left to Right

^(Bitwise exclusive OR)

Left to Right

|(Bitwise inclusive OR)

Left to Right

&&(Logical AND )

Left to Right

||(Logical OR)

Left to Right

?:(Conditional)

Right to Left

=, *=, /=, %=, +=, -=, &=, ^=, |=, <<=, >>=(Assignment operators)

Right to Left

,(Comma)

Right to Left

 

  1. Decision Making:

 

Type

Description

Syntax

If Statement

If the condition will return true, It will execute the statements else It will skip the execution of statements.

if(condition){

   Statements;

}

If-else Statement

If the condition will return true, It will execute the statements-1 and if condition will return false, it will execute the statements-2.

if(condition){

   Statements-1;

}

else{

   Statements-2;

}

Nested If-else

If we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called "nesting" of ifs.

if (condition1)
   statement;
else {
   if (condition2)
       statement;  
   else    {
       block of statement;
   }
}

If-else Ladder

The expressions are evaluated in order; if an expression is true, the "statement" or "block of statement" associated with it is executed, and this terminates the whole chain. The last else part handles the "none of the above" or default case where none of the other conditions is satisfied.

if(condition1)
   statement;
else if(condition2)
   statement;
else if(condition3)
   statement;
else if(condition4)
{
   block of statement;
}
else
   statement;

Switch Statement

The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. The switch statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the switch statement.

switch (expression)
{
   case constant-expression:
       statement1;
       statement2;
       break;
   case constant-expression:
       statement;
       break;
   ...
   default:
       statement;
}


 

  1. Loop Control Statements

 

Type

Description

Syntax

while

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

while(condition) {
   block of statement
}

do-while

It is more like a while statement, except that it tests the condition at the end of the loop body.

do{
   statements;
}while (condition);

for

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

for ( initialization; condition; increment/decrement ){
   statements;
}

 

  1. Array:

Arrays are structures that hold multiple variables of the same data type. An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.

 

Array Declaration

Array Initialization

Accessing Data

Entering data into array

An array needs to be declared so that the compiler will know what kind of an array and how large an array we want.

Initializing means filling array with data/elements.

This is how individual elements in the array can be referred. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks [5] is not the fifth element of the array, but the sixth.

for(i = 0;i <= 29;i++)
{
   printf("\nEnter marks ");
   scanf("%d", &marks[i]);
}

 

After this we will have an array with name marks with 30 values entered by user.

int marks[30] ;
Here,

int- specifies the type of the variable.

marks- specifies the name of the variable.

[30]- 30 tells how many elements of the type int will be in our array. This number is often called the "dimension" of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.

int n[3] = { 1, 6, 8 } ;


int x[] = { 33,44,55,66} ;


float p[] = { 11.23, 34.11} ;

 

While initializing we can skip giving the size of array.

int x[] = { 33,44,55,66} ;

int e = x[3];
 

e is the value of forth element in array x.

Output ->e = 66.

 

for(i = 0;i <= 3;i++)
{
   printf("%d",x[i]);
}

 

This will access all the elements using loop through whole array.

output-> 33 44 55 66

The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf() function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks[30].In scanf() function, we have used the "address of" operator (&) on the element marks[i] of the array. In so doing, we are passing the address of this particular array element to the scanf() function, rather than its value; which is what scanf() requires.


 

  1. Strings:

Strings are arrays of characters. Each member of array contains one of characters in the string.The length of a string is determined by a terminating null character: ‘\0’ . So, a string with the contents, say, “abc” has four characters: ‘a’ , ‘b’ , ‘c‘ , and the terminating null character. The terminating null character has the value zero.

Example:

#include<stdio.h>
main()
{
   char name[20];
   printf("Enter your name : ");
   scanf("%s",name);
   printf("Hello %s ,\n how are you ?\n",name);
}

 

Output:

Enter your name : Umang
Hello Umang,

how are you ?

 

Explanation:

%s- placeholder for string variables(we will not use & sign for receiving string values.)

\n- escape character for new line.

 

Some of string function are given below:

For given examples: s1=”Gauri” and s2=”Pasricha”

String Functions

Purpose

Results

strcpy(s1, s2);

Copies string s2 into string s1.

s1=”Pasricha”

s2=”Pasricha”

strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

s1=”GauriPasricha”

s2=”Pasricha”

strlen(s1);

Returns the length of string s1.

Length of s1=6(5 characters and one \0 null character)

strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

Return -1.

strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

Example:

char string[55] ="This is a string for testing";

 char *p;

 p = strchr (string,'i');

 

 printf ("Character i is found at position %d\n",p-string+1);

 printf ("First occurrence of character \"i\" in \"%s\" is" \

       " \"%s\"",string, p);

 

Output:

Character i is found at position 3

First occurrence of character “i” in “This is a string for testing” is “is is a string for testing”

strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Example:

char string[55] ="This is a test string for testing";

 char *p;

 p = strstr (string,"test");

 if(p)

 {

   printf("string found\n" );

   printf ("First occurrence of string \"test\" in \"%s\" is"\

       " \"%s\"",string, p);

 }

 else printf("string not found\n" );

 

Output:

string found

First occurrence of string “test” in “This is a test string for testing” is “test string for testing”


*NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."