0% found this document useful (0 votes)
9 views

CSC 102

With questions

Uploaded by

midn4150
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views

CSC 102

With questions

Uploaded by

midn4150
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 37
Auer _— ry 1 Mh iota ced WB. sie was yntroduced 5 oH VISE AL gant vac dates back 10 yoo! when V8 SORT a world leading The History of Visa ee «owe, was develope’ PY mic ny language! is an modern orange VB (an event-driven prvel’ nian BASIC _ Beetnners All actly are oa aL BASIC Visual Basic was denved ihe Mid 19605 af ‘ aerinym for VIS ‘enon Code (which Was developed © 1d application 4 purpose Sembolic IRSIPMCl TN ace of VB in 1991, enables the TAP jo data bases | . ea ; $8 10 a) ich al user interface GUT) application, 265°" 3s the graphica atures Visual Basic Was develop ; see oh a -and-drop interface hee ol Basic Net, Alan Cooper had developed a drag-am Pp si -ompany, Tripod, to inthe late-19R0s, Microsoft approached him and = a vevioped the project developed the concept inio a form building applicalio’ amming language al for Microsoft. It was called Ruby and it did not include @ progra j creating all, Microsoft decided to bundle it with the BASIC programming ange S miaiaini ‘Visual Basic. Ruby also provided the ability to load dynamic link libraries tom additional controls (then called ‘gizmos’, which later become the VBX interface. Visual Basic is a fast and easy way to create programms for Microsoft Windows Visual Basic is a language well suited for scientific and engineering calculations as it provides facilities for mathematical problem which can be stated, compiled and ‘executed on many kinds of computers. Today, many people in science and engineering use the VISUAL BASIC programming language as their primary method of communicating with a computer. with other interest def History of Visual Basic (1.0 to 6.0) Visual Basic 1.0 for Windows was released in May 1991 at a trade show in Atlanta, Georgia. Visual Basic 2.0 was released in November 1992, The programming environment was easier to use, and its speed was improved. Notably, forms became core objects, thus laying the foundational concepts of class modules as were later offered in Vb4 Visual basic 3.0 was released in 1993 and came in Standard and Professional versions. WB3 included version 1.1 of the Microsoft Jet Database Engine that could read and write Jet (or Access) Ix databases, Visual Basic 4.0 was released in August 1995. It was the first version that could create 32-bit as well as 16-bit Windows programs. It also introduced the ability to write non- GUI! classes in Visual Basic. While previous versions of Visual Basic had used VBX. _ controls, Visual Basic now used OLE controls (with files names ending in .ocx) instead, These were later to be named ActiveX controls. ‘With version 5.0 relcasc in February 1997, Microsoft released Visual Basic 2 _ metusively tor 32-bit versions of Windows. Programmers who preferred to write fh . +, (bit programs were able to import programs writien in Visual Basic 4.0 to Visual Basic” $0, and Viswal Basic 5.0 programs could easily be converted with Visual Basig 4.0. ” “Vicual Besic 5.0 alsa introduced the ability to create eustom user controls, as pathad Ns the ability yo compile to native Windows e¢xtcutable code, speed: Set Mf ecution A ton, dowtleadahic Coral Coosin Earn cnen 9%" peloased fay crantion of ActiveX. contols, Miata eased mad 98 moved ina ‘hyp cxeutn rth-bosed applicetices. VB hes bean the ee a ? Edncm-weeabe ¢ hy ‘rmuad Basic, Fhe ihe ranvine SUpNArteg Altho devel pment ens renmen . sani oes esr enivinnte ve Pera Server 204% ani WinidOWS Marnstrean Supporter 5. a sous. Exrended supportended in Marsh 2008 In Rsconatl bt Dende ee ee 4 Aaaaceeancem and lohbred axevgt response, the Visual Basic user community expr ivecunce . wo ngna Perna valerp ine productalive. Microisofl has s0 tarrefused to change ther 1 position on the matter. ‘ Brief History of Visual Basic NET (7.0 to 9.0) : Visual Basic NET 1s Microsof's designated successor to VB 6.0. and is part of . Microsoit’s NET platform. It compiles and runs using the NET Framework and ts 4 not hackwards compatible with VB 6.0. An automated conversion tool exists, bul for most projects automated conversion is impossible. Visual Basic NET 1s designed to create NET” applications, Windows or Web applications, and Web Services Visual Basic NET 2003 was released in April 2003. Microsoft re-engineered Visual > Basic from the ground up, including full object-based programming facilites and” complete integration with the NET Framework Common Language Runtime (CLR) This release became the first version in the history of visual basic to provide programming tools for Pocket PCs and other mobile devices, it also had better XML features and support for Windows Server 2003 5 In 2005, Microsoft released Visual Studio 2005, which included Visual Basic 8.0 and = the NET Framework 2.0. Visual Basic 2005 is the name used to refer to this update af Microsofi decided to drop the .NET portion of the title. The new features included Design-time expression evaluation, My pseudo- namespace, dynamically generated "? chases and Data Source binding for easier database clientiserver development. These ancements were mainly intende J to reinforce VB's focus as a rapid application development platform and further differentiate it from C# In 2005, Microsofi also launched the Visual Basic 2005 Ex, ) asic 2 Press as part of the Vii Studio Express product range, The Express editions are free development ical fog é astreamlined version of the user interface, and lack more advanced features of the * standard versions. Microsoft created these for students, hobbyists and novices. This x was a milestone event in the his! i i ws uniletone in the history of visual basic as it was the first time VB becartf ln 2008, Microsoft launched Visual Studio 2008 inc : r luding VB 9, Ranewote ae Visual Basic 2008 as it is known, incindey features Whe esol types ree ot LING, Le correaions and XML literals. In 2008. Micsorat « ola ria sued He 2008 Express as an updated version of Visual Bat (im: a i. like Highlighting References and ImelliSense Suggestion Mo ' id Thowhi-out the History of Visual Basie the focus has always been on Rapi Application Development and that’s what makes Visual Basic such a widely used programming environment. haus, we have Year 199T Visual Basie 1 i ral Basie 1992 \ wal Basic | 193 4 Wistil Basie 4 1995, 3 50 1997 & ic Bl 1998 7 i) 2008 8 ie U.Ah 2010 ADVAN TAGESSTRENGTHS OF VISUAL, BASIC: Jtatlows the user to cteate nice locki eoding, unlike nian o eraphical programs with ease and a little jages thai may take many lines of programmer cks requite eventilnven proges language. crally nin ease sensitiy exceptsiring comparism thats case sensitive isitnge and by this, the exccution of the overhead which atfect its level of efficiency, Hee eablex tuader programming technique and litle is being done to Airy dhe Visual Basio environment sinee it has been largely superseded by VISUAL BASIC.NET and other languages, 1. inherited some of the BASIC ATARACTERISHICRS ne ASSIFICATION OF ALGORITHM: buna METHODS OF REPRESENTING ALGORITHM: WARY LATTER PR LGORITHMS: _ és algorithm must have a finite sct or sequence of Sea action Sequence of action in an algorithm, must have an ini oes A stinating a pice MUSt be a nique successor to each action in the sequenc®, constituting an algorithm ; i ti There is always the need to have the algorithm defined on a general basis rather than] na specific problem solution. : the proble The sequence terminates with either a solution of a statement that the p Mm can or | cannot be solved. gorithm may be classified into four ways, ic By Implementation By Design Paradigm By Field of Study By Complexity, Algorithm can be represented or ex; pressed in different ways. They include Natural Languages: Flowcharts Pseudo codes Data flow diagram (DED) Decision Tables. Natural Languages: IL is important to note that Natural language expressions of algorithms tend tobe verbose and ambiguous and are therefore rarely used for complex or technical } gorithms. It is for this reason that the Flowcharts, Pseudo code and Dec ion, pref structured ways to express algorithms that avoid mai if the guittes common in natural language statements, while remaining independent 4 particular implementation language Furthermore, programming languages are pr imarily intended for expressing i algorithms in a form that can be executed by a computer, but are often used as a way’ to define or document algorithms Meanwhile, the three most important modeling techniques used in analyzing and building information systems are Data Flow Diagrams (DFDs) , Logical Data Structure Modeling (LDS) and Entity Life Histories (ELH). FLOWCHART: By definition, FLOWCHART is the pictorial or gra hhical representation of an ALGORITHM ee meen But to some programers or system developer, FLOWCHART is an ALGORITHM that uses some kinds of special symbols to represent activity at any level fora 4 .°§ Particular form of operation, Nin (vou ggg an ‘Types Classification of Flowehart: FLOWCHART cai be ‘secing to be of two types: 1 Program FLOWCHART System FLOWCLART. Program FLOWCHART: that Mere, « graphical representation tool that provides-excellent pictorial panes adily deptet procedural detail is used Some symbols for memory refreshing includes: mbols | Name LF hive Useg/Deseription Example e/Process) Use for processing | i, [Area L*B of assignment 0 (Oval object Terminator) | Use to stan ginning) or End (stop) of a 0 pevgram FLOWCHART| - (On page connection) — | Use 16 show the C ‘ continuation ofa FLOWCHART on the same page. ” Use for continuation 4 <7 | comtprge conmsction | Se FLOWCHART on another page 5 Z| (Paraltelogram) or Use for data input or | 1. Input/Output Output operations tests and decision Pre-defined process Use for calling up/ oe | coke eee ‘defined routines rogram that will ‘assist us in our present task 6. [ | Desisiowpiamond Use to indicate logical a DENT U —beeibsseripin amie Ditwetional Arows | Use 10 comet eymbols | andin of low To be treated in es the diteetion| Nowchaet agra —— fs Gl rp thas for represent an FLOW CHART. These pictorial methods inchide: [a CHART, and DECISION TABLE Nole thal Program FLOWCHART niay bo suhliv ited into) low other the wh CHART, GRID (2) Micro FLOWCHART and (b}, Masso FLOWCHART, \ The Mictn FLOWCHART iNest wep alll lon oF ORAS aT AG is the Macro FLOWCHARI alses only gensaloulline of the procodane a given probl \ 2. Systems FLOWCHART aan FLOWCLART system FLOWCHART) equally wse-symboly o Tepresent sctivities tu be tmiplemented at any level, This ALGORITHM Is used stom analysis or dava collection level nith sysiem FLOWEMARL mmelude 1 . this involves eer aN eR A a} of ene or ace specie Sots of ems from a fie or < \ pay c - Puncbed Cord Magne sk Delay “ 6 Cm 88 PSEUDO CODE rhe ways through which a progeammet cat Se aes IEG gu cmp, sudo oe sed rT rhe rb si lent of ogran Sige aN ete cde is aot meant tbs compiled or exe “Peeudo used mph lows one lo convey basic SCS genet il eb conpler ropa! Tees aeamming key words) and English te phases tears cede tans ow of Foie Geneeal Eenispter Question f . sy age and tls tes Develop a pseudo code for the ALGORITTIM that accepts user's age thre ts tle midi not states how many MOTE years will ke for him to be cline. [Assume te lel voting age fs Band above} Step]. Algorithm start Siep2 Geluser's age Sip, Mage>~ 18 Then Step Display "You are eligible” Sips Else Step 6 Process: difference «= 1-age Stop 7, Display difference +" more years to ga!" Sepa. Edit Seep. Algorithm step Question 2: Develop a preudo (algorithm) code that adds up 30 numbers and find the average. ‘Also draw the FLOWCHART, Working: ‘Stop 1: Sct up a counter which counts the number of times a mamber is added Step 2: Setsum to accumulate to zero Step 3: Input the frst value Step 4: Increment the aecumtlator Step §: _Inerement the counier by 1 . Make a decision Le check how many times you have added up the ‘nuraber and see if tis the required namber of times Compute the average of the umber ‘ Print the average Algorithm Step Develop a pseudo code forthe al concentric esces thom the wser lord for» program that tceives thera of em / ‘nd for each computes and displays the ated and the Sireumference. Hint: =m; Cireuterenes Algorithm stant Set pito 3.442 Set counter to 10 Get a value into radius Compute pi * radius * 2, store in ae Compute 2 * pi * raging, store in cxcumfarence Display arca Display cincumference Decrement coumer by 5 9 Weounter~tthen go ta & VL Algorithm siop Question &: ‘Draw a flowehart for the algerithm fora program that aecspls ausct’s ape and tel he eligible o vole and eS haw twSty toce Yeats wil take For hin eh ‘eligible, {Tlints Assume the legal sling age is LR aad above) Workings 1 Alpenth Get user's fr start ee == 1E Then Display “You ar Vee Process: diftere Display uiflerzne + "mone years Endif ‘Algorithm. sop See Diagram for flow RTE ; TOUESTIONS: 2 F FRAMINATION OUES! a: ww do wo onsver oF 100 Questia he flowing pseudoe™ gorihan start net Get ita the second value oe Ca eel 2 an sto ul a Jo cam by 2 aed store eesti Display sum Daplay average . got stop saat ite feehan symbol can be weed to representa 1 — Oi neade = —~ operation. {il Sep S}is regarded ae =o Hiorbinegt 1 duswer= : : {ih Stemtes as sspardod as Ougput (Ii), Step (5) is regarded as Assigmment Question 2 ‘ne ofthese is nota way to represent an algorithm A. Flowchart B. Pseudocode Chesson table B. Dataflow digeram E. Recursion Working: Option B ls Correct (Answer = Recursiom) Onestion 3 A flowcharr can be classitied as: A, System Mowchart and program flowchart B. Terminal C. Reuse D, Briefiness E, None Opifan A is correct (Le Anamer = System flowchart and program flowehart) Qvestian 4) vy be subdhvided imo A. Mini and mica flowchart B. Micro and macra Newehat sida ©. Mainframe and mini flowchart DD. Pseudo code and micro Workings UH Option 8 is carrect (Answer = Misra and macro flowchart) ‘Question &: Drow a flowehart forthe algorithm for a program | the sume and aversge of twee ve aig dvohct} alee peoraa, arese of values {say vee! and wae?) entered be eke user ofthe Workings Get the First value into value! Get the second value in Add value! to value2 and steré result in som Divide sum by 2 and store inaverage Display sum 4. DATA FLOW DIAGRAM. Data flow diagrams (DED) is chart that eaces the movement om and shows how the data is be processed, This defi 1 ako go for sich let Bubble diagram Processed model Business provess model or Work ow dag er Fancoual mode ata ow dig ci also be Ses 3 a rahi epiesenution af he ow of thr veh an ink up valinn system, Again, Data flow diagram can a be used for the Conteat-leve! DED st, which shows the raion between the syste and O98 5, DECISION TABLE Decision able ne composed of rows andeoluenns, separated into four seme (lu- soo a TTAOnSDS Or sing JoRrETjon of he conditions Vo te ves that should be (2 jon table forms onic of a portion oF Toon gpeening ie 05 OOP od of eo same provessing SUPT ose ents Sup qecron table used a cle eis shown Do} Me cone wel of a decision tat Decisin Rule _____——— ‘Condiion bninies Condition Consiton Su ‘Action Subs} ¢ Fig. A: The Decision Table Matrix Decision tible has a standardized format and is composed of four (4) main sections. Condition Stub Fearne of all possible conditions that could apply to a particular problem. ition Entry: rntuats the different combinations of the conditions; each combination being rule Action Stubs This section contains lst of possible actions that could apply for any any given. combination af conditions, Action Entry: 1s tobe taken for each combination of conditions. Methods of Preparation Lis the conan inte condtgn stub Work ol he pose nb af eambintons of condition 92%, where ie the number of conditions. This will give the number of rules. . - Rep sae comps in he condton ny Seton fr the umber ‘When ent" othe combinations must be nique When" oe cominons must be uiqu (noo ols mst ics api to each owe of eonation Enter the actions to be taken in the action stub. Sof condtion le Follow down each rule and mark the appropriete action to be taken, Aovantge of esison Tae Adelson ibe ts standard fomat Condon nds set of atone ae A decision table is concerned wi cl problem ented for problem definition in which each set of arly and unambiguously identified. ith the logic of decision rules and is, therefore, There is tinte at program based on a decision ible will have Incomplete oy inconsistent logic, since the stricture ofa decision table promotes oeleally ‘completed and consistent problem definition Decision table facilitate checking for redundancies and contaieons “The format of decision tables facilitates expansion, cosration or revision Of Tope. Decision tables are an effective means of communication between members of the system development team, users and managers Disadvantage of Decision Table: Decision table should not be used ifthe n the order of conditions is important and therefore it condition is given by the order of column sles do not share many condilvons. Again, a decision thle, the ordet ofa Application Areas Of Decision Table 1, Business Analysis 2. Programming, 4, Hardware Design ete 3. Testing Example: es fteorin UNIZK advitingnew students segue to camo wh Ann Nm Jah sue 250 oF moread has NE ei flowing po: Ay placed emt i nd sy stat wah 1AM Se inrleant ube a ev rin eee suet ahold be pers ite a ine enerstances should be eer 19H int uta decison ale present Ie 2bove Workings: Epis situation, we have tree conditions, which es a JAMB score of 250 or more b. JAMB score in herange 200-249 f. Salisfactory credit in relevant subject & eefore, ts number of alos whichis given by 7° where. ihe mune oF ‘conditions becomes: Number of Rules = 2" 5 Number of Rules = 2 Number of Rules = & therefore. the decision table becomes: Rules | Conditions _ 1] 2] a} als ‘AMD scoeotS0ormore —[y{ [vy | y [TN ‘AMU score inthe range200-20[¥ | ¥ [NTN | Y Satisfactory credit? YEN PY, NT YI ‘Actions | Pree om Wirt List ¥ Place on Second List x Refer to Register X n COMPUTER PROGRAM: t, 18 cally related instructions that ‘examples of the dents grade point ram isa sequence of log ° mn problem. Typically Ty definition, A computer Pr fer programs ares StU pater on how to solve & Vel Grects the computer on how (01 : Galen the computer can solve sing ComPU verage, university payroll ct PROGRAMMING LANGUAGES: There are twa (2) eategorics of programming languaess Nd caene a that ceals with the same sort of objects et ee Languages: have ave anginees how Level Languages os er assed ino the Machine language andthe Assembly Fane inguaiges or problem oriented languages ). THigh-level language (General purpos The machine language. This isthe only language the computer can cun without modification, I¢ usually nus at fone sequences of binary digits that haye meaning fo the computer and hector wising a complex progeam in such a language can be very cumbersome with deadant sity oF arom Ne recall that when the Brst generation computers were invaded. joprans were writen only in binary based machine level tangy language as it was dhe only hncuape understood by Ge computer. ft is machine dependant, that sans ns opts move town nique nseucions (a maine language program yiriven fr ane ype of computer cannot be run on another type of cor twine sigiicant alterations), Also, iis not portable ‘SPrORonR The Assembiy Languages: Te asl languages ake use of nemo ( ype sthetvninacion Asnbly ngage secre oie {lp sie aor (alle ah ASSEMBLER) conver into amachine a ill ache dependant and lak portabiiy, S High-evel Languages, Ths ao rele sa Seneral Piopose guiness he ast mpatible with human kang es bX rocesses, Nowa onset a gigs and ne aug ces Noli selec ah el ngs wl be van! seve atts fact lambing and a program writicn in a high4tevel language can. si Suecimyahiapus ecenptete meanest ae “sar The heh fining weedeat te pclems soe iho agnope (chine ange the sony snzige hs canbonomexs anne coms oh of is Sn vey auionnt adverts oe Boo ok machine language- For sim epee Seo Seley, Uniformity ard portability (ts not machine ; high level Purpose Symbolic instruction Cade). ADS. EORTC eg eee fa Soll nstcton Cole), ADA, FORTRAN ‘Fomularaniaton Sal CONDE (Connon Busines Oren angsnes env, Vina 1¢ hig] ic Language), Al 3 x? 1 Structore Progranmiig and Object Oriented Pragestining (OOP) Structured Programming: Struc: i saraming) isa technique tor organizing and ich a hirarshy of modules is used each Raving 9 sil point. Some examples of structured prngram wshide: PASCAL, ADA, DBASE. ALGOL 68 and PLIt ele languages ‘Object Oriented Programming (OOP): ‘An object Onented Prograt snrganized around ning (OOP) is a programming language model beet rather than aetions andi daca cather than logic. Ohiéct Oriented language is any kind of progeamen 4 programming langage ‘with some object oriented consuls ur prey sect prneipies ave fullowed PHP, VB.NET, Cs, C++, RUBY ete SOURCE PROGRAM: A souree prog Because the comput suuree progesii requires a sranslator i convert or tanslate the source program, into the machine language version before the camputer ean execise the instructions, comamned in the program, There aze twa types of TRANSLATORS, n and the Interpreter Tat the ‘THE COMPILER 8 program that n, called the "SOURCE C EA The the programmer's procedural alec the st cade tc ther Be saved und run later Examples of procedural linguagss that use compile ASCHAL, COROL and FORIRAN, ‘mies machine language cov THE INTERPRETER: An interpreser is program that conven te procedural lana Progran ene sestement at time, into an hime code just before No object code ix saved in this case, An evtenple ofa that uses an inlerpcter is the standaed version of | executed, of procedural lunguage BASIC. DON'T FORGET, ‘Any prograrn that is wsiten in « High-fevel hi into machine languag, anguaye must however be translated 2 : 11 Can be executed peogtan ae a nePtCT is self a computer program that accepts a high-level thogly, the original high-level program iscalled the SOURCE < “ Mf Te OBIECT rogram 18 cf PI ne maine men % PROGRAM ane ie PROGRAM. 4 that is-Wen a2 use every day: ari un ae at eh ‘Note that Visual Baste " rds known, « different types 01 £ of wor tone speak or write, One me Basic also has ditferent Opes to write P oe sca tet. ae os PRO in ; Panga! S sic incl : ip cleients in Visual Basic 10 varaming ele sverarors, keywords ana conmnens / [11 MAJOR COMPONE INTERFACE W THE 11 Form Designer . |__ Solution Explorer Toolbox Properties ‘Window ‘The Companients of the VB IDE are; Fora Designer: this is he window that houses the VB form, initially titled Fornel A form represents 4 window in the appl ion you are creating and houses the ‘controls-texthoxes, commeamd Buttons, fabeds ete-that provide the user interface, The écsigmer window can manage as many forms as you feel your program requires. (Code window this is tke text editor that is allached to the VB IDE. When it is used { edit tent itis referred to as the Text Editor. However, when used to edit source ‘code itt VB application development-its most common use-it is referred to a8 the Corde E : Solution Explorer files. Whesev : ts ple rogeets 1 OO op ese conte £0 Vis. you cin drag-and sche curenly setected For, ify ieformation jon. Each forin Properties Window: this displays tke im Design vie. With controle and details fr consol such a8 uot has is cwvn sot of properties ad 2 potion ofthe Properties Window whenevst VISUALBASIC CONSTANTS: Visual Basie constants ae numbers within 2 Pr VISUAL BASIC being mathematic Were Thi numibers ean be several sie p involved am whose vaes do 08 Change rakes great use an the types of TYPES OF VISUAL BASIC CONSTANTS: TPES OF ai types VISUAL BASIC CONSTANT 1. Numeric constant String coma aver constanis (I) Comple sesans (HN) Le constants 1. Numeric Constants: eens constants cat fartec be divided into a eammeeSettm Real Consans (1) Arba cms Aaj _tevegee Constant: Integer Contant are pene oF RESINE NTS nibers writen aivtean dial points and coramas, Examples re aid Igeger Constants ie 00 cna point not (uy. Reat Constants: Real Constants are those aunbers with a decal poin and with ea tone bal no comms, nd may cir be postive oF negative name Examples a any, we sign okay andl spate permitted te ual values must be set fomnenas and AC Teia0s.o | Es einvaors con be tenet al MONTE precision oF a J Aravmetic constant #8. Arithmetic Constants: Ariimesc ev unsigne sea arithmetic constant 18 Meena, Hea b rapes const erie of speci! siving Cointantse These ne constants tha anpriscs of alphanueneric 0° SP serine Comet inion mah. Exams SO 172014" HT RHICS™ ily “ABCD” (OV). "BENSON" ISUAL BASIC VARIABLES: ‘variables 2 val connputer to store in its memory while the program 'S rene vaste e program asa tite sbeel you may dese Ut will ang, Wha Sn ox and He salary in anther box; then anovhe Oo will yin ya ace desig the prorat, you carne pretict ih Jee enple ho wl be using the program and you definitely cane) He a re ill ge week afer weck, What you have 9 do i ask the aa ae rary storage areas that one user can use white the Drograin if aa oe tay be uve to sure a sary, when another user is using the SIM a jel box soul be ready to eosive new inputs, new salary For ak otner wr compute memory is made of sll storage ares use told the things that» a ‘Ava programmer, you specify these things, oF you pride Th cemputer then puts them in these storage areas. Ne you nea one of tem, you Tetthe computer know, The machine Jocated it and rakes i avaiable to you to use as you see it ie Naming Of Variables: There ate es you sm nd sly ast Flow when naming your variables. Must bogin with a letter words the period is an operator) : ipod aay SPIES Can be ess than 255 characters ak ” Must be unique inside fe pracedure or the mori itis used in o spacing is allowed Once avaiable ha a mane, you can use itas you soe Fat example, yo can i€8 Value and thon use he variable in yor program 28 if repeesened nt yale Storing Information In Variables: To store information in variable, we have three major steps; they are Deelate the variable (Il), Assign the variable (ITI), Use the variable Declaring Variables In VIL.NET, a variable is declared using the Dim (short for Dimension) keywords, Here is the syntus, ) and As Dim varName As varlype ‘Where varName is the name of'your vasiable ‘arType is the data type: ofthe variable Data lypes include string integer, double, Boolen ete. For exanipte, to declare integer name My Int use: arcan my Dim Myint As inieger Assigning Variables: You assign a value to your variable with ~ sien, wh assignment operator. Fete is un example this semetijes called the This ine of code takes the value 38 undl stoves (Lin the p y declared variable named aNumber, Introduction to Data Types: ‘When you decide to se a variable, you certain amount of space to hold that varia for differemt purposes, you showld specify the kind ef wariable yaw intend tes use, tet the computer will figure out how much space is needed for a particular Each variable you use will utilize a certain amount wf space in the & asking the-comp Since uifferest variables al Before declaring or using a variable, fist decide what kind of role that variable will hy in your progeam. Different variables are meant for difsieat situations. The kind ‘of twiable you want to use is oferred to asa data type. To specify the kind of ‘aable you want to use, you iype the AS keyword an the right side of the variables ‘ale The formula to declave such a variable is joose the appropriate daa sed hi cet imbers, characters, oF other rable you ind ovis YO Once you know ee nized in cate8 7 ype. Dale Iypesare orsani objects 1 BASIC Data Types: sects int 2 et which can be computed mathematica Wy and divide etc, The | numbersfreal numbers) Csstcaton of VISUAL BASIC Cay, Va ae Dates te er se com of mambots which Ct Namerle Dar Or operas suchas a, minus mull ye neg Double eet iis consists on non stumerie string values. Examples are. nerie Dats Eye yolean, Object, Variant (numerie/text) Non Date siting (faxed length or variable bength), Bo Cha Literati: these are vulues we can assign to adata, Fxamples of literals are Lang, Sinpie, Double, Currency, ie Data type: this are deta type that comprises of more than one data type. Com a xan Brief Explanation on Some af the Data type Strings A string isan empty tent letler,» word ora group of words considered, Example, ()."1 preter mustours to mest” (ID) “Congeanulatinn, you score 82 out of 96" (ILD, so nppsrenily unineligibte eoenination such as "($e ( Declaration OF a String, Variable: Tu declires string variable, use the String data type. Here isan example: Private Sub Form Losd ) Dim Cauniry Same As Sizing Enid Sub Asice declaring the variabls, you can initialize, If you want its area of tuemory to be ‘emply, you saa assign i (wo double-quotes. Here is an example: Private Su Fem Load) Dim Country ame As Siting CouniryName =" ind Sub If yu want to store something in the memory space allocated to the variable, assign it sword oF group of words included between double-quotes. Here isan example: Private Sub Form Load) » Countey ame Great Brian” End Sub ‘You ean also initialize a suing variable with anoth Vail. Concatenating Strings with Ampersand (&): Generally. we use the ampersuna(&) characte’ #9 Strings into a new swing. as shown belo sully cutibane 0 OF mote Dim rString. As Sing = "*Actass the Operr Dim yString As String -"Titigaase Dimm eSiring A Sing = eString = Seng & y5inng The above example: 4 Aeioss lanes three Scrng vari a the Open" to tl Tat do you Then fs assigns wo lear iat the value is Acros think the value VF esinng ot the beginning the Open But if you m a 10 ad spaces « wost-such ag ~ Din eSecing, S084 2 Boolean: ; oo Ta declare A Roulean tanable is ene so bw only ens sucha sariableuse the Boek Brvate Sub Fons adh Dada Mbarried As Bool Yd Sub Alter declan Fan pt ether True 20 Tete seam example Prvate Sah Fern Lerait) i: Dou IyMannea As Bowlean IsMaried End Sab Vake a Like any other variable atte 7 ne saris: it heap its value wand yg change its value again, u ‘Numeric Data Types: 4 Insrodvction ‘ nasural number |s oe that contains only one digit or a combination of digits amd ng other characte, yeep those aed to make i easier t read. Examples of natural frumbers are 122.8, and 2664347, When a netural nuanber is to long. such 3253734343, co make it easier to read, the thausands are scparated by a special character This characte depends on the language or group of language and itis called she thousands sepuraor. For US English, this characte i ube comuna The theaand Ssparsiot symbol is mainly used onl fo make the number casier to read. {To sippor ditlerentseenanos, Microsofi provides diferent types of natural mumben Byte A bytes small natural positive muitiber dha ran ‘ype Sun be used to hold «mall values such as snail, ete Tosieciate avaiable es from O to 255..A variable of byte erion's age, the number of fingers on fora sivail number, use the Byte Aespword, Here is an example: = Is. narural numer Tanser than the! #8 and 32.76% Examples ofeach eanpes: Byte. can hold a value betwen To deviate. variable of iy integer tse Ue re: the muriber of pages of a hook, integer keyword, Hete is an example: Peixate Sub Forn_Load) Dirm MusicTiacks.as Integer Eng sub Long tnieger hy 07 isa natural nam iad Taam senbe thoks a beeen 2147-9. and 285.682 Examples ae the population ofa citys the silirencounincs the numberof ody of «book, Sane Between places af fo declare a vara i uc tha an fo avery ange natura numb use the ots i830 example: eywond, Priviie Sub Form Load) Din topwion Neb Fad Sub “ Piccinval Data Types: ade RENIN 1S NO scan fol st eta ype Hee ina Load Font Fran counteyNane As ST Pom antared 8 Ba reel mAs Long, arn Dian Distance As Si Double — We es Mrs Visual ona Je that would hold punibers that Fa watt st sma Y'2976931 48025 ay it's peferable use Double wstet nove yecision eaarmple of delanng a Dobe vai THeve tsan xa Private Sub Yorn Ld Phat Estes As Dable nber canbe a deena ihe Deetmal Panel af snes bow Much re such a V8 Dion sacred As Boule Dine sindenge As Byte Din Tracks As lnteget i popula As Lone pin Disce As Sine Da esa As Comer Other Dats Types ie sre number of days that have elapsed since a date sa unoie wath 7 anne te ns dacrmined Sr ae thal represents che numb {hve elapse may values, oF both, use the wed After the variable has been declared, you will configure st the Hppopate value. THe are two examples [um fyMarnid As Boolean hs Inte in KickOH Fine As Dat Tin So An Ohjeet 1s alos aything else that you want to use in your program, UT you den't pecifya ats type or can Ligure out what dasa type You Want LO URE, YoU EAR USE The Variant keyword or et Visual Basie use the Variant da Variant ’ Vorutt ean be used declare any kind ot varishle, You can use a varnant when you cea! nuke up 9 rind regarding a Vanable bul, as a beginning programmer, you Double When you open Visual Basi fom START men, tien yuck as the fle ment. 'A. New projet 8, Sae aC. Old peel DBA PO inser = New project (Option Ais eorret). VISUAL BASIC Expressions & Operators Expressions in Visual Basic: An expression i ome by imply col and operators. This combination usually involves te use of pareliess range of operation, Examples are wm Yes Where ¥ and 3 are operands and + is en opetor (1D, ABSM-N¢P (It), TOM + 15°2- OHMS. ning operands 1 defie the Rules that Guide the Formation of Expressions in VB: AAll valid VB expressions must be writen in a staigit ine No two or more arithmetic operators ray appear consecutively inthesame expression 1 2 3. Any variable used in VB expression must be a valid V variable, ¢ ANTVB exprensons rust contain at lest one operate the Some expression, then the Ifa character type and numeric expresion app ‘wo expression must he Operators in Visual Base Te compute inp from users and to ps rathentatial operators Is Visual Bas excep ‘Operators are different fom normal msthematial operators, sal, we need to we vari symbols for the shown below Example: (Exponential (S)e.e.2°4=16 (1). Multiplication *) 2-493 AU), Division ic 24 = 3 (IV). Mod: Modutis(rtuen the remainde Eg ISMad4=3 255 nod 10=5 (¥)._ Integer Division(diseards the decimal places) i There are fout main types of operstarsin VD. they a 2 (5t6))2= 00 (2). Arithmetic Operators (6), Character Operators (). Relational Operators (a). Logical Operators (a). Arithmetic Operators: Arithmetic operators are applied expressions, The following arithmetic cpeators are racy Name ‘Addon Subtaction Multiplication Division Exponentiat Parenthesis SQR (x) seu’ ee cy efreshing the order of Ps Order $$ Fo mes Qpersters Ys Evaluatios of functi ans ; Exponentition i Multiplication and Division | 4th Adi 1d Subtraction th shu ten nt won andsubection ate on he sare level therefore, | \ Ts ee ar move rom the lef is treated fist, The same applies ro uirson and ulation, whieh ae on he same level Examples Sale Tete he order of mst th, Bitte {ih wre tion ofthe algebraic relationship of the VB. Working Algebraic Expression Visual Basic Equivalent (meth a), (iy (1), be vb! dic a = (bh SOR (hs? -4*atcyl2%a) ming Pen \ IDs Tolls ' b Tiput tov t ye [tus vcthic prinninyreonteil far entey text in VENTET OUIPML BaNe ): Thisnc user display owput in VB.NET Question 1: C sing Arithmetic Ope Watea Vin teins ta Salve Arithmetic Problems, fn tht rests the iver (o enier amy two mumerie values: say humby sind onal Mom alispstay the restelis of the arithmetic operations, avldimor SMEALTIN. anata stunini he aser inputs 8 andl 2. The Vilisplass ihe ¥ ! Dane \ 2 LO amd 8/2 = 4 in Sueceone gait Wes for entering mucatiens Nat Woe For dixplaying the wutput Solution 10 Question | Dwble-eick the fon ts open the Fanny 2 Inthe Fornt Load procedute, replace ine Procedure code urea EXISUng Code with the followin m% (ao COMPUE RN RUAN -¥R a Pinenumbl AS tueger Dim numb? As theser numb fopul Bey ("Voter the fiest mamber’) numb? Input Bow Enter [he seeond number") the Girst and second lines declared inte and fourth bi S used iny “Assigned to the varia ef vartebles nunbd Put hoses t0 prompt the user bles mint | und ruin? il en? while Ube thitet foenter the values that will be Add the follow ine LoUde-1e eoneatenate the display the huntbers sited sty result one and MsgRox (numb) MseBox (inmmbl a» MseBox (numb & «8 MsgBox (numbt “a nunih2 & * € numh2 & *& numb? & Rumis? & “ & numbl + numb?) © & numbt - nomb2) ~ numb} * gum “8 mucob | / muni) The me: be the operator chan produ s.CoNnCionale ane acters with the cog ed the resulis displays the yalues of num rresponding, nb and numb? and arithmetic ea pressions that Press FS lo nun your program Enter the values of nomt] and numb? sappear, Then click OX an each ot th Terminate the proyram after the | and click OK in-cach case for the input box to seas Rige boxes to display the next and also to last message box. Question Write a "B program thar requests the use reeting 10 the ater e.g the use Rita, how as life "10 enter histher “Rita” and the Bi name and then displays of inputs rogrim displays ™ Helly See itiusiration betaw: Exercise What is your name? wee Hello Rita, how is life? Input box for entering user's name Message box displaying output Solution to Question 2: L Dim Name As Strin ig Name = Input Box (What is your name”) 29 AUERANING 1-08 AN (NE 3 detlared a sring variable pau ¢ Wer to enter a value whit orecond fine uses an inpul box Te wh d fing uses @ vhile ido. the variable name: (@Prompr th splay the resteits* nd display ‘Hl the Following code to concatenate the strings on eT) MsgBox (* Hello” & name & End 4 Press FS to run your program. Question orto enter his name (ast Write a VB programa that requests the user to el th splays his age wil Of bicth, (an anteger) and then computes and display on dis “|92" the program then d assunning the user enters “Tfeama” and 1992" the prog message: “FH [feoma, you are 20 years old.” is/her year ring and bis! a message box e.g plays the Hi Loomis, you are 20 years old. cE aus ln displaying the age Solution to Question 3 1 Double-click the sim, {fo open th 2, Inthe Form) _Load procedure, © Form _Load procedure code area Tpaice the existing code with the following: Dim name As Striny Dim eutrentYear As Integer = wi Dim yearOfBitth Ag Integer Dim age As Inteper Dim mspString Ag String The five lines are deeb, yeurOMBirth, age and msgSicing Tre Second line also assigned the value of 2012 tothe variable currenYean a ane & variable MseSicing to hold the cee far clarity, we foteodoee string vai BSiring to hold the messa, e assi fon to the Msgbox¢) function, ‘BE to be displayed before P Tee ements fOr the Vasiableg name, current¥eaty = InpualBiox (Pleas roe = Awe = Suereny er your name .....") . mutBox (“Please enter your yearOfBirth”) ~ vearO{Birth String = "Hi & name & *, You are“ & age & ears old,” s Then nl the codes to-display the results using the Msgbox () function, MsgBox (msgString) End Press FS to min your program, NC input box and cl eC until vou click OK For Memory refresh 28 ¢ boxes for input data " Corsmnd button for ealewlation ths Outils on the form: they are 2 labels for Prom Sata inputs, | command button for ‘instruction to calculate and then 4 labels for 1 LIKELY Question 1; The primary contro! A. message Inswer | for entering text in Vb NET is the _ box B. input box C. label D. text box nput box. Option Bis correct, Exercise 31 is below prod InputBox(“Enter your reg no”) ead (Enter your reg no:”) Which of the statemer p A. MsgBox("Enter your reg no") C. Write(“Enter your reg 0") 1, Print (“Enter your reg no! Answer = InputBox (“Enter your reg no"), Option B is correct. ucstion 3; eo figure below; ° Answer Questions I to V with the fig What is the value of the text property of the first label control the first Number B.6 €.B D.6+3=9 EB, Calculate. Answer = 0. This is so because 6 is a value inside the text Box for data correspond to the first label correct, alue ofthe text Property of the second label control in Enter the Second Numb Bo C3 Answer =3, Option C is correct SHI. The first label control for A. Enter the first Ny mis Answer D. Calculate E643 = romp! in the Form design er BG ©. Enter th Phier the first Number. Option tj IS Correet. The for cong tals represent D.Lists gE ed by A and B are: Combo Boxes, Aaswer = Labels (Option ¢ is correet) 1V. "The text boxes in the form dec: theshoyg, Some design ae labeled A BC CA pp Ald daswer Option B is corrogt _, Question 4: In VB.NET form desivn, whic form, A-location (7. 1) gives False 2 SE. Greater than 5207-1) gives True ota oF equal to 2 i Not equal to (d). 5# (7-1) gives True Logical Operatars: Lo; statements, Ex gical op: amples are NOT, AND, "Sate Used lo negate, compare or combine NEOV, The order of precedence is as in the above order ex are on the same level, The logicat ‘operators AND. OR, Well as in structuring codes. For intier than or equal “ss than or equal to 30.56 van be expressed as 20.68-< X < 30.56, NOW, there ae two conditions here: 0.65 30 i MS = insp & numb & , Hum += 9 f Loop MsgBox (insg) End C. Do. Loop Until Here, a set of st; aleMenty iy executed y c Lit the TRUE. Notice that; siren PlUre, the statements and so the P Stiutement EXCcutes Bi¥en below: 12> termination condition becomes {est comes at the eng of the execution of the al feast once, The structure of this» ( 40 Do... Loop Until Do Statement | Statement 2 Loop Until (termination condition) Example: Write a VB.NET inclusive using the Do Working: Program that will display even integer between 0 and 30 Loop Until construct De Loop ... Until m numb As Integer = 00 Dim msg As String = “> Do Msg = msg & numb & 4,” numb += 3 Loop Until mum >39 MsgBox (msg) End Loop While... End While Je (continuation condition) While (continuation Statement | condition) Statement | Statement 2 End While "il display even integer between 0. and 39 inclusive + LoopaNn WHILE... END WHILE construct Working While... End While nnumb As Integer =q Dim msg As String ==» Dim numb As Integer = q Do While num <=39 Dim msg As String = =" ile numb <= 30 sg = msg & numb & Bese = mise & numb & «+ numb += 2 numb +=2 Loop End While MsgBox (msg) MsgBox (msg) End End 4] ified number of, is a Spec! i! c The For ... Next construct executes a set oe s wais ina single | tines h specifies a counter-controlled (or definite) rep! of Code, Counter-controlled constructs involves: hat determines whether the loop \L. The control variable (i.e loop counter) # should continue. iable . / The initial value of the control varia - CV) by incrementin ti The is value that modifies the control var! iable ( 18 Or arements 1 variable to deter: WV, eect tests for the final value of the contro cterting when to stop The structure of a For... Next loop is given below; For... Next For initialization To final Value Step stepvalue Statement 1 ‘Statement 2 Next Example: Write a VB.NET program that will display even integer between 0 and 30 inclusive using the For ... Next construct. Working: ve Next Dim msg As String For numb As Integer =9 To 30 step 2 numb = msg & numb &“* Next MsgBox (imsg) End FOR -TO-NEXT ; This construct is a condit cl Monal transfer gp of statements in a specified ee ae Pevified Tumber of times q oo IL used to repeat thas the ¢ Tepeat a statement or block ‘ENERAL form as show? For Control Vatiable = Statement | Lower Limit “mit To Upper 13 itement 2 BP * Limit (step Value) Bg 1 to 10 % (step = Bec Pt) “ NH: From the above, the initial value of the control variable | while the final value is 49, ‘Again, Fot control variable-= Upper limit To Lower limit (Step value negative) Statement | ‘Statement 2 Neal control variable J= 100 To LO CStep = $0) Bg Ford 100 To P= 30) b=F*2 Next J We noticed from the shave that. (1), In For- To ~ Next Statement, [F- (fy ‘The initial value of the e. The initial value oF the If after the final value ( assume that the inetem G. FOR PACH. NEXT This structure executes a struelure such as an array The For Each ... Next us The syntax for a For ea control variable is grea epber or lower limit) Le-no step value is indicated, then it is rented value is serial or equal to one. et than final value, the step size i ch ... Next loop is: For Each .., Next For Each varName In arrayName Statement | 2 Statement Next (iy TF THEN Statement fu) IF -'THEN - ELSE Statement ip FOR - TO -NEXT Statement ") ‘The IF-THEN ‘Statement: The IF -THEN ‘Statement is the simplest selection Mtucture. [1 is used to compare two values for quality in values, A decision is made Sul of the comparison and then appropriate i 43 PERN 0 WN srg A : mn the companson. The FLOWCHART segment (Syntax) form of the 1F -THEN - Statement is given below? the G Statement or Block of statement tement The FLOWCHART segment of the IF - THEN Stat IF (Condition) THEN te | Statement | el Statement 2 END IF The GENERAL form of the IF - THEN statement LIKELY EXAMINATION QUESTIONS One of this ts a repetition structure in VB.NET A. While Until ... Loop 1s While... Wend C, While... Loop D, For... Next E. Until ... While Answer = For ... Next (Option D is correct), Use the program below to answer Question 2-5 3 Dim number! As Integer As Integer Dim Answer As Integer wer = number! + number? msgbox answer Vhatis the function of the above oe, mers C. add two numbers Be Count numbers B. Subset anables can you find in the ame PreBTaM_E, None ee ext is. valid aig Program A.2 By ¢.3 D4 E%" i BAMeNt statem = s s §. mszbox answer -C. pri Sttin VB.NET A. Dim answer B. AML Of the ab Vate sub but + ‘ove ton i 1 Whit 1s the function OF mspbox answy D. answer = answer Swer in he program B. calculate pesufy Of the the above program? A. hi result Program Cj gram? A. hid display result of the (Cir: OPT PORNO A STUN Ae OES f program 1. Assign result of answer E. Done nothing Answers . 2 Add twonumbers 3. 2 variables 4D answer = answer] + answer? 5 Display result of the program © Which of the following repetition constructs tests for a loop continuation condition, A. Do Until... Loop B. Do... Loop Until C. While ... End While D. While. Wend B Do... Until WI Answer = While ... End While : Answer Question 7-9 with the program below; S ‘Dim numb, sum As Integer =0 2. Do Untit pumb = -1 8. numb = InputBiox (“Enter number") 4 Sum += numb 4 5. Loop . 6, MsgBox ( “the sum is: m) 7. Bt 4 Low many variables are declared in the program. A.6 B.4. C. 2D.0 £2 4 Which of the lines in the Program displays the output. A. Line 6 B. Line 8 C-Lines 2.4&7 D. Line? B. Only line 5 9 he Loop termination condition in the program is A, Do Until B, numb < 10 C. Loop B.numb+=2 E-none of the above Ancwers: TC 2 RA Lineg es 9% Do Until ‘newer Questions 10-12 with the program below Din nami As Integer=0 2, (in mise As Striny se % Do tse = mse & num & eunib + ved in the program. A.6 B.4 C.2D.0 B-2 the Imes in the Progr ram displays the out ( put A. Line 6 B. Line 8 Lines .4&7 Do Line? E Only line 5 12 Vhe Loop continuation condition im the Program is A. Do B. numb <= 39 C. Loop While Donumb+=2 none of the above laswers: We 2 ND Line? 12.¢ Loop While 45 Se OF ARR oe a group of data elements referenced by the same name. It is ction of items which will not allow the mixing of hamogEnOO Are so, an array is @ consecutive set of meméry Hehe of differen ean of two or more adjacent memory cells, called array elemen ee sociated witha symbolic (variable) name Array has the comin? that are asso that single variable can represent multiple data items, Atta characterise ations in Which one may need to save data items fe ed in many applic i are See ‘An array could be one-dimensional or multi- ‘Su! dimensional ‘ONS, i.e Defining/Declaring And Referencing Arrays. — ; Before any array 18 ed ina program, the compiler or {nterpreter has to be informed lo reserve particular number of adjacent memory cells and associate them with a variable name. In VB, Dimension statement written DIM is used ty declarefdefine an array. ie Dim values () As Integer Anartay variable values has been declared by putting parenthesis after the variable name. Noticed that the statement above creates a set of adjacent memory focations named valves for storing integer type values as shown below values () CITTTT TTT tit | 3 4 4 6 7 8 Qe ee TET number of values to be stored was net nbers below the memory locations are ed. However, if the number of values to be n be specified, ie ared above ig 12. 3 12. Ther s ; nib @ ‘ With one less tho ree Of Values, or afore, it can Siore 12 integer value Contains the lame ae Auber speciieg euch Starting with clement and a roug ¢ © declaration elements. Assuming Y° 46 ——. data of ations, ie clements, s. Arrays ms for IS to be edn rer erm en the 9th vé rou — Yrent 5, to Ferere Wt: wait 10 20 Wereference the oth values faference element 8. o ARRAY ELEM! below’ ANG VALUES T ass Ne the flowing Oe Values (1) = + ext) Values (3) =7 sent of the array (INGEX sed to the fist elemento ue shove end, the value He sig ane an) ere that the array element ne a ce end be out dre te geet andthe val ethan side of he assignens OP 2 seelre ana assign waves €2 am aFTAY C8 a single fine as shown BELOW: poim values () AS Tat 17 be 28 13) se, the ey texan inate sistas TH VETS are assigned 10 iach nda sae ofthe aay is no seeicd Tt Tied esp hat yu ist, For stan, the size of the apray ( : sex dome dimensional aray ean be thought of as a ist Senter sume type that are collectively referred sje pnwviles a natural extension of one-dimensional array, Taina) of data items. The multi- sre subscript (index) following the array ny comune If tbe array has two subscripts towsnded 489 two-dimensional array. On the pis followin e, the array is : von, nea ink of 0 dimensional \o sows and columns, Similarly, a three ‘ 3, like pages in a book a . SOS Da Be eas Boe Soe Osa! Er 4 E infinity —_— wo en 9 TOE B. Iwo: E. None of thi inswers Bo Morking. IF Array Value |. “Index hus ove, the lowest index of the array value (i,¢ 5) is 0. Option E is 4 (Note that she array values are {5, 8,0, 6,1}, thus; the highest index of the array $4 Option D is correct number of elements in the srray is 5). Option B is correct. QUESTION 2 of values of the same type is called E. Form

You might also like