Vous êtes sur la page 1sur 17

C Programming Notes

The C program is a set of functions.


The program execution begins by executing the function main ().
#include <stdio.h>
main(){
printf("Hi \n");
}
Hi

C Language Keywords
auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
for
goto
if

int
long
register
return
short
signed
sizeof
static

struct
switch
typedef
union
unsigned
void
volatile
while

In all C programs, the starting point is the main() function.


Every C program has one.
#include <stdio.h>
int main()
{
printf("Goodbye!\n");
return(0);
}
List the command line arguments
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Program name: %s\n", argv[0]);
int i;
for(i = 1 ; i<argc ; i++)
printf("\nArgument %d: %s", i, argv[i]);
return 0;
}

Variables

1.
2.
3.
4.
5.
6.

You can store values in variables.


Each variable is identified by a variable name.
Each variable has a variable type.
Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores.
Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables.
The variables are defined at the begining of the block.

The following is an example of some variable names:


average
/* average of all grades */
pi

/* pi to 6 decimal places */
number_of_students /* number students in this class */

The following are not variable names:


3rd_
/* Begins with a number */
all$
the end
int

/* Contains a "$" */
/* Contains a space */
/* Reserved word */

Meaningful variable name:


entry_total /* total number of items in current entry */
all_total

/* total of all entries */

How to declare a variable


A variable declaration serves three purposes:
1. It defines the name of the variable.
2. It defines the type of the variable (integer, real, character, etc.).
3. It gives the programmer a description of the variable.
int answer;
/* the result of our expression */
1. The keyword int tells C that this variable contains an integer value.
2. The variable name is answer.
3. The semicolon (;) marks the end of the statement.
4. The comment is used to define this variable for the programmer.

Using a variable to store value


#include <stdio.h>

int main(void)
{
int salary;
salary = 10000;
printf("My salary is %d.", salary);
return 0;
}
Initialize int value in declaration
#include <stdio.h>
int main(void)
{
int number0 = 10, number1 = 40, number2 = 50, number3 = 80, number4 = 10;
int number5 = 20, number6 = 30, number7 = 60, number8 = 70, number9 = 110;
int sum = number0 + number1+ number2 + number3 + number4+
number5 + number6 + number7 + number8 + number9;
float average = (float)sum/10.0f;
printf("\nAverage of the ten numbers entered is: %f\n", average);
return 0;
}
Average of the ten numbers entered is: 48.000000

Meaningful variable name


int p,q,r;
Now consider another declaration:
int account_number;
int balance_owed;
int account_number;

/* Index for account table */

int balance_owed;

/* Total owed us (in pennies)*/

Define three variables and use assignment operator to assign value


int main()
{
int term;
int term_2;

/* term used in two expressions */


/* twice term */

int term_3;

/* three times term */

term = 3 * 5;
term_2 = 2 * term;
term_3 = 3 * term;
return (0);
}
Use printf to output variable
#include <stdio.h>
int main()
{
int term;

/* term used in two expressions */

term = 3 * 5;
printf("Twice %d is %d\n", term, 2*term);
printf("Three times %d is %d\n", term, 3*term);
return (0);
}
Twice 15 is 30
Three times 15 is 45

Printing Variable Contents


Use the printf function with formatting options.
#include <stdio.h>
main(){
int x;
float y;
char c;
x = -4443;
y = 554.21;
c = 'M';
printf("\nThe value of integer variable x is %d", x);
printf("\nThe value of float variable y is %f", y);
printf("\nThe value of character variable c is %c\n", c);
}
The value of integer variable x is -4443
The value of float variable y is 554.210022
The value of character variable c is M

Conversion specifiers are made up of two characters: % and a special character.

The special character tells the program how to convert the data.
Conversion Specifier
%d
%f
%c

Description
Displays integer value
Displays floating-point numbers
Displays character

Finding the limits


#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(void)
{

printf("Variables of type char store values from %d to %d", CHAR_MIN, CHAR_MAX);


printf("\nVariables of type unsigned char store values from 0 to %u", UCHAR_MAX);
printf("\nVariables of type short store values from %d to %d", SHRT_MIN, SHRT_MAX);
printf("\nVariables of type unsigned short store values from 0 to %u",USHRT_MAX);
printf("\nVariables of type int store values from %d to %d", INT_MIN, INT_MAX);
printf("\nVariables of type unsigned int store values from 0 to %u", UINT_MAX);
printf("\nVariables of type long store values from %ld to %ld", LONG_MIN, LONG_MAX);
printf("\nVariables of type unsigned long store values from 0 to %lu", ULONG_MAX);
printf("\nVariables of type long long store values from %lld to %lld", LLONG_MIN, LLONG_MA
printf("\nVariables of type unsigned long long store values from 0 to %llu", ULLONG_MAX);
printf("\n\nThe size of the smallest non-zero value of type float is %.3e", FLT_MIN);
printf("\nThe size of the largest value of type float is %.3e", FLT_MAX);
printf("\nThe size of the smallest non-zero value of type double is %.3e", DBL_MIN);
printf("\nThe size of the largest value of type double is %.3e", DBL_MAX);
printf("\nThe size of the smallest non-zero value of type long double is %.3Le", LDBL_MIN);
printf("\nThe size of the largest value of type long double is %.3Le\n", LDBL_MAX);
printf("\nVariables of type float provide %u decimal digits precision.", FLT_DIG);
printf("\nVariables of type double provide %u decimal digits precision.", DBL_DIG);
printf("\nVariables of type long double provide %u decimal digits precision.", LDBL_DIG);
return 0;
}
Variables of type
Variables of type
Variables of type
Variables of type
Variables of type
Variables of type
Variables of type
Variables of type
Variables of type
9223372036854775807
Variables of type
The
The
The
The
The
The

size
size
size
size
size
size

of
of
of
of
of
of

the
the
the
the
the
the

char store values from -128 to 127


unsigned char store values from 0 to 255
short store values from -32768 to 32767
unsigned short store values from 0 to 65535
int store values from -2147483648 to 2147483647
unsigned int store values from 0 to 4294967295
long store values from -2147483648 to 2147483647
unsigned long store values from 0 to 4294967295
long long store values from -9223372036854775808 to
unsigned long long store values from 0 to 18446744073709551615

smallest non-zero value of type float is 1.175e-38


largest value of type float is 3.403e+38
smallest non-zero value of type double is 2.225e-308
largest value of type double is 1.798e+308
smallest non-zero value of type long double is 3.362e-4932
largest value of type long double is 1.190e+4932

Variables of type float provide 6 decimal digits precision.


Variables of type double provide 15 decimal digits precision.
Variables of type long double provide 18 decimal digits precision.

Finding the size of a type


#include <stdio.h>
int main(void)
{
printf("\nVariables
printf("\nVariables
printf("\nVariables
printf("\nVariables
printf("\nVariables
printf("\nVariables
printf("\nVariables
return 0;
}
Variables
Variables
Variables
Variables
Variables
Variables
Variables

of
of
of
of
of
of
of

type
type
type
type
type
type
type

of
of
of
of
of
of
of

type
type
type
type
type
type
type

char occupy %d bytes", sizeof(char));


short occupy %d bytes", sizeof(short));
int occupy %d bytes", sizeof(int));
long occupy %d bytes", sizeof(long));
float occupy %d bytes", sizeof(float));
double occupy %d bytes", sizeof(double));
long double occupy %d bytes", sizeof(long double));

char occupy 1 bytes


short occupy 2 bytes
int occupy 4 bytes
long occupy 4 bytes
float occupy 4 bytes
double occupy 8 bytes
long double occupy 12 bytes

Scope of variables
1.
2.
3.
4.
5.

Variable can be defined in the block.


The blocks are marked using { and } braces.
The scope of the variable is in the block where it is declared.
Variable defined in the outer block can be used in the inner block.
The nearest definition has more precedence.

#include <stdio.h>
main() {
int i = 10;
{
int i = 0;
for( i=0;i<2;i++)
{
printf("value of i is %d\n",i);
}
}
printf("the value of i is %d\n",i);
}

value of i is 0
value of i is 1
the value of i is 10

Inner variable shadows outer variable


#include <stdio.h>
int main(void)
{
int count = 0;
do
{
int count = 0;
++count;
printf("\ncount = %d ", count);
}
while( ++count <= 8 ); /* This works with outer count */
/* this is outer */
printf("\ncount = %d\n", count);
return 0;
}
count
count
count
count
count
count
count
count
count
count

=
=
=
=
=
=
=
=
=
=

1
1
1
1
1
1
1
1
1
9

Declare global variables


A global variable is available to all functions in your program.
A local variable is available only to the function in which it's created.
1. Global variables are declared outside of any function.
2. Global variables are typically declared right before the main() function.
3. You can also declare a group of global variables at one time:
int s,t;
And, you can preassign values to global variables, if you want:
char prompt[]="What?"
;
Define and use Global variables

#include <stdio.h>
int count = 0;

/* Declare a global variable

*/

void test1(void){
printf("\ntest1 count = %d ", ++count);
}
void test2(void){
static int count;
/* This hides the global count */
printf("\ntest2 count = %d ", ++count);
}
int main(void){
int count = 0;

/* This hides the global count */

for( ; count < 5; count++) {


test1();
test2();
}
return 0;
}
value of i in main 0
value of i after call 50

Local variable shadows global variable.


#include <stdio.h>
int i =0;
//Global variable
main(){
int i ;
// local variable
void f1(void) ;
i =0;
printf("value of i in main %d\n",i);
f1();
printf("value of i after call%d\n",i);
}
f1(void)
{
int i=0;
i = 50;
}
value of i in main 0
value of i after call 0

Static variable

#include <stdio.h>
int g = 10;
main(){
int i =0;
void f1();
f1();
printf(" after first call \n");
f1();
printf("after second call \n");
f1();
printf("after third call \n");
}
void f1()
{
static int k=0;
int j = 10;
printf("value of k %d j %d",k,j);
k=k+10;
}
value of k 0 j 10 after first call
value of k 10 j 10after second call
value of k 20 j 10after third call

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


{
test1();
test2();
}
return 0;
}
test1
test2
test1
test2
test1
test2
test1
test2
test1
test2

count
count
count
count
count
count
count
count
count
count

=
=
=
=
=
=
=
=
=
=

1
1
1
2
1
3
1
4
1
5

Output address and value


#include <stdio.h>

int main(void)
{
int number = 0;
int *pointer = NULL;
number = 10;
printf("\nnumber's address: %p", &number);
printf("\nnumber's value: %d\n\n", number);

/* Output the address */


/* Output the value */

return 0;
}
number's address: 9a378
number's value: 10

Using the & operator


#include<stdio.h>
int main(void)
{
long a = 1L;
long b = 2L;
long c = 3L;
double d = 4.0;
double e = 5.0;
double f = 6.0;
printf("A variable of type long occupies %d bytes.", sizeof(long));
printf("\nHere are the addresses of some variables of type long:");
printf("\nThe address of a is: %p The address of b is: %p", &a, &b);
printf("\nThe address of c is: %p", &c);
printf("\n\nA variable of type double occupies %d bytes.", sizeof(double));
printf("\nHere are the addresses of some variables of type double:");
printf("\nThe address of d is: %p The address of e is: %p", &d, &e);
printf("\nThe address of f is: %p\n", &f);
return 0;
}
A variable of type long occupies 4 bytes.
Here are the addresses of some variables of type long:
The address of a is: 9a57c The address of b is: 9a578
The address of c is: 9a574
A variable of type double occupies 8 bytes.
Here are the addresses of some variables of type double:
The address of d is: 9a568 The address of e is: 9a560
The address of f is: 9a558

Put values in the memory locations by using pointers

#include <stdio.h>
main(){
int a[5];
int *b;
int *c;
int i;
for(i = 0;i<5;i++){
a[i]=i;
}
for(i = 0;i<5;i++) {
printf("value in array %d\n",a[i]);
}
b=a;
b++;
*b=4;
b++;
*b=6;
b++;
*b=8;
b++;
*b=10;
b++;
*b=12;
printf("after\n\n\n");
for(i = 0;i<5;i++) {
printf("value in array %d\n",a[i]);
}
}
value
value
value
value
value
after

in
in
in
in
in

array
array
array
array
array

0
1
2
3
4

value
value
value
value
value

in
in
in
in
in

array
array
array
array
array

0
4
6
8
10

Calculate an average using variable argument lists


#include <stdio.h>
#include <stdarg.h>
double average(double v1 , double v2,...);

/* Function prototype */

int main(void)
{
double Val1 = 10.5, Val2 = 2.5;
int num1 = 6, num2 = 5;
long num3 = 12, num4 = 20;
printf("\n Average = %lf", average(Val1, 3.5, Val2, 4.5, 0.0));
printf("\n Average = %lf", average(1.0, 2.0, 0.0));
printf("\n Average = %lf\n", average( (double)num2, Val2,(double)num1,
(double)num4,(double)num3, 0.0));
return 0;
}
/* Function to calculate the average of a variable number of arguments */
double average( double v1, double v2,...)
{
va_list parg;
/* Pointer for variable argument list */
double sum = v1+v2;
/* Accumulate sum of the arguments */
double value = 0;
/* Argument value
*/
int count = 2;
/* Count of number of arguments
*/
va_start(parg,v2);

/* Initialize argument pointer

while((value = va_arg(parg, double)) != 0.0)


{
sum += value;
count++;
}
va_end(parg);
/* End variable argument process
return sum/count;
}
Average = 5.250000
Average = 1.500000
Average = 9.100000

Adding Comments
Comments in a C program have a starting point and an ending point.
Everything between those two points is ignored by the compiler.
/* This is how a comment looks in the C language */
The beginning of the comment is marked by the slash and the asterisk: /*.
The end of the comment is marked by the asterisk and the slash: */.
#include <stdio.h>
int main(){
/* This is the comment.*/
printf("%15s","right\n");
printf("%-15s","left\n");

*/

*/

return(0);
}
right
left

Using Comments to Disable


Comments are ignored by the compiler.
You can use comments to disable certain parts of your program.
#include <stdio.h>
int main(){
/* printf("%15s","right\n"); */
printf("%-15s","left\n");
return(0);
}
left

The comments are enclosed in '/*...*/'


#include <stdio.h>
main(){
printf("Hi \n"); /* This is the comments.*/
}
Hi

The '//' is used as single line comment


#include <stdio.h>
main(){
int i,j,k;
i = 6;
j = 8;
k = i + j;
printf("sum of two numbers is %d \n",k); // end of line comment
}
sum of two numbers is 14

Source code header comments

1. At the beginning of the program is a comment block.


2. The comment block contains information about the program.
3. Boxing the comments makes them stand out.
The some of the sections as follows should be included.
1. Heading.
2. Author.
3. Purpose.
4. Usage.
5. References.
6. File formats. A short description of the formats which will be used in the program.
7. Restrictions.
8. Revision history.
9. Error handling.
10. Notes. Include special comments or other information that has not already been covered.
/********************************************************
* hello -- program to print out "Hello World".
*
*
*
* Author: FirstName, LastName
*
*
*
* Purpose: Demonstration of a simple program.
*
*
*
* Usage:
*
*
Runs the program and the message appears.
*
********************************************************/
#include <stdio.h>
int main()
{
/* Tell the world hello */
printf("Hello World\n");
return (0);
}
Hello World

1.15.Comments
Indentation and Code Format
while (! done) {
printf("Processing\n");
next_entry();
}

if (total <= 0) {
printf("You owe nothing\n");
total = 0;
} else {
printf("You owe %d dollars\n", total);
all_totals = all_totals + total;
}
In this case, curly braces ({}) are put on the same line as the statements.
The other style puts the {} on lines by themselves:
while (! done)
{
printf("Processing\n");
next_entry();
}
if (total <= 0)
{
printf("You owe nothing\n");
total = 0;
}
else
{
printf("You owe %d dollars\n", total);
all_totals = all_totals + total;
}
Clarity
/* poor programming practice */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;

temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;

A better version would be:


/*
* Swap the two corners
*/
/* Swap X coordinate */
temp = box_x1;
box_x1 = box_x2;
box_x2 = temp;
/* Swap Y coordinate */
temp = box_y1;
box_y1 = box_y2;
box_y2 = temp;
Include header file
#include <stdio.h>
int main(void)
{
printf("\nBe careful!!\a");
return 0;
}
Be careful!!

Headers
1. Each function in the C standard library has its associated header.
2. The headers are included using #include.
3. Header Including obtains the Declarations for the standard library functions.

Common Headers
Header
assert.h
ctype.h
errno.h
float.h
limits.h
locale.h
math.h
setjmp.h
signal.h
stdarg.h
stddef.h
stdio.h
stdlib.h
string.h
time.h

Purpose
Defines the assert() macro
Character handling
Error reporting
Defines implementation-dependent floating-point limits
dependent limits
Localization
math library
Nonlocal jumps
Signal handling
Variable argument lists
Constants
I/O system
Miscellaneous declarations
string functions
system time functions

Vous aimerez peut-être aussi