0% found this document useful (0 votes)
33 views

C Programming - From

C is a general-purpose programming language developed in the 1970s. It is commonly used for embedded systems and performance-critical applications due to its speed and low-level access. The document provides an overview of basic C concepts like variables, data types, operators, control flow statements, and functions. It also demonstrates how to compile and run simple C programs that perform tasks like input/output and calculations.

Uploaded by

lynxbee dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

C Programming - From

C is a general-purpose programming language developed in the 1970s. It is commonly used for embedded systems and performance-critical applications due to its speed and low-level access. The document provides an overview of basic C concepts like variables, data types, operators, control flow statements, and functions. It also demonstrates how to compile and run simple C programs that perform tasks like input/output and calculations.

Uploaded by

lynxbee dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

C Programming

Basics of Computing World !

lynxbee.com
Modular C Programs lynxbee.com

. ├── io │ ├── README


├── arrays │ ├── console │ └── undef.c
│ ├── array_initilsation.c │ │ ├── field-width-specifiers.c ├── strings
│ ├── array_of_pointers.c │ │ ├── formatted_io.c │ ├── array_of_pointer_to_strings.c
│ ├── array_size_limit.c │ │ ├── sprintf_sscanf.c │ ├── benefit_of_null_char.c
│ ├── passing_array_elements_to_functions.c │ │ └── unformated_io.c │ ├── get_string_from_user.c
│ ├── passing_entire_array_to_function.c │ └── file │ ├── initialisation_of_string.c
│ ├── pointers_and_arrays.c │ ├── argc_argv.c │ ├── pointers_and_string.c
│ └── why_to_use_array.c │ ├── fileseek.c │ └── standard_library_functions.c
├── bitfields.c │ ├── fread.c ├── structures
├── bitwise_operators │ ├── read_file │ ├── array_of_structures.c
│ └── example.c │ ├── read_from_file.c │ ├── initilization.c
├── boolean.c │ ├── sample_text_file.txt │ ├── passing_struct_to_function.c
├── datatypes │ └── this_is_demo_session_exe │ ├── pragma.c
│ └── data_type_sizes.c ├── loops │ └── structure_pointers.c
├── enums │ └── do_while.c ├── typecasting.c
│ └── example.c ├── preprocessor ├── union.c
├── functions │ ├── ifdef_else_endif.c └── variable_argument.c
│ ├── function.c │ ├── ifdef_endif.c
│ ├── function_pointer.c │ ├── if_elif.c
│ └── function_returning_pointer.c │ ├── if_else_endif.c
├── how_compilation_works │ ├── ifndef_endif.c
│ ├── hello.c │ ├── ifndef_endif.h
│ ├── README │ ├── macro.c
│ ├── t.i │ ├── macro-with-argument.c
│ ├── t.o
│ └── t.s
What is C ? lynxbee.com

● C was developed by Dennis Ritchie in 1972 at


AT&T Bell Laboratories, USA.

● C is basic of all languages, to make


fundamentals stronger it's advised to learn C
first.

● C is base language for Embedded system.

● C is best language for performance ( speed of


execution ), produces less code size hence good
for embedded devices which have processor
power & memory size restrictions.
Very Basic C program lynxbee.com

$ vim minimum-c-program.c #include <stdio.h>

main() { main() {
} printf("Hello World\n");
}
Above is the very basic framework for Any C program.
- main, () and {} - What happens when you didn’t written
#include
$ gcc -o minimum-c-program minimum-c-program.c

$ ./minimum-c-program
Constants, Variables, Keywords lynxbee.com

Constants - Entity that do not change Variables - entity that may change

Integer constants - Names given to memory location which


1, 423, +700, -345 etc can change.

Float Constants - int age; float salary; char yes_no;


426.9, -367.3 etc

Character constants -
‘A’ , ‘n’, ‘Z’, ‘3’ etc
Maximum length => 1 Char in
single inverted
Keywords lynxbee.com

● Words whose meaning is already decided for the compilers.


● Keywords can’t be used as variable names.

auto double int struct break else long switch

case enum register typedef char extern return union

const float short unsigned continu for signed void


e

default goto sizeof volatile do if static while


First Program lynxbee.com

#include <stdio.h>

void main() {
printf(“hello world”);
}

● Header
● main
● Body

● #include is - preprocessor.

● Printf is declared in header stdio.h and defined in a library.

● Always ends with ;


Second Program lynxbee.com

#include <stdio.h>

int main(void) {
/* Printing Hello World */
printf(“hello world”);
return 0;
}

● Comments should be included in /* */


● Returns integer
● Void
Third Program lynxbee.com

#include <stdio.h>

int main(void) {
int p, n; /* declaration */
float r, si;
p = 1000; /* definition */
n = 3;
r = 8.5;

si = p*n*r/100;
printf (“Simple Interest is : %f \n”, si);
}

● Printf => printf(“<format string>” , <list of variables>);


● %f - float, %d - Int, %c - Char.
● \n -> New line
Compilation and Execution lynxbee.com

● Create a file using editor


vim simple_interest.c

● Compile using gcc ( GNU C Compiler for Linux )


gcc -o simple_interest simple_interest.c

● ./simple_interest
Receiving Inputs from User using scanf lynxbee.com

