Handout_Problem_Solving_and_C_Programming_v1[1].0

Share Embed Donate


Short Description

Download Handout_Problem_Solving_and_C_Programming_v1[1].0...

Description

Handout: Problem Solving and 'C' Programming

Version: PSC/Handout/1107/1.0 Date: 16-11-07

Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com

Problem Solving and C Programming

TABLE OF CONTENTS About this Document ....................................................................................................................6 Target Audience ...........................................................................................................................6 Objectives .....................................................................................................................................6 Pre-requisite .................................................................................................................................6 Session 2: Introduction to Problem Solving and Programming Languages ...........................7 Learning Objectives ......................................................................................................................7 Problem Solving Aspect ...............................................................................................................7 Program Development Steps .......................................................................................................8 Introduction to Programming Languages ...................................................................................14 Types and Categories of Programming Languages ...................................................................15 Program Development Environments ........................................................................................18 Summary ....................................................................................................................................19 Test your Understanding ............................................................................................................19 Session 3: Introduction to C Programming Language .............................................................21 Learning Objectives ....................................................................................................................21 Introduction to C Language ........................................................................................................21 Evolution and Characteristics of C Language ............................................................................21 Structure of a C Program ............................................................................................................23 C Compilation Model ..................................................................................................................24 C Fundamentals .........................................................................................................................25 Character Set..............................................................................................................................25 Keywords ....................................................................................................................................26 Identifiers ....................................................................................................................................26 Data Types .................................................................................................................................26 Variables .....................................................................................................................................28 Constants....................................................................................................................................29 Operators ....................................................................................................................................30 Expressions ................................................................................................................................32 Type Casting...............................................................................................................................33 Input and Output Statements......................................................................................................35 Try It Out .....................................................................................................................................39 Summary ....................................................................................................................................39 Test your Understanding ............................................................................................................39 Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Session 5: Selection and Control Structures ............................................................................41 Learning Objectives ....................................................................................................................41 Basic Programming Constructs ..................................................................................................41 Sequence....................................................................................................................................42 Selection Statements ..................................................................................................................42 ‘if’ Statement ...............................................................................................................................42 Conditional / Ternary / ?: Operator .............................................................................................44 Switch Statement ........................................................................................................................45 Iteration Statements ...................................................................................................................46 ‘for’ statements ...........................................................................................................................46 ‘while’ statement .........................................................................................................................48 ‘do - while’ statement ..................................................................................................................48 Break, Continue Statements.......................................................................................................49 Try It Out .....................................................................................................................................50 Summary ....................................................................................................................................51 Test your Understanding ............................................................................................................51 Session 7: Arrays and Strings ....................................................................................................53 Learning Objectives ....................................................................................................................53 Need for an Array .......................................................................................................................53 Memory Organization of an Array...............................................................................................53 Declaration and Initialization.......................................................................................................54 Basic Operation on Arrays..........................................................................................................55 Multi-dimensional Array ..............................................................................................................56 Strings.........................................................................................................................................58 String Functions ..........................................................................................................................59 Character Functions ...................................................................................................................61 Try It Out .....................................................................................................................................61 Summary ....................................................................................................................................63 Test your Understanding ............................................................................................................63 Session 9: Functions ...................................................................................................................65 Learning Objectives ....................................................................................................................65 Need for Functions .....................................................................................................................65 Function Prototype .....................................................................................................................66 Function Definition ......................................................................................................................67 Function Call ...............................................................................................................................69 Passing Arguments ....................................................................................................................70 Functions and Arrays ..................................................................................................................73 Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Try It Out .....................................................................................................................................75 Summary ....................................................................................................................................77 Test your Understanding ............................................................................................................77 Session 10: Functions/Structures and Unions..........................................................................79 Learning Objectives ....................................................................................................................79 Storage Classes .........................................................................................................................79 Command Line Arguments .........................................................................................................82 Introduction to Structures and Unions ........................................................................................83 Declaration and Initialization.......................................................................................................84 Structures and Arrays .................................................................................................................87 Structures and Functions ............................................................................................................88 Try It Out .....................................................................................................................................89 Summary ....................................................................................................................................90 Test your Understanding ............................................................................................................90 Session 14: Structures and Unions / Files and Preprocessor directives ...............................92 Learning Objectives ....................................................................................................................92 Unions.........................................................................................................................................92 Union of Structures .....................................................................................................................93 Enumeration ...............................................................................................................................94 Typedef Statement .....................................................................................................................95 Introduction to Files ....................................................................................................................95 File Operations ...........................................................................................................................96 Character I/O ..............................................................................................................................98 String I/O...................................................................................................................................100 Numeric I/O...............................................................................................................................100 Formatted I/O............................................................................................................................101 Block I/O ...................................................................................................................................102 Try It Out ...................................................................................................................................104 Summary ..................................................................................................................................106 Test your Understanding ..........................................................................................................106 Session 15: Files and Preprocessor directives / Pointers .....................................................108 Learning Objectives ..................................................................................................................108 Random File Operations ...........................................................................................................108 Preprocessor Directives ...........................................................................................................109 Introduction to Pointers .............................................................................................................115 Declaration and Initialization.....................................................................................................115

