C Programming - From
C Programming - From
lynxbee.com
Modular C Programs lynxbee.com
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
Character constants -
‘A’ , ‘n’, ‘Z’, ‘3’ etc
Maximum length => 1 Char in
single inverted
Keywords lynxbee.com
#include <stdio.h>
void main() {
printf(“hello world”);
}
● Header
● main
● Body
● #include is - preprocessor.
#include <stdio.h>
int main(void) {
/* Printing Hello World */
printf(“hello world”);
return 0;
}
#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);
}
● ./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;
}
Third = Assignment
Associativity of Operators lynxbee.com
#include <stdio.h>
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
Simple Program
#include <stdio.h>
#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;
}
Simple Example
Else - If Statement lynxbee.com
Simple Example -
The Not ! Operator 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
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’)
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.
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
#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
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;
}
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
#include <stdio.h>
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;
}
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
Int factorial(int x) {
Int f = 1, i;
For (i=x; i>=1; i--)
F = f*i;
Return f;
}
Data Types 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
#include <stdio.h>
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.
Two ways -
- #include “filename.h”
- #include <filename.h>
#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
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>
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 __IFNDEF_ENDIF_H
#define __IFNDEF_ENDIF_H #define MYNAME "somename"
#include <stdio.h>
#define MACRO 4
int main(void) {
int a = 5;
#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
- 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>
int main(void) {
int x[2] = {4, 10};
int *y;
y = &x[0];
return 0;
}
Passing entire array to function lynxbee.com
#include <stdio.h>
int main(void) {
int x[2] = {4, 10};
function(&x[0], 2);
// above call also can be made as,
// function(x, 2);
return 0;
}
#include <stdio.h>
int main(void) {
int x[2] = {4, 10};
int *p[] = {x, x+1};
#include <stdio.h>
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;
// 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("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);
#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);
return 0;
}
lynxbee.com
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);
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;
return 0;
}
Solution ... lynxbee.com
return 0;
}
Structures lynxbee.com
Declaration -
Struct person {
Char name[10];
Int age;
Float salary;
};
lynxbee.com
struct person {
char name[20];
int age;
float salary;
};
int main(void) {
function(p1);
return 0;
}
Note :
#include <stdio.h>
ptr = &p1;
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;
return 0;
}
Console Input / Output 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
return 0;
}
Escape Sequence lynxbee.com
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];
strcpy(name, temp);
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.
#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);
fp = fopen(FILENAME, "rb");
if (fp == NULL) {
printf("file %s is not present, please check\n", FILENAME);
return -1;
}
File Seek Operations lynxbee.com
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 its upto you to decide how we want to use this arguments.
return 0;
}
Bitwise Operators lynxbee.com
| Bitwise OR 12 | 123
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
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