#include <stdio.h>

int main(void) {
int p,n;
float r,si;
printf(“Enter values of p, n, r”);
scanf(“%d, %d, %f”, &p, &n, &r);
si = p*n*r/100;
printf(“Simple Interest = %f\n”, si);
return 0;
}

& - Address of operator, which is actually a memory location


Operators lynxbee.com

Priority Operators Description

First * /% Multiplication, division, Modular

Second + - Addition, Subtraction

Third = Assignment
Associativity of Operators lynxbee.com

#include <stdio.h>

int main (void){

/* Associativity of operators :1) Left to Right 2) Right to Left */


/* Multiplication & Division has "Left to Right Associativity" */
/* for Division: / , left side is 3 & right side is 2*5, indicating left side is unambiguous */
/* for Multiplication: * , left side is 3/2 & right side is 5, indicating right side is unambiguous */
/* Since both * & / has same priority & "Left to Right" Associativity, In below example */
/* Division will get executed first and them multiplication */
/* Hence result will be 5 */

int a = 3/2*5;
printf("a=%d\n", a);

/*Above Statement will print result as 5 since 3/2 is equals to 1 due to integer division*/
return 0;
}
Decision Making Statements - If, If-else, Switch lynxbee.com

If Statement

Conditions - x == y, x != y, x < y, x > y, x <= y, x >= y

Simple Program

#include <stdio.h>

int main (void) {


int x = 9;
if ( x < 10 )
printf(“ you have assigned x less than 10\n”);
return 0;
}
If - else Statement lynxbee.com

#include <stdio.h>

int main() {
Int x = 11;
If (x<10)
printf(“you have set x less than 10\n”);
else
printf(“you have set x greater than 10\n”);
return 0;
}

Nested If else statements are possible


Logical Operators lynxbee.com

AND ( && ), OR ( || ) & NOT (!)

Different than bitwise operators

Simple Example
Else - If Statement lynxbee.com

If the first condition is satisfied, other conditions are not checked.


Reduces the multiple indentation required by “if-else” statements.

Simple Example -
The Not ! Operator lynxbee.com

- This operator reverses the result of the expression it operates on.


- Final result will be either true or false i.e. 1 or 0
- !(y<10) => this means “not y less than 10”. In other words, if y is less than 10, the expression will be
false, since (y<10) is true.

The Conditional Operator


? : also called as ternary operators.
Expression 1 ? expression 2 : expression 3
Loops lynxbee.com

- While
- For
- Do-while

While Loop

#include <stdio.h>

int main() {
int count = 1;
while ( count < =5 ) {
printf ( “count is %d”, count);
count = count + 1;
}
printf(“now count is more than 5, exiting program\n”);
return 0;
}
Increment and Decrement Operators lynxbee.com
The For Loop lynxbee.com

- Most used
- All steps at one statement

for ( initialize; test; increment ) {


}

Example :

#include <stdio.h>

int main() {
int count;
for ( count = 1; count < =5; count++ ) {
Printf ( “count is %d”, count);
}
printf(“now count is more than 5, exiting program\n”);
return 0;
}

lynxbee.com
Do - while loop lynxbee.com

- Used when you are not sure how many times the loop needs to be executed.
- Loop is executed atleast once.

Example -

Int main () {
Char condition;
Int num=0;
Do {
printf(“You are inside for the %d time\n”, num++);
printf(“do you want to remain in loop ( y/n ) : ”);
scanf(“%c”, &condition);
}while (condition == ‘y’)

printf(“you entered: %c, hence out of loop\n”, condition)


return 0;
}
Break & Continue lynxbee.com

break - is used to move out of loop immediately upon meeting certain condition
continue - is used to move back to loop by skipping steps beyond this.

Example : Continue Example

Int main() { Int main() {


Int i, j=5; Int i, j=5;
for(i=1;i<=10;i++) { for(i=1;i<=10;i++) {
If ( i == j) If ( i == j)
break; continue;
printf(“i=%d\n”,i); printf(“i=%d\n”,i);
} }
Return 0; Return 0;
} }
Switch Case lynxbee.com

- Used when we need to make a choice between number of things.


- Integer expression can be constants or something which evaluates to integer.
- “Case” will be followed by “int” or “char” constant.
#include <stdio.h>
#include <stdio.h> Int main() {
int main() { Int i = 2
int i = 2 Switch ( i ) {
Switch ( integer expression ) Switch ( i ) { case 1 :
{ case 1 : printf(“1”);
Case constant 1 : printf(“1”); break;
“Do this” case 2: case 2:
Case constant 2: printf(“2”); printf(“2”);
“Do this” Case 3: break;
Default : printf(“3”); Case 3:
“If no match” Default : printf(“3”);
} “in default” break;
} Default :
return 0; “in default”
} }
Return 0;
}
Goto Keyword : better avoid lynxbee.com

Int main() {
Int main() {
Int i; j=2;
Int i; j=6;
For (i=0; i<5; i++) {
For (i=0; i<5; i++) {
printf(“i is %d\n”, i);
printf(“i is %d\n”, i);
If (i==j)
If (i==j)
goto at_end;
goto at_end;
}
}
printf(“normal completion of loop\n”);
printf(“normal completion of
return 0;
loop\n”);
return 0;
at_end: printf(“reached directly at end due to i==j\n”);
Return 0;
at_end: printf(“reached directly at end
}
due to i==j\n”);
return 0;
}
Functions lynxbee.com