Page 4 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Pointer Arithmetic .....................................................................................................................116 Pointers and Arrays ..................................................................................................................117 Try It Out ...................................................................................................................................123 Summary ..................................................................................................................................125 Test your Understanding ..........................................................................................................125 Session 17: Pointers ..................................................................................................................127 Learning Objectives ..................................................................................................................127 Functions and Pointers .............................................................................................................127 Structures and Pointers ............................................................................................................129 Dynamic Memory Allocation .....................................................................................................130 Try It Out ...................................................................................................................................133 Summary ..................................................................................................................................136 Test your Understanding ..........................................................................................................136 Syntax Summary ........................................................................................................................138 References ..................................................................................................................................151 Websites ...................................................................................................................................151 Books ........................................................................................................................................151 STUDENT NOTES: ......................................................................................................................152

Page 5 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Introduction

About this Document This document provides the following topics: ‰

Problem solving concepts

‰

An introduction to C programming language

‰

Basic concepts of C programming language

Target Audience In-Campus Trainees

Objectives ‰

Explain the concepts of problem solving

‰

Explain the concepts of C programming language

‰

Write effective programs using C programming language

Pre-requisite This module does not require any pre-requisites

Page 6 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Session 2: Introduction to Problem Solving and Programming Languages Learning Objectives After completing this session, you will be able to: ‰

Explain the Problem Solving Aspect

‰

Identify the steps involved in program development

‰

Know about the Programming Languages and it’s types and categories

‰

Understand the Program Development Environments

Problem Solving Aspect Problem solving is a creative process. It is an act of defining a problem, determining the cause of the problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a solution.

A problem can be solved successfully only after making an effort to understand the problem. To understand the problem, the following questions help: ‰

What do we know about the problem?

‰

What is the information that we have to process in order the find the solution?

‰

What does the solution look like?

‰

What sort of special cases exist?

‰

How can we recognize that we have found the solution?

It is important to see if there are any similarities between the current problem and other problems that have already been solved. We have to be sure that the past experience does not hinder us in developing new methodology or technique for solving a problem. The important aspect to be considered in problem-solving is the ability to view a problem from a variety of angles.

There is no universal method for solving a given problem. Different strategies appear to be good for different problems. Some of the well known strategies are: ‰

Divide and Conquer

‰

Greedy Method

‰

Dynamic Programming

‰

Backtracking

‰

Branch and Bound

Page 7 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Program Development Steps The various steps involved in Program Development are: o

Defining or Analyzing the problem

o

Design (Algorithm)

o

Coding

o

Documenting the program

o

Compiling and Running the Program

o

Testing and Debugging

o

Maintenance

Analyzing or Defining the Problem The problem is defined by doing a preliminary investigation. Defining a problem helps us to understand the problem clear. It is also known as Program Analysis. Tasks in defining a problem: o

Specifying the input requirements

o

Specifying the output requirements

o

Specifying the processing requirements

Specifying the input requirements Determine the inputs required and source of the data. The input specification is obtained by answering the following questions: o

What specific values will be provided as input to the program?

o

What format will the values be?

o

For each input item, what is the valid range of values that it may assume?

