Docsity

C Programming: Arrays and Strings, Slides of Computer Programming

Partial preview of the text

Download C Programming: Arrays and Strings and more Slides Computer Programming in PDF only on Docsity!

Dr. Hanif Durad^

2

Lecture Outline  Short-Cut Assignments  Postfix Increment and Decrement  Prefix Increment and Decrement  Arrays  One Dimensional  Multidimensional Arrays  Strings in C  String input and output function

Short-Cut Assignments^ a += b;

D:\C\CSCI-1190\ lecture-4.ppt, P-2 a = a + b;a -= b; a = a – b;a *= b; a = a * b;a /= b; a = a / b;a %= b; a = a % b;

Postfix Increment and Decrement  Postfix increment and decrement operatorsreturn the original value of the variable,then increment or decrement the variable.^ int a,b;a = b = 10;printf("%d\n",a++);

printf("%d\n",a);

printf("%d\n",b--);

printf("%d\n",b); postfix.c^ /* 9 */

Prefix Increment and Decrement  Prefix increment and decrement operatorsincrement or decrement the variable, thenreturn its resulting value.^ int a,b;a = b = 10;printf("%d\n",++a);

printf("%d\n",a);

printf("%d\n",--b);

printf("%d\n",b);

Using Arrays  There are no built-in operators for arrays^ int i,a[5],b[5],c[5];a=1;^

/* error */ b=2;^

/* error */ for(i=0;i<5;i++){ a[i]=1; b[i]=2; }

/* ok */ c=a+b;^

/* error */ for(i=0;i<5;i++)c[i]=a[i]+b[i];

/* ok */

Array Indices  Indices must be integers^ int i,j,a[10];float r=1.0;a[-1]=1;^

/* error */ a[10]=1;^

/* error */ a[15]=1;^

/* error */ a[r]=1;^

/* error */ j=r;^

/* j=1 */ a[j]=1;^

/* okay */

Multidimensional Arrays

D:\C\Hanif Search\C.tn.pdf

Array Traversals (examples)

Dr. Hanif Durad^

12

  • In-Class Exercise 4-1  Generate 10000 floating point random numbers between 0and 1. Divide the range [0,1] into 20 intervals with width0.05. The first interval is [0,0.05], the second is[0.05,0.10], ..., the last is [0.95,1.00]. Show the number ofvisits to each interval. The output of you program shouldlook like:0.000000-0.050000: 5010.050000-0.100000: 4630.100000-0.150000: 476...0.900000-0.950000: 4660.950000-1.000000:

Strings in C

Example -1#includevoid main (void ){ char *st1 = "abcd";char st2[] = "efgh";printf( "%s\n", st1);printf( "%s\n", st2);}

Dr. Hanif Durad^

17 string1.c

Example-2void main(void){char myname[] = { ‘H', ‘a', ‘n', ‘i', ‘f' };printf("%s \n",myname);}

Dr. Hanif Durad^

18 string2.c

Example-3#include <stdio.h># include <string.h>void main ( ){ char myname [40];printf ("Type your Name :");gets (myname);printf ("Your name is :");puts(myname);}

Dr. Hanif Durad^

20 string3.c

Some String Functions:

Dr. Hanif Durad^

21

Function^

Description strcpy(string1, string2)

Copy string2 into string strcat(string1, string2)^

Concatenate string2 onto the end of string length = strlen(string)^

Get the length of a string strcmp(string1,string2)

Return 0 if string1 equals string2, otherwisenonzero strchr(string1, chr);^

will find the first matching character in a string