- Function is a block of statement which performs some task.


- Functions need three things, declaration, call and definition

#include <stdio.h>
- Start main
/* declaration */ - Control passes to
Void function_name(); function while main is
suspended
int main () { - Function is executed
/* function call */ - Control returns to main
function_name(); - Main resumes execution
printf(“inside the main \n”); - Main is completed
return 0;
}

/* function definition */
Void function_name() {
printf(“inside the function \n”);
}
Types of Functions lynxbee.com

- Library Function ex. main, printf


- User defined functions ex. myfunc()

Benefits of Functions -
- Avoid rewriting of same code
- Modular functions make program design easier for development and debugging

Passing Values to Functions - adds communication between calling & called function

Void sum(int);
Int main(void) { Type, order and number of arguments from
int i = 10; calling and called function should be same.
add(i);
return 0;
}

void add (int j) {


printf(“sum = %d”, j+5);
}
Return Type & Variable from a Function lynxbee.com

int sum(int);
int main(){
Int i=10, ret; - Only “return” with no value will return
ret = sum(i); garbage.
printf(“sum = %d\n”,sum);
Return 0; - “return” returns only one value.
}

int sum(int j) {
Int add;
Add = j+5;
Return add;
}
Scope in Functions lynxbee.com

- The scope of a variable is local to the function in which it is defined.


- Local variables defined inside a function are created in “stack” memory.

Calling Convention - C has “right to left” calling convention

#include <stdio.h>

Int main(){ This program will return as 3, 3, 1


Int i = 1;
printf(“%d, %d, %d \n”, i, ++i, i++);
Return 0;
}
Function calls - 1. Call by Value 2. Call by reference lynxbee.com

1. Call by Value
- We pass “values” of variables to the called function.

#include <stdio.h>
Int main(void) {
Int j=10; Call by reference - will need understanding of
function(j); pointers
Return 0;
}

Void function (int k) {


printf(“%d ”, k);
}
Pointers lynxbee.com

Int i = 5; * - is called “value at address” operator


This does 3 things,
- Reserve memory Int main () {
- Give a Name Int i = 5;
- Store Value in it Printf (“address = %u \n”, &i);
Printf (“value = %d \n”, i);
Int main() { Printf (“ value = %d \n”, *(&i) );
Int i = 5; Return 0;
printf(“address = %u \n”, &i); }
printf(“value = %d \n”, i);
Return 0;
}

& - is called “address of” operator


Pointers lynxbee.com

Address can also be collected in a variable.


Definition => j = &i ; declaration => int *j ;

This means, J is a variable which is used to store address of integer or value at the address contained in j
is integer.

Int main() {
Int i=5, *j;
j = &i;
printf(“Address of i = %u”, &i);
printf(“value of i = %d”, i);
printf(“value inside j =%d”, *j);
return 0;
}
Back to Function Call by Reference lynxbee.com

Int main() {
Example : swapping of two integers Int i=10, j=20;
swap( &i, &j );
Int main() { printf(“i= %d, j=%d”, i, j);
Int i=10, j=20; Return 0;
swap(i,j); }
printf(“i= %d, j=%d”, i, j);
Return 0; Void swap( int *x, int *y) {
} Int t;
T = *x;
Void swap(int x, int y) { *x = *y;
Int t; *y = t
t = x; }
X = y;
Y = t; Above program will actually exchange i &
printf(“x = %d, y=%d”, x,y); j
}
We can’t use return since it can return only one value. ● Useful to return more than one
variables to main.
Recursion lynxbee.com

Recursion : when statement in a function calls the same function


Using recursion
Example : Calculate Factorial 4! = 4*3*2*1
Int factorial( int x ) {
Int factorial (int); Int f;
Int main() { If (x == 1)
Int num, ret; Return 1;
printf(“Enter the number = ”); Else
scanf(“%d”, &num); F = x * factorial (x-1);
Ret = factorial ( num); Return f;
printf(“calculated factorial = %d”, ret ); }
Return 0;
}

Int factorial(int x) {
Int f = 1, i;
For (i=x; i>=1; i--)
F = f*i;
Return f;
}
Data Types lynxbee.com

- char, int, float


- Signed & unsigned
- long & short

char Signed, unsigned

int Signed, unsigned Long, short

float Float, double, long double


Use of sizeof lynxbee.com

#include <stdio.h> printf ("sizeof (int) = %d \n", sizeof(a));


printf ("sizeof (short int) = %d \n", sizeof(a1));
printf ("sizeof (long int) = %d \n", sizeof(a2)); $ ./a.out
int main(void) {
printf ("sizeof (signed int) = %d \n", sizeof(a3)); sizeof (char) = 1
char c;
printf ("sizeof (unsigned int) = %d \n", sizeof(a4)); sizeof (signed char) = 1
signed char c1;
printf ("sizeof (short signed int) = %d \n", sizeof(a5)); sizeof (unsigned char) = 1
unsigned char c2;
printf ("sizeof (short unsigned int) = %d \n", sizeof(a6)); sizeof (int) = 4
printf ("sizeof (long signed int) = %d \n", sizeof(a7)); sizeof (short int) = 2
int a;
printf ("sizeof (long unsigned int) = %d \n", sizeof(a8)); sizeof (long int) = 4
short int a1;
sizeof (signed int) = 4
long int a2;
printf ("sizeof (float) = %d \n", sizeof(b)); sizeof (unsigned int) = 4
signed int a3;
printf ("sizeof (double) = %d \n", sizeof(b1)); sizeof (short signed int) = 2
unsigned int a4;
printf ("sizeof (long double) = %d \n", sizeof(b2)); sizeof (short unsigned int) = 2
short signed int a5;
sizeof (long signed int) = 4
short unsigned int a6;
return 0; sizeof (long unsigned int) = 4
long signed int a7;
} sizeof (float) = 4
long unsigned int a8;
sizeof (double) = 8
sizeof (long double) = 12
float b;
double b1;
long double b2;

printf ("sizeof (char) = %d \n", sizeof(c));


printf ("sizeof (signed char) = %d \n", sizeof(c1));
printf ("sizeof (unsigned char) = %d \n", sizeof(c2));
Storage Classes in C lynxbee.com

- Where the variable would be stored


- Decides the initial value of variable when it's not specifically initialised.
- Scope of variable
- Life of variable

Storage Default Value Scope Life

Automatic Memory Garbage Local to block Till last statement in


block

Register CPU Garbage Local to Block Till last statement in


Registers block

Static Memory Zero Local to Block Persists between


different function calls

External Memory Zero Global Till Program is running


Storage Classes in C ... lynxbee.com

Automatic Storage Class Static Storage Class

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


void main() {
auto int i, j; Void counter();
printf(“i = %d, j=%d \n”, i, j);
} Int main() {
counter();
Register Storage Class counter();
counter();
#include <stdio.h> }
void main() {
register int i; void counter() {
For (i=1; i<10; i++ ) Static int i=1;
printf(“i = %d \n”, i); Printf (“counter is = %d\n”, i);
} I++;
}
Extern Storage Class lynxbee.com

Another Example :
#include <stdio.h>
#include <stdio.h>
Int i = 2;
Int x = 5;
Int main() {
I = i + 3; Void main () {
Printf ( “ i is set to %d \n”, i); Extern int y;
function(); Printf (“x = %d, y = %d \n”, x, y);
Printf (“ i is set to %d \n”, i); }
}
Int y = 7;
function() {
I = i + 10;
}
C Preprocessors lynxbee.com

- C program before compilation gets through C preprocessor


- Preprocessing is first step of building executable.
- Preprocessor begins with #
- During compilation preprocessor replaced
Macro Expansion : every occurrence of “MACRO_NAME”
with assigned value i.e. 23 in our case.
#include <stdio.h> - You need to make only one change.
- Compiler generates faster and more
#define MACRO_NAME 23 compact code for constants than
variables.
int main(void) { -
int a = 10;
a = a + MACRO_NAME;
printf("Adding a macro to a : %d\n", a);
return 0;
}
Macro with Arguments lynxbee.com

#include <stdio.h>

#define SQUARE(x) (x*x)

int main(void) {
printf("SQUARE(9) is : %d\n", SQUARE(9));
printf("SQUARE(25) is : %d\n", SQUARE(25));
return 0;
}
Why Macros, Not functions ? lynxbee.com

- Preprocessor replaces the Macro with the actual code / initialisation of macro during compilation
which generates more code size but fast in run time.
- Function call, passes the control from one the other, adding delay in execution hence slowing run
time execution but reduces the size of program.

Macros to Include File.

Two ways -
- #include “filename.h”
- #include <filename.h>

Difference only in search path.


Conditional Compilation using Macros lynxbee.com

#include <stdio.h>
“Ifdef” can be used to
// below program will not print anything if ENABLE is not defined. make programs
// way to enable this code is, just define like below, portable.
#define ENABLE

// to disable this, just comment above line

int main(void) {

#ifdef ENABLE
printf("This code is enabled upon condition as above\n");
#endif
return 0;
}
#ifdef - #else - #endif lynxbee.com

#include <stdio.h>

// below program will print second message because ENABLE


// is not defined.

int main(void) {

#ifdef ENABLE
printf("This code is enabled upon condition as above\n");
#else
printf("When disabled, you want to execute this code\n");
#endif
return 0;
}
#ifndef lynxbee.com

#ifndef - Important during header file definitions to avoid multiple inclusion.

Header - ifndef_endif.h Header - ifndef_endif.h

#ifndef __IFNDEF_ENDIF_H
#define __IFNDEF_ENDIF_H #define MYNAME "somename"

#define MYNAME "somename"


Program - ifndef_endif.c
#endif
#include <stdio.h>
Program - ifndef_endif.c #include "ifndef_endif.h"
#include "ifndef_endif.h"
#include <stdio.h>
#include "ifndef_endif.h" int main(void) {
printf("%s\n", MYNAME);
int main(void) { return 0;
printf("%s\n", MYNAME); }
return 0;
}
Example of using #if - #else #endif lynxbee.com

#include <stdio.h>

#define MACRO 4

int main(void) {
int a = 5;

// Note: here you can't compare a macro with variable


// hence #if MACRO == a
// this statement will not work.

#if MACRO == 5
printf("Macro value matches with a\n");
#else
printf("Macro value doesnt match with a\n");
#endif

return 0;
}
Example of #if - #elif - #endif lynxbee.com

#include <stdio.h>

#define MACRO 3

int main(void) {

#if MACRO == 5
printf("Macro is currently set to 5\n");
#elif MACRO == 4
printf("Macro is currently set to 4\n");
#else
printf("Macro is something else\n");
#endif

return 0;
}
#undef Example lynxbee.com

#include <stdio.h>

#define TEST

int main(void) {
printf("starting program execution inside main\n");

#ifdef TEST
printf("TEST is defined, so do something here\n");
#endif

#undef TEST

#ifdef TEST
printf("TEST is defined, so do something here\n");
#else
printf("TEST is undefined, did you do that ?\n");
#endif

return 0;
}
Arrays - set of similar data types lynxbee.com

Ordinary Variables are Age = {21, 18, 27, 31, 45};


capable of holding only one
value at a time. - In array counting of elements begins at 0

#include <stdio.h> How to declare above array ?


Int main (void) {
Int x; Int age[5];
X = 4;
X = 10;
Printf (“x=%d\n”, x);
Return 0;
}
Using Arrays lynxbee.com

- You can take values from user using scanf


#include <stdio.h> for (i=0; i<2; i++) {
printf(“%d”,&x[i]);
int main(void) { }
int x[2];
x[0] = 4; - Number inside square bracket is called
x[1] = 10; array dimension e.g. in x[2] , 2 is array
printf("x[0] = %d\n", x[0]); dimension
printf("x[1] = %d\n", x[1]); - Accessing elements from array
return 0; printf("x[0] = %d\n", x[0]);
} You can use the for loop like below,
for (i=0; i<2; i++) {
printf(“x[%d] = %d \n”, i, x[i]);
}
Initialisation of Arrays lynxbee.com

Int x[2] = {4, 10};


Int x[] = {4, 10};

- Till the array elements are not given specific values, they contains garbage.
- If array is initialized where it is declared, mentioning of array dimension is optional.
- All array elements gets stored in contiguous memory.
- There will be no error message if you are going beyond array size like below,

#include <stdio.h>
Int main() {
Int x[3], i;
For (i=0; i<10; i++) {
X [i] = i;
}
Return 0;
}
Array Boundary Checking lynxbee.com

$ ./a.out
Enter elements of array:
#include <stdio.h> 1
3
14
34
int main(void) { 23
int x [5], i; 56
99
printf("Enter elements of array: \n"); 2
7
for (i = 0; i < 10; i++) 89
scanf("%d", &x[i]); Printing output of above array :x[0] = 1
x[1] = 3
x[2] = 14
x[3] = 34
printf("Printing output of above array :"); x[4] = 23
x[5] = 56
for (i = 0; i < 10; i++) x[6] = 99
printf("x[%d] = %d \n", i, x[i]); x[7] = 2
x[8] = 7
x[9] = 89
*** stack smashing detected ***: ./a.out terminated
return 0; Aborted (core dumped)
}
Passing Array elements to function lynxbee.com

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


void function (int y); void function (int *y);
int main(void) { int main(void) {
int i, x[2] = {4, 10}; int i, x[2] = {4, 10};
for (i=0; i<2; i++) for (i=0; i<2; i++)
function(x[i]); function(&x[i]);
return 0; return 0;
} }
void function (int y) { void function (int *y) {
printf("%d\n", y); printf("%d\n", *y);
} }
Incrementing & Decrementing Pointers lynxbee.com

#include <stdio.h>

int main(void) {
int x[2] = {4, 10};
int *y;
y = &x[0];

printf("x[0]=%d, *y=%d\n", x[0], *y);

// now lets increment the pointer


printf("Incrementing pointer as y++\n");
y = y + 1; // here you can increment as many till y+(n-1) if "n" is element size
printf("*y=%d\n", *y);
// this printed 10, which means incrementing pointer reaches to next element.

printf("Decrementing pointer as y--\n");


y--;
printf("*y=%d\n", *y);

return 0;
}
Passing entire array to function lynxbee.com

#include <stdio.h>

void function (int *, int);

int main(void) {
int x[2] = {4, 10};
function(&x[0], 2);
// above call also can be made as,
// function(x, 2);
return 0;
}

void function (int *y, int j) {


int i;
for (i = 0; i < j; i++)
printf("%d\n", *(y+i));
}
Array of pointer lynxbee.com

#include <stdio.h>

int main(void) {
int x[2] = {4, 10};
int *p[] = {x, x+1};

printf("%d, %d\n", **p, **(p+1));


return 0;
}
Strings ... lynxbee.com

- String is a one dimensional array of characters terminated by null (‘\0’)


Char message = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
Each character occupies one byte and also the last character ‘\0’ hence total size of string will be
always one more than actual characters in string.
- Null character ‘\0’ is way to decide when the string ends.

#include <stdio.h>

int main(void) { Initialisation of Strings


char message[] = {'H', 'E', 'L', 'L', 'O', '\0'};
printf("string is : %s\n", message);

// Another way of initialising same string is as below,


// char message[] = "HELLO";
// note here, we dont need to mention "null" character '\0'
// and this is most standard way to initialize strings

return 0;
}
Another use of null character lynxbee.com

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

int main(void) {
char message[] = "How will you calculated the characters in this sentence ?";
int length = 0;

// so this is where null character helps us.


while (message[length] != '\0') {
length++;
}

printf("Number of characters in message = %d\n", length);

// can we get this length instead of using while, yes, using strlen library function
// but for that, we have to include string.h header
// printf("Number of characters in message = %d\n", strlen(message));

return 0;
}
Get string from Users ... lynxbee.com

printf("Now, Try to enter your name & surname\n");


#include <stdio.h>
if(fgets (name, 20, stdin) != NULL) {
// if you want to run the program to test user input /* writing content to stdout */
// using scanf, just enable below line. puts("You entered your name and surname as\n");
// #define TAKE_STRING_USING_SCANF puts(name);
}
int main(void) { #endif
char name[20];
#ifdef TAKE_STRING_USING_SCANF return 0;
printf("Enter Your Name: \n"); }
scanf("%s", name);
printf("You entered your name as: %s\n\n", name);

printf("Did you want to enter your surname along with name? Try
Again...");
scanf("%s", name);
printf("You entered your name & surname is: %s\n\n", name);

printf("Did you observed that, we couldn't print your surname which\n");


printf("was separated by space i.e. ' ' \n");
printf("So, thats the limitation of accepting string using scanf \n");
printf("You can't accept the \"Multi Word\" string.\n\n");

printf("Ok, got it.. So, whats the solution ?\n");


printf("Thats where, fgets & puts will help us..\n");

#else
Pointers and Strings lynxbee.com

#include <stdio.h>
- you can point address of one
int main(void) {
char *message = "hello"; string to another pointer
char *p;
- update the string inside pointer.
p = message;
printf("string in p : %s\n", p);

// Now we will try to update the string in p


p = "world";
printf("updated string in p : %s\n", p);
// same you can't do with static string which can be defined as

// char message[] = "hello";


// char p[10];
// p = message;
// this will give error;
// or p = "world" is not possible.

// hence we need to use pointers;

return 0;
}
lynxbee.com

#include <stdio.h> Library functions for string


#include <string.h>

int main(void) {
- Strlen, strcpy, strcat and
char source[] = "hello"; strcmp are most widely used
char destination[50]; string library functions
int length;
- Check string.h for other
length = strlen(source); supported functions.
printf("length of source string = %d\n", length);

strcpy(destination, source);
printf("destination string after copying source is now: %s\n", destination);

strcat(destination, " world!");


printf("destination string after appending another string is now: %s\n", destination);

if (!strcmp(source, "test string")) {


printf("source and \"hello\" string is same\n");
} else {
printf("source is certainly not same as \"test string\"\n");
}

return 0;
}
Array of Pointer to Strings lynxbee.com

#include <stdio.h> This program will end up with run time error,
since we are not initializing the memory
locations of the strings in the array.
int main(void) {
char *names[5];
int i;

for (i=0; i<5; i++) {


printf("Enter Name: ");
scanf("%s", names[i]);
}

return 0;
}
Solution ... lynxbee.com

Here we allocate memory in runtime for the new


int main(void) { string and save this address to the array of
char *names[5];
int i, len; pointers.
char single_name[20];
char *p;
New things -
for (i=0; i<5; i++) { - Malloc
printf("Enter Name: "); - Typedef (char *) , actually malloc returns
scanf("%s", single_name);
len = strlen(single_name);
void pointer hence we need to typedef it to
p = (char *)malloc(sizeof(char *) * len); character.
strcpy(p, single_name); - Malloc memory needs to freed by ourself
names [i] = p;
} after using.
printf("\n Entered Names are as below: \n");
for (i=0; i<5; i++) {
printf("%s\n", names[i]);
}

return 0;
}
Structures lynxbee.com

Variables are single data type, int, float, char


Arrays are collection of single data types
Structures are collection of different data types.

For example - person has “name”, “age”, “salary” etc.

Declaration -

Struct person {
Char name[10];
Int age;
Float salary;
};
lynxbee.com

#include <stdio.h> Check for


- Struct Variable declaration
int main(void) { - Struct initialization
struct person { - Structure element access
char name[20]; - we can also initialise elements using
int age; scanf and &p1.name
float salary;
}; We can also create the struct variable as,

struct person p1 = {"person_name", 20, 20000.78}; Struct person {


Char name[20];
printf("name = %s, age = %d, salary = Int age;
%f\n", p1.name, p1.age, p1.salary); Float salary;
return 0; } p1;
}
Points to Note: lynxbee.com

- Closing bracket of struct declaration must follow semicolon


- Struct declaration does not tell compiler to reserve any space in memory
- Normally structures are declared at the top of the program, even before main or mostly inside a
separate header which can be included in the program.
- If a struct variable is initialized with {0} , then all its elements will be initialized to 0.
Array of Structures lynxbee.com

struct person {
char name[20];
int age;
float salary;
};

struct person p[5];


Passing Structure to Function lynxbee.com

#include <stdio.h> - We had to move structure declaration


outside of main so that it will be
struct person {
char name[20];
available to function.
int age; - Entire structure can be passed to
float salary; function
};

void function(struct person);

int main(void) {

struct person p1 = {"person_name", 20, 20000.723};

function(p1);

return 0;
}

void function(struct person p) {

printf("name = %s, age = %d, salary = %f\n", p.name, p.age, p.salary);


// printf("name = %s, age = %d, salary = %.3f\n", p.name, p.age, p.salary);
}
Structure Pointers lynxbee.com

Note :
#include <stdio.h>

int main(void) { - Structure Pointers use ->


struct person { operator to access
char name[20];
int age;
element
float salary;
};

struct person p1 = {"person_name", 20, 20000.78};


struct person *ptr;

ptr = &p1;

printf("name = %s, age = %d, salary = %f\n", ptr->name, ptr->age, ptr->salary);

return 0;
}
#pragma lynxbee.com

#include <stdio.h>
Check how this program works with
// To enable pragma, just uncomment below line. commenting and uncommenting
// #pragma pack (1)
#pragma pack (1)
struct t {
char c;
int i;
float f;
};

int main(void) {
struct t t1;

printf("Address of character: %u\n", &t1.c);


printf("Address of int: %u\n", &t1.i);
printf("Address of float: %u\n", &t1.f);

return 0;
}
Console Input / Output lynxbee.com

- Formatted => printf, scanf


- Unformatted => getch, getche, getchar, putch, putchar, gets, puts

printf(“format string”, list of variables);

Format string contains -


- Characters that are printed as they are
- Conversion specification that begins with %
- Escape sequence that begin with \

Example -> printf(“Age : %d \n”, n );

Here, Age is printed as is, %d is conversion specification and \n is Escape sequence.

%d , %u, %ld, %lu, %x, %o - Integer conversion specifiers


%f, %lf - Float conversion specifiers
%c - character and %s - string conversion specifiers
Field Width Specifiers lynxbee.com

- Can be used for printf to properly format output or restrict the digits after decimal

#include <stdio.h>

int main(void) {
float s = 2789.742;
int age = 23;

printf("s = %10d years\n", age); //print in 10 columns with right justified like: s = 23 years
printf("s = %-10d years\n", age); //print in 10 columns with left justified like s = 23 years

// print default float


printf("s = %f\n", s);
// print only 2 digits after decimal
printf("s = %.2f\n", s);

return 0;
}
Escape Sequence lynxbee.com

\n , \t, \’ , \” => these are mostly used.


sprintf(str, "%d %c %f", 10, 'c', 23.45);
Sprintf & sscanf
printf("string: %s\n", str);

printf("reading back from string to


#include <stdio.h> struct\n");
sscanf(str, "%d %c %f", &t1.i, &t1.c, &t1.f);
struct t { printf("%d, %c, %f \n", t1.i, t1.c, t1.f);
int i;
char c; return 0;
float f; }
};

int main(void) {
char str[20];
struct t t1;
Unformatted I/O lynxbee.com

#include <stdio.h>
#include <string.h>
Scanf has a limitation of accepting strings
int main(void) {
int i = 0, j = 0; with %s.
char name[20];
char ch, temp[20];

printf("\nEnter person's name: \n");

while ((ch = getchar()) != '\n') {


temp[j] = ch;
j++;
}
temp[j] = '\0';

strcpy(name, temp);

printf("===== You Entered =====\n");


printf("Name: %s ", name);
return 0;
}
File Operations lynxbee.com

- Creating new file // verify with NULL


- Opening existing file
- Reading from a file int main(void) {
- Writing to a file FILE *fp;
- Moving to specific location in file ( seek ) char ch;
- Closing a file
fp = fopen(FILENAME, "r");
int main(void) { if (fp == NULL) {
FILE *fp; printf("file %s is not present, please
char ch; check\n", FILENAME);
return -1;
fp = fopen(FILENAME, "r"); }

while((ch = fgetc(fp)) != EOF) { while((ch = fgetc(fp)) != EOF) {


printf("%c", ch); printf("%c", ch);
} }

return 0; return 0;
} }
File opening Modes lynxbee.com

- R - read
- W - write - The function fread() reads
- A - append nmemb items of data, each
- R+ - read, write, modify size bytes long, from the
- W+ - write, read back, modify stream pointed to by
- A+ - read, append stream, storing them at the
location given by ptr.
fprintf, & fscanf => same as printf & scanf but operates on files.
- The function fwrite() writes
fread & fwrite => reads and writes in one go. nmemb items of data, each
size bytes long, to the
#include <stdio.h> stream pointed to by
stream, obtaining them from
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); the location given by ptr.

size_t fwrite(const void *ptr, size_t size, size_t nmemb,


FILE *stream);
Read from file and save to string lynxbee.com

#include <stdio.h>
#include <sys/stat.h> filelength = file_length(FILENAME);
#include <stdlib.h> printf("filelength = %d\n", filelength);
#include <string.h> buf = (char *) malloc(filelength * sizeof(char) + 1);
if (buf == NULL) {
// This program reads a text file into character buffer printf("Can't allocate memory\n");
// and then prints as string. return -1;
}
#define FILENAME "sample_text_file.txt" memset(buf, 0, filelength);

int file_length(char *f) r = fread(buf, 1, filelength, fp);


{ printf("read %d characters into buffer\n", r);
struct stat st; buf[filelength+1] = '\0';
stat(f, &st);
return st.st_size; printf("%s", buf);
} return 0;
}
int main(void) {
FILE *fp;
char *buf;
int filelength, r;

fp = fopen(FILENAME, "rb");
if (fp == NULL) {
printf("file %s is not present, please check\n", FILENAME);
return -1;
}
File Seek Operations lynxbee.com

fread(buf, 15, 1, fp);


#include <stdio.h>
buf[15] = '\0'; //terminate to make string
#include <string.h>
printf("Buffer of length: %d contained : %s\n", strlen(buf), buf);
#define FILENAME "sample_text_file.txt"
printf("Now we were at : %d, lets go to end of file\n", ftell(fp));
int main (void) {
printf("By going to end of file, will also tell us length of file\n");
FILE *fp;
int pos;
fseek(fp, 0, SEEK_END);
char buf[20];
pos = ftell(fp);
printf("We reached to end: position = filelength : %d\n", pos);
fp = fopen(FILENAME, "rw+");
if (fp == NULL) {
printf("Now lets rewind ourself to start of file\n");
printf("unable to open file: %s\n", FILENAME);
rewind(fp);
return -1;
}
pos = ftell(fp);
printf("We are now at position : %d\n", pos);
pos = ftell(fp);
printf("When file opened, pointer is at : %d\n", pos);
return 0;
}
printf("Now lets go 7 positions ahead, and print 15 characters\n");
fseek(fp, 7, SEEK_CUR); //SEEK_CUR is current pointer position

pos = ftell(fp);
printf("We are reached now at pointer position : %d\n", pos);
Argc & argv lynxbee.com

#include <stdio.h>
- Using static string for filenames etc, int main(int argc, char *argv[]) {
requires program to compile every time // suppose we decided we want to take only
// two arguments as input to the executable
- Argv, argv allows to run same program // then argc i.e. argument count will be 3
// 2 for actual arguments and one for exe name
with different inputs from command line
without compiling program if (argc != 3) {
printf("incorrect number of command line arguments\n");
return -1;
}

// now we will just print what will get copied


// into argv which is array of character strings

printf("argv[0] = %s\n", argv[0]);


printf("argv[1] = %s\n", argv[1]);
printf("argv[2] = %s\n", argv[2]);

// so if we compile this program and run, then it will print as.

// $ ./a.out file1 file2


// argv[0] = ./a.out
// argv[1] = file1
// argv[2] = file2

// Now its upto you to decide how we want to use this arguments.
return 0;
}
Bitwise Operators lynxbee.com

~ One’s Complement ~12

>> Right Shift 12 >> 3

<< Left Shift 12 << 4

& Bitwise AND 12 & 123

| Bitwise OR 12 | 123

^ Bitwise XOR 12 ^ 123


Example of Bitwise Operators lynxbee.com

printf("%d results to bits as: => ", y);


printbits(y);

#include <stdio.h> printf("One's complement of %d is : %d => ",x, ~x);


printbits(~x);
void printbits(int z) {
int size = 8 *sizeof(int); printf("bitwise AND : %d & % d is %d => ", x, y, x&y);
int j; printbits(x&y);

for (j = (size - 1); j >=0; j--) { printf("bitwise OR : %d | % d is %d => ", x, y, x|y);


(0x1 << j) & z ? printf("1") : printf("0"); printbits(x|y);
}
printf("\n"); printf("bitwise XOR : %d ^ % d is %d => ", x, y, x^y);
} printbits(x^y);

int main(int argc, char **argv) { printf("Right shift %d by %d results : %d => ", x, 4, x>>4);
int x = 12; printbits(x>>4);
int y = 123;
printf("Left shift %d by %d results : %d => ", x, 4, x<<4);
printf("%d results to bits as: => ", x); printbits(x<<4);
printbits(x);
return 0;
}
Enums lynxbee.com

Enums gives a opportunity to define our


own data type. Scope of enums can be global if
- Makes program more readable declared outside main or local if
declared inside function. This is major
- Good for multi-developer scenario difference between macro and enum.

- Internally compilers treat the enums Enum engineering {


as integers starting with 0 as first Entc,
element. Computer,
IT,
- We can also initialize first element Mechanical
something other than 0, then all next };
elements will be 1 more than previous
Enum engineering trade;
- We can also initialize all elements
with different integer values.
Enum Example lynxbee.com

include <stdio.h>
// here just for simulation, we will take input in
enum engineering {
integer from user
entc,
printf("Enter your trade in number as seen: ");
computer,
scanf("%d", &mytrade);
it,
mechanical
trade = mytrade;
};
if (mytrade == entc)
int main (int argc, char **argv) {
printf("You are Electronics & Telecomm Engineer\n");
enum engineering trade;
else if (mytrade == computer)
int mytrade;
printf("You are Computer Engineer\n");
else if (mytrade == it)
printf("Enum initialized values to : entc = %d,
printf("You are Information and Technology
computer = %d, it = %d, \
Engineer\n");
mechanical = %d \n", entc, computer, it, mechanical);
else if (mytrade == mechanical)
printf("You are Mechanical Engineer\n");
// Note: this can also be done using switch

return 0;
}
Visit
lynxbee.com

You might also like