o

What restrictions are placed on the use of these values?

Specifying the output requirements Describe in detail the output that will be produced. The output specification is obtained by answering the following questions: o

What values will be produced?

o

What is the format of these values?

o

What specific annotation, headings, or titles are required in the report?

o

What is the amount of output that will be produced?

Specifying the Processing Requirements Determine the processing requirements for converting the input data to output. The processing requirement specification is obtained by answering the following questions: o

What is the method (technique) required in producing the desired output?

o

What calculations are needed?

o

What are the validation checks that need to be applied to the input data?

Page 8 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Example 2.1 Find the factorial of a given number Input: Positive valued integer number Output: Factorial of that number Process: Solution technique which transforms input into output. Factorial of a number can be calculated by the formula n! = 1*2*3*4….*n

Design A design is the path from the problem to a solution in code. Program Design is both a product and a process. The process results in a theoretical framework for describing the effects and consequences of a program as they are related to its development and implementation. A well designed program is more likely to be: ‰

Easier to read and understand later

‰

Less of bugs and errors

‰

Easier to extend to add new features

‰

Easier to program in the first place

Modular Design Once the problem is defined clearly, several design methodologies can be applied. An important approach is Top-Down programming design. It is a structured design technique which breaks up the problem into a set of sub-problems called Modules and creates a hierarchical structure of modules. While applying top-down design to a given problem, consider the following guidelines: ‰

A problem is divided it into smaller logical sub-problems, called Modules

‰

Each module should be independent and should have a single task to do

‰

Each module can have only one entry point and one exit point, so that the logic flow of the program is easy to follow

‰

When the program is executed, it must be able to move from one module to the next in sequence, until the last module is executed

‰

Each module should be of manageable size, in order to make the design and testing easier

Top-down design has the following advantages: ‰

Breaking up the problem into parts helps us to clarify what is to be done

‰

At each step of refinement, the new parts become more focussed and, therefore, easier to design

‰

Modules may be reused

‰

Breaking the problem into parts allows more than one person to work on the solution simultaneously

Page 9 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Algorithm (Developing a Solution technique) An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered sequence of well-defined and effective operations which, when carried out for a given set of initial conditions, produce output, and terminate in a finite time. The term “ordered sequence” specifies, after the completion of each step in the algorithm, the next step must be unambiguously defined. An algorithm must be: ‰

Definite

‰

Finite

‰

Precise and Effective

‰

Implementation independent ( only for problem not for programming languages)

Developing Algorithms Algorithm development process is a trial-and-error process. Programmers make initial attempt to the solution and review it, to test its correctness. The errors identified leads to insertions, deletions, or modifications to the existing algorithm.

This refining continues until the programmer is satisfied that, the algorithm is essentially correct and ready to be executed. The more experience we gain in developing an algorithm, the closer our first attempt will be to a correct solution and the less revision will be required. However, a novice programmer should not view developing algorithm as a single-step operation Example 2.2: Algorithm for finding factorial of a given number Step 1: Start Step 2: Initialize factorial to be 1, i to be 1 Step 3: Input a number n Step 4: Check whether the number is 0. If so report factorial is 1 and goto step 9 Step 5: Repeat step 6 through step 7 n times Step 6: Calculate factorial = factorial * i Step 7: Increment i by 1 Step 8: Report the calculated factorial value Step 9: Stop

Pseudo Code Pseudo code is an informal high-level description of an algorithm that uses the structural conventions of programming languages, but omits language-specific syntax. It is an outline of a program written in English or the user's natural language. Example 2.3: Pseudo Code for finding factorial of a given number Step 1: START Step 2: DECLARE the variables n, fact, i Step 2: SET variable fact =1 and i =1

Page 10 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Step 3: READ the number n Step 4: IF n = 0 then Step 4.1: PRINT factorial = 1 Step 4.2: GOTO Step 9 Step 5: WHILE the condition i p2 p1==p2

p1+2 p1-p2 (if p1, p2 points to same array)

Illegal operations p1/p2

p1*p2

p1+p2

p1/5

