C Uptoweek3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Short Course

C Programing
Tr.Pwint Phyu Shwe
Envioronment
• http://www.Cygwin.com
• http://cygwin.com/cygwin-ug-net/cygwin-ug-net.html
• PATH %PATH%;c:\cygwin\bin
Standard
• Preprocessor
• Library/header
#include <stdio.h>
• Entry
int main(){return 0;}
main(){}
Escape Sequence
Escape Sequence Purpose Example
\n Create new line
\t Create tab
\r Move cursor to the beginning of current
line
\\ Insert backslash C:\
\” Double quote ”This is sample”
\’ Single quote Susan’s house

Example:
printf("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
printf("\t\t\t\t1\t2\t3\n");
printf("4\t5\t6\t7\t8\t9\t10\n");
Compilation
compiler
• gcc <filename.c> => default a.out
• gcc <programName.c> –o <executableName.out> => executableName
• gcc <programName.c> –o <executableName> => executableName

Run Program
• ./a.out
• executableName
Primary Data Type
Data Types
Integers – int , short , long
Floating Point – float, double
Character – char
0x001

Declaration
<data types> < variable name> = <value>
int x;
Assignment
int x = 10;
Print content
int x;
float y; Placeholder
char c;
%d
%f
x = -44;
%c
y = 10.33;
c = ‘z’; %.2f

printf("value integer variable x is %d \n", x);


printf("value float variable y is %f \n", y);
printf("value char variable c is %c \n", c);
printf("value float with 2 decimal %.2f", y);
Print content – Character Array, Pointer
char* sch;
char sch[100];
sch = “Spring”.
printf (”value %s \n ", sch);

%p for Pointer Address


%h for hexadecimal
Input from screen - scanf
int ivar;
float fvar;
char cvar;

printf(“enter integer variable x value \n”);


scanf(“%d”, &ivar);
printf(“enter float variable y value \n”);
scanf(“%f”, &fvar);
printf(“enter char variable z value \n”);
scanf(“%c”, &cvar);
Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

memory address %p
fgets
fgets() is a library function in C. It reads a line from the specified stream and stores it into the string pointed to
by the string variable. It only terminates when either:
• end-of-file is reached
• n-1 characters are read
• the newline character is read
int x;
char str[100];
scanf("%d", &x);
fgets(str, 100, stdin);
printf("x = %d, str = %s", x, str);
Constant
• const
can’t change through out program
const float PI = 3.14
Arithmetic in C
X = 10, y=3, z = 2

Symbol Operation
+ x+y 13
- x-y 7
* x*y 30
/ x/y 3.333
% x%y 1

Precedence
1. */ %
2. +-
Char Array
• Characters array Dynamic array using Pointer
char myString[5] = {‘J', ‘a', ‘m', ’e’, ’s’, '\0'};
char myString[] = “James”;
Pointer Character (To explain details in next chapert)
char *myString = ”James";

Reading and Printing


0xff
Initialize
char myString[5] = {'\0’};
J a m e s \0
printf("Enter your name: ");
Data Retrieve
scanf(” %s", myString);
Condition
int x = 10;

- if..else switch (x){


- Nested if..else case 1: break;
- switch
case 2: break;

case 10:
X*=10;
break;
default: printf(“there is no value relevant”);

}
Begin

yes
encrypt Do encrypt

No

yes
decrypt Do decrypt

No

yes
encode Do encode

No

yes
decode Do encode

No

Error
Week - 2
Function
• Function is used for code reusability
• Dedicated activities conduct in each function block

System Support printf(),scanf(), exp(), pow()

account

User design
Function - call
• Funcation can be call multiple times from calling program
• Function can have muliples
• Empty Function – display()
• Function with one or more arguments/parameters – deposit(double)
• Function with no return - void
• Function with return – datatype (int, bool, char, double)
Variable Scope
• Global Scope
• Share data between and across functions. Global variables are created and defined outside any functions

• Local Scope
• local scope variables are tied to their originating functions, you can’t reuse variable names in other functions without running the risk
of overwriting data. Local variables are created and defined inside function
Array
• Supports to build collections of same data type.
• Share same variable with different index
• Each value inside index is called element
• can be declared to various data type (int, float, short, char)

index
memory addr

num[0] 7 2290xF int num[4] = {7,20,-32,-100};


Variable name
num[1] 20 229012 int num[4];
//later initialization
num[2] -32 229017 num[0] = 7;
num[1] = 20;
num[3] -100 229021
num[2] = -32;
num[3] = -100;
Char Array
• Character array must be initialized before using it
• Character array has special features – hold characters plus NULL (‘\0’) terminator at
end.
• Creating character arrays require to assign enough value to store including last
NULL character.

char cName[] = {‘J’, ‘O’, ‘Y’, ‘\0’};


index
memory addr
char cName = “JOY”;
cName[0] J 2290xF
Variable name Reading and Printing
cName[1] O 229012 Initialize
char myString[5] = {'\0’};
cName[2] Y 229017 printf("Enter your name: ");
Data Retrieve
cName[3] \0 229021 scanf(” %s", myString);
Two Dimensional Array
int twoD[3][3];

COLUMN
[0][0] [0][1] [0][2]
int iTwoD[3][3] = { {10, 12, 18},
R 10 12 18 {21, 23, 22},
O {20, 30, 40} };
W [1][0] 21 23 22

[2][0] 20 30 40 iTwoD[0][0] = 10;…

//Initializing using default value


int x, y;
//row
for ( x = 0; x <= 2; x++ ) {
for (int x = 0 ; x < size; x++){ //each row of columns
scanf (”%d” , i1D[x] ) for ( y = 0; y <= 2; y++ )
} iTwoD[x][y] = ( x + y );
}
Pointers
• variable hold memory address
• That address point to variable of another, function and data structure
• only can assign memory address, 0 or NULL

char c = ‘C’; x 10 0x16dd73938


int x = 10;
int *ptrX; //pointer declaration char *ptrC;
ptr 0x16dd73938
ptrX = &x; (address of)

int y = *ptrX (indirection operator ) y 10

*ptr = 20;
Week 3
Initialization Pointer
int *ptrSample = NULL;
int *ptrSample = 0;
int x = 10;
int* ptrSample = &x;

As practice: pointer must be initialized with another variable’s memory address or with 0 or NULL. Not initializing
may result invalid data or invalid expression.
Array with Pointer
Array variable name holds the address of first index.

For example:

variable num holds the address of first index and it is constant value.

int *ptr = num;


int num[4] = {7,20,-32,-100};
ptr = num ; (ptr get address 2290xF)

printf (“%p”, ptr); // 2290xF;


printf (“%p”, ptr+1); // 229012;
index
variable num can’t be moveable but the ptr created can be move around. memory addr

num[0] 7 2290xF
Variable name
num[1] 20 229012

num[2] -32 229017

num[3] -100 229021


Pointer Calculation
• pointer address can be calculated and change using arithmetic operator (+, -)
ptr = num;
• based on pointer data type addition and subtraction will be automatically adjusted to data size (For example:
+1 means if it is interger moving to next 4 bytes, if character then moving to next 1 byte)

index
Example: memory addr

num[0] 7 2290xF
Variable name
num[1] 20 229012

num[2] -32 229017

num[3] -100 229021


Function & Pointer
• change the original value of data rather than giving out copy value
• pass memory address of variable to function
• useful for efficient memory management as well as ability to modified single value from different places
• careful for not to misuse
• pointer is most useful with array passing (pass by argument are pass by reference)

index
memory addr

num[0] 7 2290xF int num[4] = {7,20,-32,-100};


Variable name
num[1] 20 229012 array name (num) itself is a pointer to first
memory address.
num[2] -32 229017
printf (“%p”, num);
num[3] -100 229021
Encryption
• Cryptography—The art and science of protecting or obscuring messages.
• Cipher text—A message obscured by applying an encryption algorithm.
• Clear text—Plain text or a message readable by humans.
• Cryptogram—An encrypted or protected message.
• Cryptographer—A person or specialist who practices encrypting or protecting messages.
• Encryption—The process by which clear text is converted into cipher text.
• Decryption—The process of converting cipher text into clear text; generally involves knowing a key or
formula.
• Key—The formula used to decrypt an encrypted message.
Keys used to lock and unlock secured messages, or cryptograms, can either be stored in the
encrypted message itself or be used in conjunction with outside sources, such as account numbers and
passwords.
Cryptogram Program
String
• build on top with combination of char array and pointer
• it’s a library function
• string names are just pointer that point to first character of array
• there is no data type called string in c unlike other programming languages (VB, C#)

char *myString = “Mike”;

string str = “Mike”


Reading/Printing
• string can’t use without initialization

char *myString = “Mike”; M I K e \0

Normal input character array from user input


char myName[10] = {’\0’};
scanf(“%s”, myNmae);
Will compile but will not work
char *myName;
scanf(“%s”, myNmae);
String arrays
Single Arrays
char *myStuName[3] = {0};

myStuName[0] = “Susan”; char *names[]={“Jimmy”, “George”, “Louis”, “James”,”Mike” };


myStuName[1] = “Joseph”
myStuName[2] = “Philip”;

S u s a n \0
J o s e p h \0
P h i l i p \0
Convert String to Number
• Under stdlib.h
• string to floating point - atof
• string to number - atoi

char *str1 = "123.79";


char *str2 = "55";
float y = atof(str1);
int x = atoi(str2);
Manipulate String
• Under string.h library
char *str1 = "A";
char *str1 = ”Susan"; char *str2 = ”a";
strlen(str1); //5 char *str3 = ”A";
char *str2;
strcpy(str2, str1); strcmp(str1,str2)
Comparison ,
if same 0
• Under ctype.h library front greater > 0
• toupper(char) front lesser < 0
• tolower(char)

char *str1 = ”susan";


for ( int x = 0; x <= strlen(str); x++ ) SUSAN
str[x] = toupper(str[x]);
string - library
strcmp() – string comparison strstr()-useful function to analyze two strings
searches the first string for an occurrence of the
char *str1 = "A"; second string
char *str2 = "A";
char *str3 = "!” char *str1 = “I have a credit card”;
char *str2 = “card”;
printf("\nstrcmp(str1, str2) = %d\n", strcmp(str1, str2)); char *str3 = “bank”;
printf("\nstrcmp(str1, str3) = %d\n", strcmp(str1, str3)); if ( strstr(str1, str2) != NULL ){
printf("\nstrcmp(str3, str1) = %d\n", strcmp(str3, str1)); printf(“str2 was found in str1\n”);
}
Return value
Return value
0 , when equal
!= NULL , Found
> 0 , when first greater than second
== NULL, not Found
< 0, when first less than second
struct
blueprint of object where allow to copy many times with same structure for consistency.

• for every usage an instance is created and


struct room{ allocate in memory
float width; • initialization same like other data type
float length;
float height; struct room bedroom = {10.0, 15.0, 9.0};
}; struct room livingroom = {30.0, 20.0, 9.0};
struct room dinningroom = {10.0, 20.0, 9.0};
width
lenght
height
typedef
The typedef keyword is used for creating structure definitions to build an alias relationship with the
structure tag (structure name)

typedef struct room{ typedef struct scores {


float width; char subjname[10];
float length; int score;
float height; } scorecard;
}rm;

rm bedroom, diningroom; scorecard physic = {“Physic”, 80};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy