introduction to c programming language by mr. s. ahmed
DESCRIPTION
Introduction to C Programming Language by Mr. S. Ahmed. JustETC Education Inc. Topics/Concepts. Structure of C Program Data Types, Operators, and Expressions Control Flow Functions and Program Structure Pointers and Arrays Structures Input and Output. Structure of a C Program. - PowerPoint PPT PresentationTRANSCRIPT
Introduction to C
Programming Languageby
Mr. S. Ahmed
JustETC Education Inc.
Structure of C Program Data Types, Operators, and Expressions Control Flow Functions and Program Structure Pointers and Arrays Structures Input and Output
Topics/Concepts
How does a C program look like?
#include <stdio.h>
main(){
printf("hello, world\n");
}
Structure of a C Program
What it does?◦ Displays/prints/echos ‘hello World’
What do the different sections indicate?◦ Header Files◦ Code Blocks, functions◦ Statements
How to compile◦ Depends on the Operating System and IDE you
use How to Run?
◦ Depends on the Operating System and IDE you use
The ‘Hello World’ Program
Program StructureProgram Structure
How to compile◦ Depends on the Operating System and IDE you use◦ Save the file as hello.c◦ Linux/Unix: cc hello.c
How to Run?◦ Depends on the Operating System and IDE you use◦ Linux/Unix: a.out
Windows:◦ Usually you will use an IDE◦ IDE will have menu options to compile and run◦ Commons are: f9, shift+f9, f5 are used to compile/run. ◦ Menus may have options such as compile, build, run,
debug, build all, auto build
Program Execution, Program in Action
A program is nothing but a set of instructions to the computer hardware to perform some operations. ◦ Each line of instructions is called a statement◦ A semicolon is placed at the end of each statement◦ You can group a set of instructions by placing them in between { }◦ You can assign a name to a code block inside { } – then the code block is called
function/procedure/method◦ You can define your own functions (code blocks)◦ C also have many functions/code blocks already defined◦ Hence, a program will consist some blocks of instructions defined by you, or will
use instruction block as defined by C itself◦ Remember, one function can call /use another function
As a statement◦ While calling another function, some information can be passed to the other
function – called Arguments
Remember
printf(“%s\t%s”, “Hello”, “World”); printf(“%d\t%f”, 100, 200.50);
Some Variations of the Printf() Function
Variables: ◦ Example: x, y, z◦ x=10, y=100.5◦ printf(“%d\t%f”,x,y);◦ word=“Hello World”;◦ printf(“%s”,word);
More correctly◦ int x = 10, float y=100.5;◦ char x[50] = “Hello World”;◦ int intArr[5] = {1,2,3,4,5};
Concepts to Understand
Note:◦ \t, \b, \n◦ \t: print a tab◦ \n: print a newline
Concepts to Understand
Understanding by Examples◦ int x=10, y=20, sum=0;◦ sum = x + y; sum = (x + y); (you can think (x+y) as an
expression)◦ (x>y) is an expression◦ ((x+y) > 20) is an expression
An expression is a statement that has a value. In C, C++ and C#, an expression is always inside brackets like these examples. [about.com] ◦ ( y > 4) ◦ ( x== 8)◦ ( c = 1)
Variable and Expressions
Write a program that will print 1 if today is holiday else it will print 0.◦ If today is holiday printf(“%d”,1);◦ else if today is not holiday printf(“0”);
Controlling what the program will do◦ Control the flow of the instruction block
Which instruction will do something Which instruction will sit idle Decide if the same statements will run 100 times or not
Control Flow. What is it?
if (expression)statement1
elsestatement2
----if (expression)
statement1else if (expression)
statement2else
statement3
Control Flow
if (a > b)z = a;elsez = b;
----if (a > b)z = a;else if (b>a)z = b;
else if (a==b)x=y;
else printf(“nothing”);
If then Else
Switch-case can be used instead of if then else sometimes (not always).◦ If (1==a)
statement1◦ else if (2==a)
Statement2◦ else if (3==a)
Statement3◦ else
statement4
Switch-Case
switch(a){◦ Case 1:statement1;break;◦ Case 2:statement2;break;◦ Case 3:statement3;break;◦ default:statement4;break;
} Fall through: break is required to stop the flow
otherwise it will keep running until it sees a break.
Default: When no match is found.
Switch-Case Equivalent of If
switch (expression) {case const-expr: statementscase const-expr: statementsdefault: statements
}
Switch
Execute a set of instructions over and over◦ For specific number of times◦ As long as an expression is true/satisfied
For Loop◦ Specific number of times
While, and Do-While◦ As long as an expression is true/satisfied
Loop
while (expression){Statement
}
for (expr1; expr2; expr3){Statement
}
expr1;while (expr2) {
statementexpr3;
}
Loops Syntax
For◦ int n=100,i=0;◦ for (i = 0; i < n; i++){
printf(”%d\n”,i);◦ }
While◦ int n=100,i=0;◦ while(i <n){
printf(”%d\n”,i); i++;
◦ }
Loops Example
Do-While◦ int n=100,i=0;◦ do {
printf(”%d\n”,i); i++;
◦ } while(i <n);
Loop Example
Break◦ Get out of the current loop
Continue◦ Stop executing current iteration and go to next
iteration
Break and Continue
Syntax◦ Go to Label
…… ………
◦ Label: …….
Operation◦ Jump to the labeled place from current place◦ Not encouraged◦ Rarely can be used to get out of deeply nested
loops.
Go to Statement
What are Pointers?◦ Note: pointers usually lead to more compact and
efficient code◦ A pointer is a variable that contains the address of
another variable◦ If p is a pointer and c is a variable the statement◦ p = &c;◦ assigns the address of c to the variable p. & gives
the address of a variable
Pointers
The & operator only applies to objects in memory: variables and array elements.
Pointers cannot be applied to expressions, constants, or register variables
when * is applied to a pointer, it accesses the object the pointer points to
Pointers
Examples◦ int x = 1, y = 2, z[10];◦ int *ip; /* ip is a pointer to int */◦ ip = &x; /* ip now points to x */◦ y = *ip; /* y is now 1 */◦ *ip = 0; /* x is now 0 */◦ ip = &z[0]; /* ip now points to z[0] */
Pointers
Every pointer points to a specific data type◦ one exception:
a ``pointer to void'‘ (void *p) is used to hold any type of pointer
You cannot use dereference with void * If p points to the integer x, then *ip can
occur in any context where x could◦ *ip = *ip + 10;◦ y = *ip + 1◦ ++*ip◦ (*ip)++
Pointers
Call by reference applies herevoid swap(int *px, int *py) /* interchange *px and *py */{
int temp;temp = *px;*px = *py;*py = temp;
}
main(){swap(x, y); //The values of x and y will also get changed here}
Pointers as Function Parameters
Any operation that can be achieved by array subscripting can also be done with pointers◦ int a[10]; int *pa; pa = &a[0];◦ x = *pa; is equivalent to x=a[0];◦ pa+1 points to the next element pointed by pa◦ pa+i points i elements after pa◦ and pa-i points i elements before ◦ Thus, if pa points to a[0]
*(pa+1) refers to the contents of a[1], pa+i is the address of a[i], and *(pa+i) is the contents of a[i]
Pointers and Arrays
Example:◦ int a[10][20];◦ int *a[10];
◦ char name[][50] = { "Illegal month", "Jan", "Feb", "Mar" };
◦ char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };
Pointers and Multi-dimensional Arrays
Applies only to char, short, int, and long whether signed or unsigned◦ & bitwise AND◦ | bitwise inclusive OR◦ ^ bitwise exclusive OR◦ << left shift◦ >> right shift◦ ~ one's complement (unary) (alternate bits)
Bitwise Operators
Bitwise Operators◦ & can be used to turn off some bits◦ x= x & 031, turn off (0) all bits except last five◦ | is used to turn bits on (1)◦ ^ sets
a one in each bit position where its operands have different bits, and
zero where they are the same.◦ << and >> perform left and right shifts of their
left operand x >> 2; y << 2;
Bitwise Operators
x << 2◦ shifts the value of x by two positions◦ fills vacated rightmost bits with zero◦ One left shift multiplies the number by 2
Right shifting (Signed Number): The vacated left most bits ◦ will be filled with bit signs on some machines – arithmetic
shift◦ and with 0-bits on others - logical shift
Left and Right Shifts
int getchar(void) int putchar(int) int printf(char *format, arg1, arg2, ...); printf("%.*s", max, s); int scanf(char *format, ...) : Read from user/console int sscanf(char *string, char *format, arg1, arg2, ...): from
string
I/O Functions
FILE *fp; FILE *fopen(char *name, char *mode); int fclose(FILE *fp) char *fgets(char *line, int maxline, FILE *fp) int fputs(char *line, FILE *fp)
File Operations
String related functions as defined in string.h◦ strcat(s,t) concatenate t to end of s◦ strncat(s,t,n) concatenate n characters of t to end of s◦ strcmp(s,t) return negative, zero, or positive for s < t, s == t, s > t◦ strncmp(s,t,n) same as strcmp but only in first n characters◦ strcpy(s,t) copy t to s◦ strncpy(s,t,n) copy at most n characters of t to s◦ strlen(s) return length of s◦ strchr(s,c) return pointer to first c in s, or NULL if not present◦ strrchr(s,c) return pointer to last c in s, or NULL if not present
Common I/O Functions
What is a structure?◦ It is just a data type/variable that has multiple variables
under it Why do we need it?
◦ For example, you are writing a student record management system. Now to define a student in your software, you have to keep many variables. Such as id, name, address, phone, email, major, minor, and some more.
◦ Yes, you can deal with all these variables for all students Better if you had only one variable for each student but as we
see many variables are required to represent a student So why not create one variable for a student and put the other
variables under that [to represent that particular student) The top level variable is the structure type
Structures
struct student {◦ int id;◦ char *name;◦ char * address;◦ char *cell;
}; Struct defines a data type. Hence, student
now is a data type. We can define variables of student type as follows◦ student studentVar;
Defining Structures
We can declare and assign at the same time◦ student studentVar =
{100,”smith” ,”winnipeg”,”999-0539”}; We can assign separately as well
◦ student studentVar;◦ studentVar.id=100;◦ studentVar.name=“smith”;
Defining Structures
How to print structure variable data?◦ printf("%d,%s", studentVar.id, studentVar.name);
Legal operations with structures◦ Copy it as a unit◦ Assign to it as a unit◦ Take it’s address with &◦ Access it’s members
Structures
struct student studentVar, *pp; pp = &studentVar; printf(“student details (%d,%s)\n", (*pp).id,
(*pp).name); printf(“student details (%d,%s)\n", pp->id,
pp->name); Notice the above two lines. How the
member variables were accessed. (*pp).id or pp->id
Pointers to Structures
struct student{◦ int id;◦ char *name;◦ char *address;◦ char *cell;
} studentList = {{100,”name1”,”address1”},{101,”name2”,”address2”},{102,”name3”,”address3”}
};
Array of Structures
Union declaration, assignment may look like pretty similar to structures
Unions are usually used to store data of different data types for the same concept◦ All member variables points to the same memory location◦ Actually, we are trying to store one value◦ But as the data type of the value can differ, hence, we are
keeping options◦ Usually, the storage will be of the size of the largest data type◦ The programmer is responsible to remember and extract the
same data type he stored For example, you want to store tags. However, tags can
be of int, float, or string type based on context. Then you can declare a union as follows
Union
union tag {◦ int ival;◦ float fval;◦ char *sval;
} u;
Union
enum DAY { saturday, sunday ,monday, tuesday, wednesday, thursday, friday
} workday; enum DAY today = wednesday;
Enum
Misc◦ int ungetc(int c, FILE *fp)◦ system("date");
Storage Management void *malloc(size_t n) void *calloc(size_t n, size_t size)
int *ip; ip = (int *) calloc(n, sizeof(int));
I/O Functions
Mathematical Functions◦ sin(x) x in radian◦ cos(x)◦ atan2(y,x)◦ exp(x)◦ log(x) (x>0) , natural◦ log10(x) (x>0) , 10 based◦ pow(x,y) x to the power y◦ sqrt(x)◦ fabs(x) absolute value of x
I/O Functions
“The C Programming Language”: Kernighan and Ritchie
Internet
References