Pointers and Arrays Arrays Array is used to store the similar data items in contiguous memory locations under single name. Array addressing is in the form of relative addressing. Compiler treats the subscript as a relative offset from the beginning of the array. Array subscripting notation is converted to pointer notation during compilation, so writing array subscripting expressions using pointer notation can save compile time. Pointers Pointer addressing is in the form of absolute addressing. Exact location of the elements can be accessed directly by assigning the starting location of the array to the pointer variable. The pointer variable is incremented to find the next element. ‰

C treats the name of the array as if it is a pointer to the first element. Thus, if v is an array, *pv is the same as v[0], *(pv+1) is the same as v[1], and so on.

Pointer pointing to an array Initialization To initialize a pointer variable, conventional array is declared and pointer variable can be made to point to the starting location of the array. Array elements are accessed using pointer variable.

Page 117 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

General Form: pointer_variable = &array_name [starting index]; OR pointer_variable = array_name; Example 15.14 int a[5] = {1,2,3, 4,5} ptr = a ;

, *ptr

, i ;

Æ similar to ptr = &a[0];

Assume that array starts at location 1000 &a[0] = 1000

a[0] = 1

ptr + 0 = 1000

*(ptr+0)

= 1

&a[1] = 1002

a[1] = 2

ptr + 1 = 1002

*(ptr+1)

= 2

&a[2] = 1004

a[2] = 3

ptr + 2 = 1004

*(ptr+2)

= 3

&a[3] = 1006

a[3] = 4

ptr + 3 = 1006

*(ptr+3)

= 4

&a[4] = 1008

a[4] = 5

ptr + 4 = 1008

*(ptr+4)

= 5

Accessing value Example 15.15 printf (“%d “,*(ptr+i)); printf (“%d “,*ptr); printf (“%d “,*(a+i));

Æ displays the a[i] value Æ displays the a[0] value Æ displays the a[i] value

Accessing address Example 15.16 printf (“%u “, (ptr+i));

Æ displays address of a(i)

Pointers and Multi Dimensional Arrays As the internal representation of a multi dimensional array is also linear, a pointer variable can point to an array of any dimension. The way in which the pointer variable used, varies according to the dimension. General Form: ptr_vble = &array_name [starting index1]…[starting indexn]; OR ptr_vble = array_name; Example 15.17 int a[2][2] = {1,2,3,4} ,

*ptr ;

ptr = &a[0][0] ; Assume that the array starts at location 1000 &a[0][0] = 1000

a[0][0] = 1

ptr+0 = 1000

*(ptr+0) = 1

&a[0][1] = 1002

a[0][1] = 2

ptr+1 = 1002

*(ptr+1) = 2

&a[1][0] = 1004

a[1][0] = 3

ptr+2 = 1004

*(ptr+2) = 3

&a[1][1] = 1006

a[1][1] = 4

ptr+3 = 1006

*(ptr+3) = 4

Page 118 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

If the pointer to the array is accessed with 2 subscripts, it results in a problem. For example, (p+0) + 1 Æ if it is used to represent 0th row and 1st column (p+1) + 0 Æ if it is used to represent 1st row and 0th column

and results in p+1.

So, multi dimensional arrays can be represented by pointer in the following two ways: ‰

Pointer to a group of arrays

‰

Array of pointers

Pointer to a group of arrays A two dimensional array, for example, is a collection of one dimensional array. Therefore, a twodimensional array is defined as a pointer to a group of one dimensional array and in the same way three dimensional arrays can be represented by a pointer to a group of two dimensional arrays. int a[3][2] can be represented by a pointer as follows: int (*p)[2] p is a pointer points to a set of one dimensional array, each with 2 elements. Note: First dimension need not be specified but the second dimension has to be specified. Here, a single pointer is used and it needs to know how many columns are there in a row. The following representations are used when a pointer is pointing to a 2D array: ‰

ptr+i

is a pointer to ith row.

‰

*(ptr+i)

refers to the entire row - actually a pointer to the first element in i th row.

‰

(*(ptr + i) +j) is a pointer to jth element in ith row

‰

*(*(ptr+i) + j)) refers to the content available in ith row, jth column

Accessing value Example 15.18 printf (“%d “,*(*(ptr + i) +j);

Æ displays the x(i,j) value

printf (“%d “,*(a[ i ] + j);

Æ displays the x(i,j) value

printf (“%d “,*(a + i)[ j ];

Æ displays the x(i,j) value

Example 15.19 main() { int i, j; int a[2][3]={1,2,3,4,5,6}; int *pa=&a[0][0]; for (i=0;irollnum, ptr->name, ptr->semester, ptr->avg); Self-Referential structures A structure containing a member that is a pointer to the same structure type is called selfreferential structures. It is used to build various kinds of linked data structures. Example 17.8 struct employee { char name[20]; char gender; float salary; struct employee *empptr;

Dynamic Memory Allocation Conventional arrays are static in nature, because size has to be mentioned in the declaration statement itself and fixed block of memory is reserved during the compilation. C supports dynamic memory allocation through the following functions: malloc(), calloc () , free() These functions provides the ability to reserve as much memory as may required during program execution, and then release this memory when it is no longer required. Thus, arrays can be represented in terms of pointers and an initial memory location can be allocated to pointer variable by means of this memory allocation functions. int *p; p = (int *) malloc ( 10 * sizeof(int)) ;

Page 130 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

The above program constructs will return memory block of 20 bytes, which can hold 10 integers. The starting address is pointed by the pointer ‘p’. A one dimensional dynamic array can be declared using pointers as follows: int *p; p = (int *) calloc (10, sizeof(int)); This will return 10 continuous memory blocks of 2 bytes each and initializes them to 0. This can be used to allocate space for arrays and structures. free(p) will release the memory pointed by a pointer variable ‘p’. free() will take a void pointer. Example 17.9: Program for adding two matrices using array of pointers void main() { int *a[3] , *b[3] , *c[3]; int i,j; for(i=0 ; i link; temp-> data = n; temp-> link = p; } return (p); } void printlist ( struct node *p ) { struct node *temp; temp = p; printf("The data values in the list are\n"); if(p!= NULL) Page 134 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

{ do { printf("%d\t",temp->data); temp=temp->link; } while (temp!= p); } else printf("The list is empty\n"); } void main() { int n; int x; struct node *start = NULL ; start = insert ( start, 1 ); start = insert ( start, 2); start = insert ( start, 3 ); start = insert ( start, 4 ); printf("The created list is\n"); printlist ( start ); getchar(); } Refer File Name: to obtain soft copy of the program code

How It Works: ‰

Declare a structure node with data as the one of the member and the link as the other member which is a pointer to same structure which will hold the address of next node.

‰

In the main program, declare a pointer variable start pointing to struct node and initialize to NULL.

‰

Call a function insert() and pass the start pointer and the value 1 as argument to the function.

‰

In the insert function,as it is first time, the start pointer will be NULL, so it will allocate memory and assign the value of data as 1 and the link pointing to the same pointer p.

‰

Then returns the pointer back.

‰

In the main program, again insert() function is called with the returned pointer from previous call and the value as 2.

‰

Now the start pointer is not NULL, so it goes to the else part and traverse the linked list till the last node.

‰

Then allocate memory and assign data as 2 and link pointing to the same pointer p.

‰

Then returns back the pointer.

Page 135 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

‰

Same is continued for next two insert function call.

‰

Now four data’s has been inserted in to the linked list.

‰

In the main program call the printlist() function to print all the data in the linked list.

‰

In the printlist() function, using do while loop traverse through the linked list and print all the values.

Summary ‰

Pointer is a variable which can hold the address of another variable.

‰

& operator is used to refer the address of a variable and * operator is used for dereferencing the pointer.

‰

Pointer can point to an array of any dimensions.

‰

There are two ways to represent multi dimensional arrays by means of pointers: o Single pointer points to set of arrays o Array of pointers

‰

Strings can easily be represented using pointer – Ragged arrays.

‰

malloc(), calloc() functions are used to allocate memory dynamically.

‰

free() function is used to de-allocate the memory.

Test your Understanding 1. State whether the following are true or false a. Pointer variable can only contain an address b. Address of the memory location can be assigned to ordinary variables c. Pointer can refer to the content of the memory location by & operator d. Size of the pointer variable is equivalent to the size of the data item it points. 2. What is the use of generic pointers? 3. What is the output of the following code? main() { int n[25]; n[0]=100; n[24]=200; printf("\n%d,%d", *n, *(n+24)+*(n+0) ); } 4. Given the following declaration: int a, *b = &a , **c = &b; What is the output of the following statements? a=4; **c=5; b = (int *)**c;

Page 136 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

5. What is the output of the following code? main( ) { char *str1=”abcd”; char str2[]=”abcd”; printf(“%d %d %d”, sizeof(str1),sizeof(str2), sizeof(“abcd”)); } 6. Differentiate malloc() , calloc(). Answers: 1. True, false, false, false 2. Generic pointers (void pointers) can point to data items of any type. 3. 100, 300 4. The first statement assigns 4 to a. The second statement assigns 5 to the location pointed to by the location pointed to by c. Since c points to b, this is same as assigning 5 to the location pointed to by b. Since b points to a, this statement is equivalent to assigning 5 to a. The third statement castes **c, which is value of a, into type int *, assign the value to a. The result is meaningless, because values cannot be assigned to pointers. 5. 2 5 5 6. malloc(), calloc() will both allocate the memory dynamically, but the difference is calloc() will return a contiguous memory location and initializes it to 0.

Page 137 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Syntax Summary Program Structure/Functions type fnc(type1,: : : ) type name main() { declarations statements }

function declarations external variable declarations main routine local variable declarations

type fnc(arg1,: : : ) { declarations statements return value; }

function definition local variable declarations

/* */

comments

main(int argc, char *argv[])

main with args

exit(arg)

terminate execution

C Preprocessor #include

include library file

#include "filename"

include user file

#define

name text replacement text

#define name(var)

text replacement macro Example. #define max(A,B) ((A)>(B) ? (A) : (B))

#undef name

undefine

#

quoted string in replace

##

concatenate args and rescan

#if, #else, #elif, #endif

conditional execution

#ifdef, #ifndef

is name defined, not defined?

name defined?

defined(name)

line continuation char

\

Page 138 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Data Types/Declarations character (1 byte)

char

integer

int

float (single precision)

float

float (double precision)

double

short (16 bit integer)

short

long (32 bit integer)

long

positive and negative

signed

only positive

unsigned

pointer to int, float

*int, *float

enumeration constant

enum

constant (unchanging) value

const

declare external variable

extern

register variable

register

local to source file

static

no value

void

structure

struct

create name by data type t

typedef typename

size of an object (type is size_t)

sizeof object

size of a data type (type is size_t)

sizeof(type name)

Initialization initialize variable

type name=value

initialize array

type name[]={value1,: : : }

initialize char string

char name[]="string"

Constants long (suffix)

L or l

float (suffix)

F or f

exponential form

e

octal (prefix zero)

0

hexadecimal (prefix zero-ex)

0x or 0X

character constant (char, octal, hex)

‘a’, ‘\ooo’, ‘\xhh’

newline, cr, tab, backspace

\n, \r, \t, \b

special characters

\\, \?, \, \"

string constant (ends with \0)

"abc: : : de"

Page 139 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Pointers, Arrays & Structures declare pointer to type

type *name

declare function returning pointer to type type

*f()

declare pointer to function returning type type

(*pf)()

generic pointer type

void *

null pointer

NULL

object pointed to by pointer

*pointer

address of object name

&name

array

name[dim]

multi-dim array

name[dim1][dim2]….

Structures struct tag { declarations };

structure template declaration of members

struct tag name

create structure

name.member

member of structure from template

pointer -> member Ex. (*p).x and p->x are the same

member of pointed to structure

union

single value, multiple type structure

member : b

bit field with b bits

Operators (grouped by precedence) structure member operator

name.member

structure pointer

pointer->member

increment, decrement

++, --

plus, minus, logical not, bitwise not

+, -, !, ~

indirection via pointer, address of object

*pointer, &name

cast expression to type

(type) expr

size of an object

sizeof

multiply, divide, modulus (remainder)

*, /, %

add, subtract

+, -

left, right shift [bit ops]



comparisons

>, >=,
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF